Sub topic 15
Validating arguments before running the tool
This chapter assumes you can read short Python examples, work with JSON, and know basic JSON Schema types. It also assumes you have seen the tool-calling loop, where the model emits a tool call and your code runs it.
Why the schema is not enough
A schema tells the model what arguments to send. It does not force the model to send them. The model generates text that usually matches your schema, but it can still produce a wrong type, a missing field, an invented ID, or a value outside your enum. Some providers can constrain output to the schema, and support varies, so do not rely on it.
Treat model-generated arguments like any other untrusted input from a client. Check them on the server before you act on them.
What to check
- Shape. Is the argument the right type? Are required fields present? Are unknown fields rejected?
- Values. Is the enum value allowed? Is the number in range? Does the date parse?
- Meaning. Does the ID exist? Does it belong to the current user? Is this action allowed for them?
The third check matters most. The model may send a valid-looking customer_id that belongs to someone else. Authorization comes from your session, not from the model's arguments.
Where validation sits in the loop
A validating wrapper
The code below checks arguments against the search_orders schema from earlier in the tutorial. It uses the jsonschema package (pip install jsonschema), then adds a check that the schema cannot express.
from datetime import date
from jsonschema import Draft202012Validator
SEARCH_ORDERS_SCHEMA = {
"type": "object",
"properties": {
"customer_id": {"type": "string"},
"status": {
"type": "string",
"enum": ["pending", "shipped", "delivered", "cancelled"],
},
"created_after": {"type": "string"},
"limit": {"type": "integer", "minimum": 1, "maximum": 50},
},
"required": ["customer_id"],
"additionalProperties": False,
}
validator = Draft202012Validator(SEARCH_ORDERS_SCHEMA)
def validate_search_orders(args: dict, session_customer_id: str) -> dict | None:
"""Return an error result, or None if the arguments are acceptable."""
problems = []
for error in validator.iter_errors(args):
where = ".".join(str(p) for p in error.path) or "arguments"
problems.append(f"{where}: {error.message}")
if problems:
return {"is_error": True, "message": "Invalid arguments. " + "; ".join(problems)}
if args["customer_id"] != session_customer_id:
return {
"is_error": True,
"message": "customer_id does not match the signed-in customer. "
"Use the ID the user gave you, or ask them for it.",
}
if "created_after" in args:
try:
date.fromisoformat(args["created_after"])
except ValueError:
return {
"is_error": True,
"message": f"created_after {args['created_after']!r} is not a valid "
"YYYY-MM-DD date.",
}
return None
if __name__ == "__main__":
print(validate_search_orders({"customer_id": "cus_4821", "limit": 500}, "cus_4821"))
print(validate_search_orders({"customer_id": "cus_4821", "created_after": "2026-13-01"}, "cus_4821"))
print(validate_search_orders({"customer_id": "cus_4821", "status": "shipped"}, "cus_4821"))The first call fails the maximum check, the second fails the date parse, and the third returns None.
Write errors the model can use
Validation failures go back to the model as tool results, so write them for the model. Say which argument failed, what a valid value looks like, and what to do next. Collect all problems in one message so the model can fix them in a single retry. Do not echo internal details such as stack traces or database errors.
Common mistakes
- Trusting
enumandmaximumbecause they are in the schema. - Accepting extra fields silently. Set
additionalPropertiestofalseand reject them. - Checking format but not ownership.
- Returning "Invalid input" with no detail, which leaves the model guessing.
Exercise
The model calls getorder with orderid "ord_9999", which matches your schema's pattern. Which kind of check catches the case where that order belongs to a different customer, and why can't the schema do it?
Show answer
The meaning check (authorization). It needs the signed-in user and your data, and the schema only describes the shape of one argument. Look the order up on the server, compare its owner with the session's customer, and return an error message if they differ.