Extract a JSON tool call from messy model output

MediumAgentsPro

Models asked to emit a tool call in JSON often wrap it in prose, code fences, or extra braces. A robust agent finds the first valid call object instead of failing on the first parse error.

Write extract_tool_call(text). Scan the text for '{' characters from left to right. For each one, find its matching '}' by counting depth, while ignoring braces inside JSON strings (strings start and end with an unescaped double quote, and a backslash escapes the next character). If the slice parses with json.loads into a dict that has a string "name" and an "arguments" field, return (name, arguments). If "arguments" is itself a string, json.loads it too; it must end up a dict. Otherwise continue with the next '{' AFTER the start of the one that failed (so nested objects are also tried).
Return ("", {}) if nothing valid is found. You may import json.

Signaturedef extract_tool_call(text)

Example

'Sure. {"name": "search", "arguments": {"q": "a}b"}} done' returns ("search", {"q": "a}b"}).

Understand the idea

Models asked for a JSON tool call often wrap it in chatter, code fences or stray braces. A robust parser tries each '{' in turn, finds its matching '}' by counting depth, and checks whether that slice is a valid call. The catch: braces inside JSON strings do not count, and a backslash escapes the next character, so a quote after a backslash does not end the string. Worked example: text 'Use {bad} then {"name": "f", "arguments": "{\"x\": 1}"}'. The first '{' matches '}' after 'bad'; json.loads fails, so move to the next '{'. That one spans the full call; the braces inside the arguments string are skipped while counting. It parses to a dict with name 'f', and arguments is a string, so parse it again to get {'x': 1}. Return ('f', {'x': 1}). Rule: for each '{' left to right, track depth outside strings, toggle in-string on unescaped quotes, cut at depth 0, json.loads the slice, accept a dict with a string 'name' and dict (or JSON-string dict) 'arguments'; otherwise try the next '{' after this start. Nothing valid gives ('', {}). Used in agent runtimes that parse tool calls from raw model text.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: brace inside a stringextract_tool_call(_t1)
  • Sample 2: prose braces and string argumentsextract_tool_call(_t2)