Sub topic 8
Validating arguments before you run anything
This chapter assumes you can read JSON Schema, know the message flow of a tool call, and have a dispatcher like the one in the previous chapter. It adds a check between "the model proposed a call" and "your function runs".
Why the model's arguments are untrusted input
The model writes tool arguments as text. Your code parses that text and passes it to a function. Nothing guarantees the arguments match your schema. Models can omit required fields, invent extra ones, send a string where you expect a number, or pick a value outside an enum. Treat the arguments like input from a web form: validate them at the boundary.
Some providers offer a strict mode that constrains output to the schema. Even then, the schema only checks shape. It cannot tell you whether a file path is safe or a user ID belongs to the current user.
Two layers of checks
- Schema validation checks shape: types, required fields, enum values, unknown keys.
- Business validation checks meaning: ranges, ownership, allowed paths, and anything the schema cannot express.
Run both before the tool executes.
Schema validation with jsonschema
The jsonschema package checks arguments against the same schema you sent to the model. Install it with pip install jsonschema.
import json
from jsonschema import Draft202012Validator
WEATHER_SCHEMA = {
"type": "object",
"properties": {
"city": {"type": "string", "minLength": 1},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
"additionalProperties": False,
}
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {
"get_weather": {"fn": get_weather, "schema": WEATHER_SCHEMA},
}
def validate_arguments(schema, arguments):
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(arguments), key=lambda e: list(e.path))
return [
(".".join(str(p) for p in e.path) or "(root)") + ": " + e.message
for e in errors
]
def run_tool_call(call):
tool = TOOLS.get(call["name"])
if tool is None:
return {"is_error": True, "content": "Unknown tool: " + str(call["name"])}
arguments = call["arguments"]
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError as exc:
return {"is_error": True, "content": "Arguments are not valid JSON: " + str(exc)}
problems = validate_arguments(tool["schema"], arguments)
if problems:
return {"is_error": True, "content": "Invalid arguments: " + "; ".join(problems)}
try:
result = tool["fn"](**arguments)
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
return {"is_error": False, "content": json.dumps(result)}
print(run_tool_call({"name": "get_weather", "arguments": {"city": "Oslo"}}))
print(run_tool_call({"name": "get_weather", "arguments": {"unit": "kelvin"}}))The first call succeeds. The second returns an error listing both problems: unit is not in the enum, and city is missing. Some providers send arguments as a JSON string rather than an object, so the dispatcher parses strings first.
Business validation
Add checks that depend on your application. For a file-reading tool, confirm the resolved path stays inside an allowed directory:
from pathlib import Path
ALLOWED_ROOT = Path("/srv/docs").resolve()
def check_path(raw_path):
resolved = (ALLOWED_ROOT / raw_path).resolve()
if not resolved.is_relative_to(ALLOWED_ROOT):
return "Path is outside the allowed directory"
return NoneA path like ../../etc/passwd passes a "type": "string" check. Only the business rule stops it.
Writing error messages the model can use
Exercise
A model sends {"city": "Oslo", "units": "celsius"} to a tool whose schema sets "additionalProperties": false. What should your validator do, and why is that better than passing the arguments to the function directly?
Show answer
The validator should reject the call and return an error such as "Additional properties are not allowed ('units' was unexpected)". Passing the arguments directly would raise a TypeError inside the function, or the misspelled key could be silently ignored so the model never learns its mistake. A clear error lets the model retry with "unit".
Exercise
Why is a path like "../../etc/passwd" a business validation problem and not a schema problem?
Show answer
It is a valid string, so it satisfies the type check. Whether it is acceptable depends on your application's rules about which directories the tool may read, which a schema cannot express. You must resolve the path and check it against the allowed root in code.