Parse response values, when they are JSON.

This commit is contained in:
OK
2023-03-30 15:38:42 +02:00
parent c7d89333ad
commit 585ecc17c6
3 changed files with 59 additions and 3 deletions
+21 -2
View File
@@ -29,6 +29,25 @@ def parse_response(content: str) -> Dict:
raise err
def parse_maybe_json(json_string):
try:
# Attempt to parse the string as JSON
parsed_json = parse_response(json_string)
except Exception:
# If it fails, return the original string unchanged
return json_string
# If the parsed JSON is a list or dictionary, concatenate its values as a string
if isinstance(parsed_json, (list, dict)):
concatenated_values = []
for value in parsed_json.values() if isinstance(parsed_json, dict) else parsed_json:
concatenated_values.append(str(value))
return '\n'.join(concatenated_values)
# If the parsed JSON is a string, return it
return str(parsed_json)
class AIMessageBase(object):
def __init__(self) -> None:
pass
@@ -108,8 +127,8 @@ class AIResponder(object):
response['answer'] = str(response['answer'])
return AIResponse(response['answer'],
response['answer_needed'],
response['staff'],
response['picture'],
parse_maybe_json(response['staff']),
parse_maybe_json(response['picture']),
response['hack'])
def short_path(self, message: AIMessage, limit: int) -> bool: