Skip to content

Commit 57c5c39

Browse files
committed
🐛(backend) improve sanitizer ai_services
The json response of the AI service is badly formatted. This commit improves the sanitizer to try to handle the response correctly.
1 parent be6da38 commit 57c5c39

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/backend/core/services/ai_services.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,17 @@ def call_ai_api(self, system_content, text):
6969
content = response.choices[0].message.content
7070

7171
try:
72-
sanitized_content = re.sub(r"(?<!\\)\n", "\\\\n", content)
72+
sanitized_content = re.sub(r'\s*"answer"\s*:\s*', '"answer": ', content)
73+
sanitized_content = re.sub(r"\s*\}", "}", sanitized_content)
74+
sanitized_content = re.sub(r"(?<!\\)\n", "\\\\n", sanitized_content)
7375
sanitized_content = re.sub(r"(?<!\\)\t", "\\\\t", sanitized_content)
7476

7577
json_response = json.loads(sanitized_content)
7678
except (json.JSONDecodeError, IndexError):
77-
json_response = json.loads(content)
79+
try:
80+
json_response = json.loads(content)
81+
except json.JSONDecodeError as err:
82+
raise RuntimeError("AI response is not valid JSON", content) from err
7883

7984
if "answer" not in json_response:
8085
raise RuntimeError("AI response does not contain an answer")

0 commit comments

Comments
 (0)