Sub topic 15
Validating Arguments Before Running the Tool
This chapter assumes you can read short Python examples and JSON Schema, and that you have already written a tool definition with a name, description, and input schema. Here you will learn why a schema alone does not protect your tool, and how to check model-produced arguments on the server before you act on them.
Why the schema is not enough
A tool schema tells the model what to send. It does not force the model to send it. The model generates arguments as text, and your code receives whatever it produced. Several things can go wrong even with a well-written schema:
- The model omits a required field or invents a field that is not in the schema.
- The model sends the wrong type, such as
"10"where you asked for an integer. - The model sends a value outside a bound, such as
limit: 500when the maximum is 50. - The model sends a plausible but wrong value, such as an ID in the wrong format or an ID for a record that does not exist.
- Some providers and modes do not enforce the schema at all. Others enforce only part of it, as the chapter on provider differences explains.
There is also a second source of bad input. The model reads the user's message, tool results, and web pages. Text in any of those can steer the arguments. So treat arguments the way you treat any input that crosses a trust boundary: as untrusted until checked.
Where validation sits in the loop
Validation happens after the model emits a tool call and before your function runs. If a check fails, you do not run the tool. You return an error result that the model can read, and the loop continues.
The error goes back as a normal tool result, usually marked as an error. This lets the model correct itself in the next turn instead of the whole request failing.
Three layers of checks
Think of validation as three layers, from cheapest to most specific.
- Shape. Is the input an object? Are required fields present? Are the types right? Are there unknown fields?
- Constraints. Does each value satisfy the enum, range, length, and format rules from the schema?
- Meaning. Does the value make sense in your system? Does the record exist? Does this user have permission to touch it? Is the date range sensible?
The first two layers can be automated from the schema you already wrote. The third is code only you can write.
Shape and constraints with a schema validator
Reuse the same JSON Schema you sent to the model. The jsonschema library checks it for you, so the definition and the enforcement cannot drift apart.
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", "pattern": r"^\d{4}-\d{2}-\d{2}$"},
"limit": {"type": "integer", "minimum": 1, "maximum": 50},
},
"required": ["customer_id"],
"additionalProperties": False,
}
validator = Draft202012Validator(SEARCH_ORDERS_SCHEMA)
def schema_errors(args) -> list[str]:
"""Return a readable message for each schema violation."""
messages = []
for err in sorted(validator.iter_errors(args), key=lambda e: list(e.path)):
where = ".".join(str(p) for p in err.path) or "(top level)"
messages.append(f"{where}: {err.message}")
return messages
if __name__ == "__main__":
print(schema_errors({"customer_id": "cus_4821", "limit": 500, "color": "red"}))
print(schema_errors({"limit": "10"}))Running this prints the problems for each bad input, for example that 500 is greater than the maximum of 50, that color is an unexpected additional property, and that customer_id is required. Install the library with pip install jsonschema.
Note additionalProperties: False. Without it, the validator accepts invented fields and your code silently ignores them. That hides a real problem: the model thinks it passed a filter that your tool never applied.
Meaning checks in your own code
Schema validation cannot know that cus_9999 does not exist. Write those checks in the tool function, as in this example from earlier in the tutorial.
ORDERS = {
"ord_1001": {"id": "ord_1001", "status": "shipped", "total": 42.5},
}
def get_order(order_id: str) -> dict:
if not isinstance(order_id, str) or not order_id.startswith("ord_"):
return {
"is_error": True,
"message": (
f"Invalid order_id {order_id!r}. IDs look like 'ord_1001'. "
"If you do not have an ID, call search_orders first."
),
}
order = ORDERS.get(order_id)
if order is None:
return {
"is_error": True,
"message": f"No order found with id {order_id!r}. Check the ID with the user or use search_orders.",
}
return {"is_error": False, "order": order}Each failure names the bad value, states the expected format, and points to a next step. That is what lets the model recover.
Combining the layers into one dispatcher
Put validation in one place so every tool gets it. A dispatcher looks up the tool, validates, then runs.
import json
def dispatch(tool_name: str, raw_args, tools: dict) -> dict:
"""tools maps name -> (validator, function)."""
if tool_name not in tools:
return {"is_error": True, "message": f"Unknown tool {tool_name!r}. Available tools: {sorted(tools)}."}
validator, fn = tools[tool_name]
# Some APIs hand you arguments as a JSON string.
if isinstance(raw_args, str):
try:
raw_args = json.loads(raw_args)
except json.JSONDecodeError as exc:
return {"is_error": True, "message": f"Arguments were not valid JSON: {exc}."}
errors = [f"{'.'.join(map(str, e.path)) or '(top level)'}: {e.message}"
for e in validator.iter_errors(raw_args)]
if errors:
return {"is_error": True, "message": "Invalid arguments. " + " ".join(errors)}
try:
return fn(**raw_args)
except Exception as exc: # report, do not crash the loop
return {"is_error": True, "message": f"Tool failed: {type(exc).__name__}. Try again or ask the user."}The unknown-tool branch matters. Models occasionally call a tool name that is not in your list, and a clear message beats a KeyError.
Decisions and edge cases
Reject or repair?
When an argument is slightly wrong, you can reject it or fix it silently. Choose deliberately.
| Situation | Better choice | Reason |
|---|---|---|
| `"10"` for an integer limit | Either, but be consistent | Harmless to coerce, but coercion hides prompt problems |
| `limit: 500`, maximum 50 | Reject | Clamping changes what the user asked for without telling the model |
| Date as `11/28/2026` | Reject with the expected format | Guessing day versus month order can be wrong |
| Unknown status such as `"sent"` | Reject and list valid values | The model may have meant `shipped`, and only it can decide |
| Extra whitespace around an ID | Repair | No ambiguity |
Repair only when there is exactly one reasonable interpretation. If you do repair, say so in the result so the model knows what ran.
Authorization is not validation of the model's intent
Check permissions using the identity of the signed-in user from your session, not an ID the model supplies. If the model passes customer_id: "cus_4821" and the current user is cus_1111, that call must fail. Do not take the user's identity from a tool argument.
Side effects need extra care
For tools that change state, validate everything before the first write. A tool that updates three fields and fails on the third leaves a half-applied change. For high-impact actions such as refunds or deletes, add a confirmation step or require an explicit user approval outside the model.
Limit retries
An error message invites a retry, and a model can loop on the same mistake. Cap the number of failed calls per tool per conversation, and return a final message such as "Stop retrying. Ask the user for the missing information" once you hit the cap.
Do not leak internals
Error messages should help the model, not expose stack traces, file paths, SQL, or secrets. Log the details on the server and return a short, safe message.
Common mistakes
- Trusting
enumandmaximumbecause the model "will follow them". - Leaving out
additionalProperties: False, so misspelled fields pass silently. - Returning
Noneor raising an exception on bad input, which gives the model nothing to act on. - Taking user identity or permissions from arguments.
- Clamping or coercing values without telling the model.
- Validating after a partial write.
Exercise
A model calls search_orders with {"customer_id": "cus_4821", "status": "sent", "limit": 5}. The schema's enum for status is pending, shipped, delivered, cancelled. Your code is about to run the query. Describe what the server should do, and write one error message that helps the model recover.
Show answer
The server should not run the query. The schema check should fail on status because "sent" is not in the enum, and the server should return an error result to the model. A good message: "Invalid status 'sent'. Allowed values are: pending, shipped, delivered, cancelled. Retry with one of these, or omit status to include all orders." It names the bad value, lists valid values, and offers a way forward. The server should not guess that "sent" means "shipped".
Exercise
A tool takes customer_id as an argument and returns that customer's orders. The signed-in user is cus_1111, but the model sends cus_4821. Why is schema validation unable to catch this, and where should the check go?
Show answer
The value is a valid string in the correct format, so it passes every schema rule. The problem is about meaning and permission. The check belongs in the tool code (or dispatcher), which compares the argument with the identity from the authenticated session and returns an error if they differ. Better still, do not accept the identity as an argument at all and read it from the session.