Sub topic 8
Validating arguments before you run anything
This chapter assumes you can read Python and JSON, and that you have built the tool-calling loop from the earlier chapters. You will need pip install jsonschema to run the code.
Why model arguments are untrusted input
The model proposes a tool call. Your code decides whether to run it. The arguments the model writes are text it generated, so treat them like a form field submitted by an anonymous user.
A schema in the tool definition tells the model what to send. It does not force the model to comply. Some providers offer strict modes that constrain output to the schema, but you should still validate for three reasons:
- Not every provider or model supports strict mode, and it often supports only part of JSON Schema.
- A schema cannot express every rule. "This path must stay inside the workspace" is not a schema constraint.
- The arguments may be shaped by text the model read, including text written by an attacker (see the security chapter).
Validation also helps the model. A precise error message lets it fix the call on the next step.
Three layers of checks
Run the checks in order and stop at the first failure. Each layer catches a different kind of mistake.
- Parse. Some providers give you arguments as a JSON string, others as an already-parsed object. If you get a string, it may be malformed, truncated, or valid JSON that is not an object (for example
[]or"Oslo"). - Schema. Check types, required fields, enum values, length limits, and unexpected extra fields.
- Semantic and permission checks. Check what only your code can know: whether the file exists, whether the date is in the future, whether this user may touch this record.
Layer 1: parse
Accept both forms, then require a JSON object. Convert every failure into a ValueError with a readable message.
def parse_arguments(raw):
if isinstance(raw, str):
try:
raw = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError("Arguments were not valid JSON: " + str(exc))
if not isinstance(raw, dict):
raise ValueError("Arguments must be a JSON object")
return rawAn empty string is a common case. Some models send "" for a tool with no parameters. Decide whether to treat that as {}. If you do, do it deliberately in this function, not by accident.
Layer 2: schema validation
Reuse the same JSON Schema you sent in the tool definition. One schema then serves as both the documentation the model reads and the contract your code enforces. Use a validator library instead of hand-written if statements, because the library handles nested objects, arrays, and combinations like oneOf.
Collect all errors, not just the first. The model can then fix everything in one retry.
def schema_errors(schema, args):
validator = Draft202012Validator(schema)
problems = []
for err in sorted(validator.iter_errors(args), key=lambda e: str(list(e.path))):
where = "/".join(str(p) for p in err.absolute_path) or "(root)"
problems.append(where + ": " + err.message)
return problemsThree schema settings matter most:
"required"lists the fields that must be present. Without it, a missingcityreaches your function as aTypeError."additionalProperties": falserejects invented fields. Without it, a hallucinated"zip"field passes silently and may be ignored or, worse, forwarded to a downstream API.- Bounds such as
minLength,maxLength,minimum,maximum, andmaxItemslimit how much damage one call can do.
Do not silently coerce types. A validator will reject "3" where an integer is expected. Converting it yourself hides model errors from your logs, and sometimes the conversion is wrong. If you decide to coerce a specific field, do it in one place and log it.
Layer 3: semantic and permission checks
A schema checks shape. It cannot know that ../../etc/passwd is a string that escapes your sandbox. Write a small check function per tool for rules that depend on state or identity. Return an error message, or None if the call is fine.
The path check is the standard example. Resolve the path first, so .. segments and symlinks are expanded, and then compare it with the allowed directory. Comparing the raw string with startswith is unsafe.
Putting the layers into the dispatcher
This program extends the dispatcher from the earlier chapter. It is complete and runs as shown.
import json
from pathlib import Path
from jsonschema import Draft202012Validator
BASE_DIR = Path("workspace").resolve()
WEATHER_SCHEMA = {
"type": "object",
"properties": {
"city": {"type": "string", "minLength": 1, "maxLength": 100},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
"additionalProperties": False,
}
READ_SCHEMA = {
"type": "object",
"properties": {"path": {"type": "string", "minLength": 1}},
"required": ["path"],
"additionalProperties": False,
}
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
def read_file(path):
return {"path": path, "text": (BASE_DIR / path).read_text()}
def check_read_file(args):
target = (BASE_DIR / args["path"]).resolve()
if not target.is_relative_to(BASE_DIR):
return "path must stay inside the workspace"
if not target.is_file():
return "no such file: " + args["path"]
return None
TOOLS = {
"get_weather": {"fn": get_weather, "schema": WEATHER_SCHEMA, "check": None},
"read_file": {"fn": read_file, "schema": READ_SCHEMA, "check": check_read_file},
}
def parse_arguments(raw):
if isinstance(raw, str):
try:
raw = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError("Arguments were not valid JSON: " + str(exc))
if not isinstance(raw, dict):
raise ValueError("Arguments must be a JSON object")
return raw
def schema_errors(schema, args):
validator = Draft202012Validator(schema)
problems = []
for err in sorted(validator.iter_errors(args), key=lambda e: str(list(e.path))):
where = "/".join(str(p) for p in err.absolute_path) or "(root)"
problems.append(where + ": " + err.message)
return problems
def error(text):
return {"is_error": True, "content": text}
def run_tool_call(call):
tool = TOOLS.get(call["name"])
if tool is None:
return error("Unknown tool: " + str(call["name"]))
try:
args = parse_arguments(call["arguments"])
except ValueError as exc:
return error(str(exc))
problems = schema_errors(tool["schema"], args)
if problems:
return error("Invalid arguments: " + "; ".join(problems))
if tool["check"]:
message = tool["check"](args)
if message:
return error("Not allowed: " + message)
try:
result = tool["fn"](**args)
except Exception as exc:
return error("Tool failed: " + str(exc))
return {"is_error": False, "content": json.dumps(result)}
if __name__ == "__main__":
calls = [
{"name": "get_weather", "arguments": {"city": "Oslo"}},
{"name": "get_weather", "arguments": '{"city": "Oslo", "unit": "kelvin"}'},
{"name": "get_weather", "arguments": '{"city": "Oslo"'},
{"name": "get_weather", "arguments": {"city": "Oslo", "zip": "0150"}},
{"name": "read_file", "arguments": {"path": "../secrets.txt"}},
]
for call in calls:
print(run_tool_call(call))The first call succeeds. The second returns Invalid arguments: unit: 'kelvin' is not one of ['celsius', 'fahrenheit']. The third reports invalid JSON, and the exact wording comes from Python's JSON parser. The fourth is rejected because zip is an unexpected property. The fifth is rejected by the semantic check, so the file is never opened.
What the model sees on failure
The error goes back as a normal tool result, tagged with the same tool_call_id. The model usually corrects the call and tries again. Write messages that name the field and the allowed values, as above. A message like "error" gives the model nothing to fix.
Be careful about how much you reveal. Echo the field name and the rule, not internal paths, stack traces, or other users' data. The step limit from the loop chapter still applies, so a model that keeps repeating a bad call ends the run instead of looping forever.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Calling `fn(**args)` without validating | Extra keys raise `TypeError`, or are forwarded to downstream code | Validate with `additionalProperties: false` first |
| Assuming `arguments` is always a dict | Crash on providers that send a JSON string | Parse in one function that accepts both |
| Checking `path.startswith(base)` on raw text | `base/../x` and sibling directories like `base-evil` pass | Resolve first, then use `is_relative_to` |
| Raising on bad input in the dispatcher | The loop crashes and the model never learns what went wrong | Return an error result instead |
| Reporting only the first schema error | One retry per problem, which costs steps | Collect all errors |
| Trusting the schema for authorization | Model can pass another user's ID | Check permissions against the real session, not the arguments |
Exercise
The read_file schema accepts any string for path. A model sends {"path": "/etc/passwd"}. Which layer rejects this call, and why does BASE_DIR / "/etc/passwd" still fail the check?
Show answer
The semantic layer (check_read_file) rejects it, because the schema only checks that path is a non-empty string. In pathlib, joining with an absolute path discards the base, so BASE_DIR / "/etc/passwd" is /etc/passwd. After resolve(), is_relative_to(BASE_DIR) is false, so the function returns "path must stay inside the workspace" and the file is never opened.
Exercise
Add a get_weather rule that rejects city names containing digits, using only a schema change. Which keyword do you add, and what is the limit of this approach compared with a semantic check?
Show answer
Add "pattern": "^[^0-9]+$" to the city property. This enforces a character rule, but a schema cannot tell whether the city actually exists. A semantic check against a list or a geocoding lookup is needed for that.