Sub topic 2
Describing arguments with JSON Schema
This chapter assumes you can read JSON and write basic Python. It also assumes you have seen a chat request with role-tagged messages. By the end you will be able to write a parameter schema for a tool and check model-generated arguments against it.
Why tools use JSON Schema
When you give a model a tool, you must say what arguments the tool accepts. Providers use JSON Schema for this. JSON Schema is a standard vocabulary for describing the shape of a JSON document: which keys exist, what type each value has, and which values are allowed.
The schema does two jobs:
- It is documentation for the model. The model reads the types, enum values, and descriptions and uses them to write an arguments object.
- It is a contract for your code. You can run the same schema through a validator before executing anything.
The first job is a hint, not a guarantee. A model can still produce a missing key, a wrong type, or a value outside your enum. Treat the schema as the specification you validate against, not as proof that the arguments are correct.
The anatomy of a parameters schema
The schema for a tool's arguments is almost always an object whose keys are the argument names.
{
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Oslo"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"],
"additionalProperties": false
}Each keyword has a specific role:
type: "object"says the arguments are a JSON object. Providers expect this at the top level.propertiesmaps each argument name to a schema for its value.requiredlists the names that must be present. Anything not listed is optional.additionalProperties: falserejects keys you did not declare. Without it, extra keys are allowed by default.descriptionis free text. It is not validated, but the model reads it, so it is where you explain meaning, units, and examples.
Value types
| Type | Matches | Typical use |
|---|---|---|
| `string` | Text | Names, IDs, dates as text |
| `integer` | Whole numbers | Counts, page numbers |
| `number` | Any JSON number | Prices, coordinates |
| `boolean` | `true` or `false` | Flags |
| `array` | A list | Several IDs, several tags |
| `object` | Nested keys | Grouped arguments |
| `null` | `null` | An explicit "no value" |
Prefer integer over number when fractions make no sense. A model asked for a page number will otherwise sometimes send 2.0.
Constraining values
A bare type is a weak constraint. These keywords narrow what the model may send.
enumlists the only allowed values. Use it for fixed choices such as units, sort orders, and status names.minimumandmaximumbound numbers.minLengthandmaxLengthbound strings.patternis a regular expression a string must match, for example^[A-Z]{3}$for a three-letter airport code.itemsdescribes the elements of an array.minItemsandmaxItemsbound its length.defaultdocuments the value your code uses when the argument is omitted. It does not insert the value for you.
Here is a schema that combines several of these. It describes a flight search.
{
"type": "object",
"properties": {
"origin": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "IATA airport code, for example OSL"},
"destination": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "IATA airport code, for example LHR"},
"passengers": {"type": "integer", "minimum": 1, "maximum": 9},
"cabin": {"type": "string", "enum": ["economy", "business"], "default": "economy"},
"max_price": {"type": ["number", "null"], "description": "Upper price limit in euros, or null for no limit"}
},
"required": ["origin", "destination", "passengers"],
"additionalProperties": false
}Note "type": ["number", "null"]. A type array allows several types. It is the usual way to say a value may be absent but present as null.
Nested objects and arrays
Schemas compose. An array of objects needs a schema at items, and that schema is a full object schema with its own required.
{
"type": "object",
"properties": {
"attendees": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"email": {"type": "string"},
"optional": {"type": "boolean"}
},
"required": ["email"],
"additionalProperties": false
}
}
},
"required": ["attendees"],
"additionalProperties": false
}Keep nesting shallow. Deep schemas give the model more places to make a mistake, and some providers cap nesting depth.
Where the schema is used
The same schema is used twice: once when you describe the tool, and once when you check the arguments that come back.
Validating with the schema
The jsonschema package (pip install jsonschema) runs the same schema in your dispatcher. This script collects every problem at once, so the model can fix all of them in one retry.
from jsonschema import Draft202012Validator
SCHEMA = {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Oslo"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
"additionalProperties": False,
}
validator = Draft202012Validator(SCHEMA)
def check(arguments):
errors = sorted(validator.iter_errors(arguments), key=lambda e: str(list(e.path)))
return [
"/".join(str(p) for p in e.path) or "(root)" + ": " + e.message
if False
else ("/".join(str(p) for p in e.path) or "(root)") + ": " + e.message
for e in errors
]
print(check({"city": "Oslo"}))
print(check({"unit": "kelvin"}))
print(check({"city": "Oslo", "days": 3}))Running it prints:
[]
["(root): 'city' is a required property", "unit: 'kelvin' is not one of ['celsius', 'fahrenheit']"]
["(root): Additional properties are not allowed ('days' was unexpected)"]An empty list means the arguments are valid. Each message names the location and the problem in plain text, which makes it suitable to return to the model.
Provider differences and gotchas
The schema language is standard, but providers do not all support all of it.
- Subset support. Some providers ignore or reject keywords such as
pattern,minimum,oneOf, or$ref. If a constraint is silently ignored, your own validation is the only thing enforcing it. - Strict modes. Some providers offer a strict mode that forces the output to match the schema. These modes often require
additionalProperties: falseand every property listed inrequired. Optional arguments are then expressed as a type that includesnull. Check your provider's documentation for the exact rules. - Wrapper keys differ. The schema may sit under
parameters,input_schema, or a similar key. The schema itself stays the same. formatis advisory. Keywords like"format": "date"or"format": "email"are not checked byjsonschemaunless you pass a format checker. Do not assume they are enforced.
Common errors
- Forgetting
required. Every property is then optional, and the model may omit the one your function needs. - Leaving
additionalPropertiesopen. The model may invent argument names. If your function is called with**arguments, this raises aTypeError. - Descriptions that repeat the name.
"city": "the city"tells the model nothing. Give an example and the expected format. - Using
stringfor fixed choices. Anenumremoves a whole class of invented values. - Overloading one schema. A single argument that means different things depending on another argument is hard for the model. Split it into separate tools.
Exercise
A tool takes query (required text), limit (optional whole number from 1 to 50), and sort (optional, either "newest" or "oldest"). Undeclared arguments must be rejected. Write the parameters schema.
Show answer
{"type": "object", "properties": {"query": {"type": "string", "description": "Search text"}, "limit": {"type": "integer", "minimum": 1, "maximum": 50}, "sort": {"type": "string", "enum": ["newest", "oldest"]}}, "required": ["query"], "additionalProperties": false}
Exercise
The model calls your weather tool with {"city": "Oslo", "unit": "kelvin"}. Which schema keyword makes validation fail, and why is it a bad idea to rely on the model alone to avoid this?
Show answer
The enum on unit fails because "kelvin" is not in ["celsius", "fahrenheit"]. The schema is only a hint to the model, which can still send values outside it, so your code must validate the arguments before running the tool.