#452Tool-Call Parse + Schema ValidationMedium

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

  • textstr, the LLM-emitted JSON. Expected shape {"name": ..., "args": {...}}.
  • schemadict describing the tool. Must have name: str and args: list[dict] with keys name, 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 (not JSONDecodeError leak).
  • bool is a separate type — don't accept int for bool.
  • 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 ValueError here 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.
Python
Loading...

▶ 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