InterviewPrepKit

Home / Coding / Agent Coding / Tools & Function Calling / Parsing a Tool Call from Model Output

Parsing a Tool Call from Model Output

medium 00:00
Solving tips
  • Models rarely return clean JSON — they wrap it in prose or a ```json fence, so strip the wrapper before parsing.
  • Scan for the first balanced {...} block instead of trusting a regex; nested objects break naive patterns.
  • Fail loudly with a structured error the loop can inspect, not by raising deep inside your parser.

Language models are told to respond with a JSON tool call, but they do not always cooperate. They add a sentence before it, wrap it in a Markdown ```json fence, or emit malformed text. Before your agent loop can dispatch a tool, it has to reliably pull the tool call out of that raw string. This parsing-and-validation step is where a surprising number of agents break in production.

Task

Complete parse_tool_call(text: str) -> dict:

  1. Locate the first JSON object in text. It may be surrounded by prose, or fenced in a json ... (or plain ...) block. Handle both.
  2. Parse that object. It must contain a string "name" and a dict "arguments" (treat a missing "arguments" as an empty dict {}).
  3. On success return {"ok": True, "name": <str>, "arguments": <dict>}.
  4. On any failure — no JSON object present, invalid JSON, missing/non-string name, or non-dict arguments — return {"ok": False, "error": <clear message>}. Do not raise.

To find the first object, scan for a { and track brace depth (accounting for braces inside string literals) until it balances; then hand that substring to json.loads.

Example

raw = 'Sure! Here is the call:\n```json\n{"name": "search", "arguments": {"q": "cats"}}\n```\nHope that helps.'

parse_tool_call(raw)
# -> {"ok": True, "name": "search", "arguments": {"q": "cats"}}

parse_tool_call("I cannot help with that.")
# -> {"ok": False, "error": "no JSON object found"}

Constraints

  • No third-party libraries; json from the standard library only.
  • The parser must never raise on bad input — every failure path returns the error dict.
  • A { that appears inside a JSON string value (for example {"q": "a { b"}) must not throw off brace counting.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug