DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Fix JSON parsing for triple-quoted Python strings
TejasD-13987d11d6afec
diff --git a/src/agents/solve/utils/json_utils.py b/src/agents/solve/utils/json_utils.pyindex 010610f6b..b7dc97f93 100644--- a/src/agents/solve/utils/json_utils.py+++ b/src/agents/solve/utils/json_utils.py@@ -1,7 +1,9 @@#!/usr/bin/env python"""JSON Utils - JSON parsing utilities-Specifically for extracting and parsing JSON data from LLM output, supports Markdown code block processing+Specifically for extracting and parsing JSON data from LLM output,+supports Markdown code block processing and is robust to Python+triple-quoted strings generated by LLMs."""import json@@ -9,26 +11,48 @@ import refrom typing import Any+def _escape_triple_quoted_strings(text: str) -> str:+ """+ Convert Python triple-quoted strings (\"\"\" ... \"\"\")+ into JSON-safe escaped strings.++ This fixes cases where LLMs generate Python code inside JSON,+ which would otherwise violate JSON syntax.+ """++ def replacer(match: re.Match) -> str:+ content = match.group(1)+ # json.dumps safely escapes newlines and quotes+ return json.dumps(content)++ pattern = re.compile(r'"""([\s\S]*?)"""')+ return pattern.sub(replacer, text)++def extract_json_from_text(text: str) -> dict[str, Any] | list[Any] | None:"""- Extract JSON object or array from text+ Extract JSON object or array from text.- Supports the following formats:- 1. Code blocks wrapped in ```json ... ```- 2. Code blocks wrapped in ``` ... ```+ Supports:+ 1. ```json ... ``` code blocks+ 2. ``` ... ``` code blocks3. Pure JSON text+ 4. JSON containing Python triple-quoted strings (sanitized)Args:text: Original text containing JSONReturns:- Parsed JSON object (dict) or array (list), returns None if parsing fails+ Parsed JSON object (dict) or array (list),+ or None if parsing fails."""if not text:return None+ # 🔧 FIX: sanitize triple-quoted strings before any JSON parsing+ text = _escape_triple_quoted_strings(text)+# 1. Try matching Markdown code blocks- # Match ```json {...} ``` or ``` {...} ```code_block_pattern = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```")match = code_block_pattern.search(text)@@ -37,36 +61,16 @@ def extract_json_from_text(text: str) -> dict[str, Any] | list[Any] | None:try:return json.loads(json_str)except json.JSONDecodeError:- # If parsing fails in code block, may contain comments or illegal characters, try cleaning- # Can add more complex cleaning logic here, currently keep original and try next methodpass- # 2. If no code block or code block parsing failed, try finding JSON structure in entire text- # Find outermost {...} or [...]-- # Remove possible comments // ... or # ... (simple handling)- # Note: This may mistakenly delete content in URLs or strings, use with caution.- # Do not aggressively remove comments, rely on LLM output standards.-- # Find first { or [- start_idx = -1- stack = []-- # Scan for valid JSON start and end- # This is a simplified search, assuming JSON is the main part of the text-+ # 2. Try parsing the full text directlytry:- # Try direct parsingreturn json.loads(text)except json.JSONDecodeError:pass- # Use regex to find outermost {} or []- # dotall mode+ # 3. Try extracting outermost JSON objectjson_obj_pattern = re.compile(r"\{[\s\S]*\}")- json_arr_pattern = re.compile(r"\[[\s\S]*\]")-- # Prefer finding objectmatch_obj = json_obj_pattern.search(text)if match_obj:try:@@ -74,7 +78,8 @@ def extract_json_from_text(text: str) -> dict[str, Any] | list[Any] | None:except json.JSONDecodeError:pass- # Find array+ # 4. Try extracting outermost JSON array+ json_arr_pattern = re.compile(r"\[[\s\S]*\]")match_arr = json_arr_pattern.search(text)if match_arr:try:@@ -82,17 +87,11 @@ def extract_json_from_text(text: str) -> dict[str, Any] | list[Any] | None:except json.JSONDecodeError:pass- # 3. Try fixing common LLM JSON errors (e.g., trailing commas)- # This is a relatively complex task, can use specialized libraries like json_repair,- # but to avoid introducing new dependencies, do simple string processing here-return Nonedef clean_json_string(json_str: str) -> str:"""- Clean JSON string, remove common illegal characters+ Clean JSON string by removing illegal control characters."""- # Remove control characters- json_str = re.sub(r"[\x00-\x1f\x7f-\x9f]", "", json_str)- return json_str+ return re.sub(r"[\x00-\x1f\x7f-\x9f]", "", json_str)diff --git a/tests/agents/solve/utils/test_json_utils.py b/tests/agents/solve/utils/test_json_utils.pynew file mode 100644index 000000000..dd377e573--- /dev/null+++ b/tests/agents/solve/utils/test_json_utils.py@@ -0,0 +1,39 @@+import pytest+from src.agents.solve.utils.json_utils import extract_json_from_text+++def test_extract_json_with_triple_quoted_python_code():+ raw = '''+ {+ "tool_calls": [+ {+ "type": "code_execution",+ "query": """+def foo():+ print("hello")+"""+ }+ ]+ }+ '''++ parsed = extract_json_from_text(raw)++ assert parsed is not None+ assert isinstance(parsed, dict)+ assert "tool_calls" in parsed+ assert parsed["tool_calls"][0]["type"] == "code_execution"+ assert "def foo" in parsed["tool_calls"][0]["query"]++++# How to run the test+# From repo root:+# pytest+++# Or just this test:+# pytest tests/agents/solve/utils/test_json_utils.py++# Expected output+# 1 passed\ No newline at end of file