Sub topic 4
Structured outputs and JSON schemas
This chapter assumes you can write Python, read JSON, and have called a chat-style LLM API. Agents need model output that code can parse. Free-form prose is hard to parse, so you ask the model for JSON and check it against a schema.
Why structure matters
A tool call is a request your program must act on. If the model writes "Let's check the weather in Oslo", your code has to guess the tool and the arguments. If it returns {"name": "get_weather", "arguments": {"city": "Oslo"}}, your code can dispatch it directly.
A JSON schema is a JSON document that describes the shape of other JSON: which keys exist, their types, and which are required. Providers use schemas in two ways. They describe tool arguments, and they constrain the final reply.
A schema for one tool
GET_WEATHER_SCHEMA = {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Oslo"},
"unit": {"type": "string", "enum": ["c", "f"]},
},
"required": ["city"],
"additionalProperties": False,
}Each part does a job:
typefixes the kind of value.enumlimits a field to listed values.requirednames the keys that must be present.additionalProperties: Falserejects keys you did not define.descriptiontells the model what a field means, and the model reads it.
Validate before you run
Even with a schema, treat model output as untrusted input. Models can omit fields, use the wrong type, or return broken JSON. Validate at the boundary, then run the tool.
import json
from jsonschema import validate, ValidationError # pip install jsonschema
def parse_arguments(raw: str, schema: dict) -> dict:
try:
data = json.loads(raw)
validate(instance=data, schema=schema)
except (json.JSONDecodeError, ValidationError) as exc:
raise ValueError(f"Invalid arguments: {exc}") from exc
return data
print(parse_arguments('{"city": "Oslo", "unit": "c"}', GET_WEATHER_SCHEMA))If validation fails, do not crash. Send the error text back as the tool result, the same way run_tool returns errors in the agent loop. The model can then read the message and correct its call.
Two levels of enforcement
| Approach | How it works | Guarantee |
|---|---|---|
| Prompt only | You ask for JSON in the instructions | None. Output can drift. |
| Schema-constrained decoding | The provider limits generation to tokens that fit the schema | Valid shape, if the provider supports it |
Even with constrained decoding, keep your validator. Providers support only part of the JSON Schema language. A reply can also be cut off at the token limit, which leaves incomplete JSON.
Common errors
- Optional fields the model fills with invented values. Mark only truly needed fields as required.
- Vague descriptions.
"id": {"type": "string"}gives the model nothing to go on. Say what kind of id it is. - Very large enums or deeply nested schemas. They raise error rates, so flatten where you can.
- Parsing with a regular expression instead of
json.loads.
Exercise
A model returns {"city": "Oslo", "unit": "kelvin"} for the schema above. What happens when you validate it, and what should the agent do next?
Show answer
Validation fails because "kelvin" is not in the enum ["c", "f"]. The agent should not run the tool. It should return the validation error as the tool result so the model can retry with "c" or "f".