Tool-Call Parse + Schema Validation
Background
LLM-emitted tool calls need argument validation before dispatch. A wrong tool name, missing required field, or wrong type means the downstream tool call will crash or — worse — silently do the wrong thing. Production agent stacks parse and validate against a schema before invoking any function.
Problem statement
Implement validate_tool_call(text, schema). Parse the JSON in text; verify name matches schema["name"]; for each declared arg, check required-ness and type. Return the parsed dict on success or raise ValueError.
Schema shape:
{"name": "search", "args": [{"name": "q", "type": "str", "required": True}]}
Supported types: "str", "int", "float" (accepts int too), "bool".
Input
text—str, the LLM-emitted JSON. Expected shape{"name": ..., "args": {...}}.schema—dictdescribing the tool. Must havename: strandargs: list[dict]with keysname,type,required.
Output
Returns the parsed dict (same structure as the input JSON) on validation success.
Examples
Example 1 — valid call
Input:
text = '{"name":"search","args":{"q":"hi"}}'
schema = {"name": "search", "args": [{"name": "q", "type": "str", "required": True}]}
Output: {"name": "search", "args": {"q": "hi"}}
Example 2 — wrong tool name
Input: schema expects "search", JSON name is "other"
Output: ValueError
Example 3 — missing required field
Input: required arg q absent
Output: ValueError
Example 4 — wrong type
Input: expected int, got "abc"
Output: ValueError
Constraints
- Malformed JSON →
ValueError(notJSONDecodeErrorleak). boolis a separate type — don't acceptintforbool.- Extra args not declared in the schema are tolerated (not flagged) — matches OpenAI's default behaviour.
Notes
- Why eager validation. Better to fail with a clear
ValueErrorhere than to invoke the tool with bad args and get a cryptic downstream stack trace. - JSON Schema. Real systems use full JSON Schema with nested objects, enums, and constraints; this kernel covers the 80% case.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference valid call returns parsed dict
- •Example optional arg omitted still valid
- •Sample float arg accepts an int value