Flatten tool JSON extraction
Keep the valid-tool-root preference added for streamed snapshots, but avoid collecting and re-walking parsed candidates. Remember the first parsed object/root while scanning and use a small predicate for tool-request recognition.
Alessandro committed
Jun 25, 2026 at 21:49 UTC
eab40dc1210fc19db5347eeae81ba387cbc40a38
1 file changed
+22
-21
helpers/extract_tools.py
+22
-21
@@ -8,20 +8,16 @@ def json_parse_dirty(json: str) -> dict[str, Any] | None:
8
if not json or not isinstance(json, str):
9
return None
10
11
- parsed_candidates: list[dict[str, Any]] = []
11
+ first_data: dict[str, Any] | None = None
12
for ext_json in extract_json_root_strings(json.strip()):
13
data = _parse_json_root_object(ext_json)
14
- if data is not None:
15
- parsed_candidates.append(data)
16
- for data in parsed_candidates:
17
- try:
18
- normalize_tool_request(data)
19
- return data
20
- except ValueError:
14
+ if data is None:
15
continue
22
- if parsed_candidates:
23
- return parsed_candidates[0]
24
- return None
16
+ if first_data is None:
17
+ first_data = data
18
+ if _is_tool_request(data):
19
+ return data
20
+ return first_data
21
22
23
def normalize_tool_request(tool_request: Any) -> tuple[str, dict]:
@@ -50,17 +46,14 @@ def normalize_tool_request(tool_request: Any) -> tuple[str, dict]:
46
47
48
def extract_json_root_string(content: str) -> str | None:
53
- roots = extract_json_root_strings(content)
54
- for root in roots:
49
+ first_root: str | None = None
50
+ for root in extract_json_root_strings(content):
51
+ if first_root is None:
52
+ first_root = root
53
data = _parse_json_root_object(root)
56
- if data is None:
57
- continue
58
- try:
59
- normalize_tool_request(data)
60
- except ValueError:
61
- continue
62
- return root
63
- return roots[0] if roots else None
54
+ if data is not None and _is_tool_request(data):
55
+ return root
56
+ return first_root
57
58
59
def extract_json_root_strings(content: str) -> list[str]:
@@ -96,6 +89,14 @@ def _parse_json_root_object(root: str) -> dict[str, Any] | None:
89
return data if isinstance(data, dict) else None
90
91
92
+def _is_tool_request(data: dict[str, Any]) -> bool:
93
+ try:
94
+ normalize_tool_request(data)
95
+ except ValueError:
96
+ return False
97
+ return True
98
+
99
+
100
def extract_json_object_string(content):
101
start = content.find("{")
102
if start == -1: