Add speaking endpoints and clean code.

This commit is contained in:
Cristiano Ferreira
2023-06-23 00:05:48 +01:00
parent a67f02ed78
commit 4e1ad6dc67
9 changed files with 274 additions and 89 deletions

View File

@@ -1,6 +1,7 @@
import json
import openai
import os
import re
from dotenv import load_dotenv
@@ -16,15 +17,25 @@ TRY_LIMIT = 1
try_count = 0
def process_response(input_string):
json_obj = {}
parsed_string = input_string.replace("'", "\"")
parsed_string = parsed_string.replace("\n\n", " ")
try:
json_obj = json.loads(parsed_string)
except json.JSONDecodeError:
print("Invalid JSON string!")
if '{' in input_string:
try:
# Find the index of the first occurrence of '{'
index = input_string.index('{')
# Extract everything after the first '{' (inclusive)
result = input_string[index:]
return json_obj
parsed_string = result.replace("\"", "\\\"")
pattern = r"(?<!\w)'|'(?!\w)"
parsed_string = re.sub(pattern, '"', parsed_string)
parsed_string = parsed_string.replace("\\\"", "'")
parsed_string = parsed_string.replace("\n\n", " ")
json_obj = json.loads(parsed_string)
return json_obj
except json.JSONDecodeError:
print("Invalid JSON string!")
else:
return input_string
def check_fields(obj, fields):
return all(field in obj for field in fields)
@@ -42,7 +53,7 @@ def make_openai_call(messages, token_count, fields_to_check, temperature):
processed_response = process_response(result["choices"][0]["message"]["content"])
if check_fields(processed_response, fields_to_check) is False and try_count < TRY_LIMIT:
try_count = try_count + 1
return make_openai_call(messages, token_count, fields_to_check)
return make_openai_call(messages, token_count, fields_to_check, temperature)
elif try_count >= TRY_LIMIT:
try_count = 0
return result["choices"][0]["message"]["content"]