Repair a truncated JSON tool call from a streaming model

HardAgentsPro

Why it matters Agent frameworks recover from cut-off streaming tool calls with this kind of repair instead of re-running an expensive generation.

Streaming models often stop mid-object (max tokens, a dropped connection), leaving a tool call like {"name": "search", "args": {"q": "kaf. An agent can often still recover it.

Write repair_json(text). Return a dict or None.
1. Start at the first "{" in text (None if there is none).
2. Scan characters, tracking whether you are inside a string (a backslash escapes the next character) and a stack of open "{" and "[". If the stack becomes empty, the object is complete: cut the text right there (ignore anything after it) and parse.
3. If the text ends first: if inside a string, drop a dangling backslash and close the string with a quote. Then strip trailing whitespace; remove one trailing ","; if it now ends with ":", append " null". Then append the closers for the open stack in reverse order.
4. Parse with json.loads. Return the result if it is a dict, else None; return None on any parse error.

Signaturedef repair_json(text)

Example

repair_json('{"name": "search", "args": {"q": "kafka') gives {'name': 'search', 'args': {'q': 'kafka'}}.

Understand the idea

When a model streams a JSON tool call and gets cut off, the text is usually almost right: a string is left open and a few brackets are missing. Repair means finishing the text the way the model would have.

Think of brackets as nested boxes: the last box you opened must be the first one you close. A stack captures this exactly. Example: '{"args": {"xs": [1, 2' opened "{", "{", "[" in that order, so we close with "]", "}", "}". If we were inside a string, we first close it with a quote. A trailing comma is dropped and a dangling colon gets null.

Rules: scan with (in_string, escape, stack); if the stack empties, cut; else close string, tidy, append reversed closers; then json.loads.

Agent runtimes use repairs like this to avoid wasting a whole generation on a truncated tool call, and partial JSON parsers in streaming UIs rely on the same stack idea.

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

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

  • Sample 1: examplerepair_json('{"name": "search", "args": {"q": "kafka')
  • Sample 2: list then commarepair_json('Sure! {"tool": "calc", "xs": [1, 2, ')