fix(agent/json_utils): Make extract_dict_from_response more robust

* Accommodate for both ```json and ```JSON blocks in responses
This commit is contained in:
Reinier van der Leer
2024-01-29 15:03:09 +01:00
parent ab860981d8
commit 25b9e290a5

View File

@@ -9,13 +9,11 @@ logger = logging.getLogger(__name__)
def extract_dict_from_response(response_content: str) -> dict[str, Any]: def extract_dict_from_response(response_content: str) -> dict[str, Any]:
# Sometimes the response includes the JSON in a code block with ``` # Sometimes the response includes the JSON in a code block with ```
pattern = r"```([\s\S]*?)```" pattern = r"```(?:json|JSON)*([\s\S]*?)```"
match = re.search(pattern, response_content) match = re.search(pattern, response_content)
if match: if match:
response_content = match.group(1).strip() response_content = match.group(1).strip()
# Remove language names in code blocks
response_content = response_content.lstrip("json")
else: else:
# The string may contain JSON. # The string may contain JSON.
json_pattern = r"{[\s\S]*}" json_pattern = r"{[\s\S]*}"