Sub topic 4
Structured outputs and JSON schemas
This chapter assumes you can write Python, read JSON, and have called an LLM API before. It also assumes you know that a prompt is text sent to a model. Here you will learn how to make a model return data your code can parse, and what to do when it doesn't.
Why free text breaks programs
A model answers in prose by default. Your code needs fields. Suppose a support agent must route a ticket. The model replies "Sounds like a billing issue, fairly urgent." Your program now has to guess the category and priority from that sentence, and the guess breaks the first time the model words it differently.
A structured output is a model reply that follows a format your program can parse. In practice the format is JSON, and a JSON schema describes which JSON is allowed. The schema is the contract between the model and your code.
Structured outputs matter for agents because tool calling depends on them. When a model requests get_weather with {"city": "Oslo"}, that request is a structured output. If the arguments are malformed, the tool call fails.
What a JSON schema contains
A schema is itself a JSON object. These keywords cover most agent work:
| Keyword | Meaning |
|---|---|
| `type` | One of `object`, `string`, `integer`, `number`, `boolean`, `array` |
| `properties` | The fields of an object, each with its own schema |
| `required` | Field names that must be present |
| `enum` | A closed list of allowed values |
| `items` | The schema for each element of an array |
| `additionalProperties` | Set to `false` to reject fields you did not list |
| `description` | Plain-language guidance for the model |
Here is a schema for ticket triage:
TICKET_SCHEMA = {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "bug", "other"],
"description": "Best matching ticket category.",
},
"priority": {
"type": "integer",
"description": "1 is most urgent, 3 is least urgent.",
},
"summary": {"type": "string", "description": "One sentence."},
},
"required": ["category", "priority", "summary"],
"additionalProperties": False,
}The enum removes a whole class of errors. The model cannot invent a category called "refund" without breaking the schema. The description fields are sent to the model, so they work as small prompts. Write them as carefully as you would write instructions.
Three ways to get structured output
Providers offer different levels of enforcement. Pick based on how much a malformed reply costs you.
- Prompt only. You ask for JSON in the prompt. This works most of the time and fails unpredictably. It needs validation and retries.
- JSON mode. The provider guarantees the reply is syntactically valid JSON. It does not guarantee your fields or types.
- Schema-constrained decoding. You pass the schema, and the provider restricts generation so the reply matches it. This gives the strongest guarantee, but providers support only a subset of schema keywords. Check which ones.
Tool calling is the same mechanism. The argument schema you give a tool is the output schema for the model's request.
Validate even when the provider enforces a schema
Treat model output as untrusted input, the same as data from a web form. Even with constrained decoding, validation still earns its place:
- Providers support only part of the schema language, so some rules go unenforced.
- A reply can be cut off at the token limit and leave incomplete JSON.
- A model may refuse a request, and the refusal may not follow your schema.
- Schemas cannot express business rules, such as "the order ID must exist."
The next example uses only the standard library, so you can run it as is. In real projects, the jsonschema or pydantic packages do this job more completely.
import json
TYPES = {
"object": dict, "string": str, "array": list,
"integer": int, "number": (int, float), "boolean": bool,
}
def check(value, schema, path="$"):
"""Return a list of problems. An empty list means the value is valid."""
expected = schema.get("type")
if expected:
ok = isinstance(value, TYPES[expected])
if expected in ("integer", "number") and isinstance(value, bool):
ok = False # bool is a subclass of int in Python
if not ok:
return [f"{path}: expected {expected}"]
errors = []
if "enum" in schema and value not in schema["enum"]:
errors.append(f"{path}: must be one of {schema['enum']}")
if expected == "object":
props = schema.get("properties", {})
for key in schema.get("required", []):
if key not in value:
errors.append(f"{path}.{key}: missing")
for key, item in value.items():
if key in props:
errors += check(item, props[key], f"{path}.{key}")
elif schema.get("additionalProperties") is False:
errors.append(f"{path}.{key}: not allowed")
if expected == "array" and "items" in schema:
for i, item in enumerate(value):
errors += check(item, schema["items"], f"{path}[{i}]")
return errorsRetry with the errors as feedback
When validation fails, send the specific problems back to the model. A message like "$.priority: expected integer" lets the model repair its own reply. This is the same idea as returning tool errors as text in the agent loop. A crash teaches the model nothing, while a readable error lets it recover.
def get_structured(call_model, prompt, schema, max_attempts=3):
messages = [{"role": "user", "content": prompt}]
for _ in range(max_attempts):
text = call_model(messages)
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
problems = [f"invalid JSON: {exc}"]
else:
problems = check(data, schema)
if not problems:
return data
messages.append({"role": "assistant", "content": text})
messages.append({
"role": "user",
"content": "Your reply was rejected: " + "; ".join(problems)
+ ". Reply with corrected JSON only.",
})
raise ValueError("no valid output after retries")
replies = iter([
'{"category": "refund", "priority": "high"}',
'{"category": "billing", "priority": 2, "summary": "Customer was charged twice."}',
])
def scripted_model(messages):
return next(replies)
print(get_structured(scripted_model, "Triage: I was charged twice.", TICKET_SCHEMA))The first reply fails three checks: the category is not in the enum, the priority is a string, and summary is missing. The second reply passes, and the program prints the parsed dictionary. Note the attempt cap. Without max_attempts, a model that keeps failing would loop forever and burn tokens.
Common errors
- Parsing text that wraps the JSON. Models sometimes add "Here is the JSON:" or a Markdown fence. Instruct the model to reply with JSON only, or use a mode that enforces it. Do not strip text with a fragile regex as your main defense.
- Optional fields that are really required. Some providers' strict modes require every field to be listed in
required. To make a field optional, allownullas a type instead. - Vague field names. A field called
dataorvaluegives the model nothing to work with. Use names likedue_date_isoand describe the expected format. - Deep or huge schemas. Large nested schemas raise the failure rate and use up context tokens. Keep each schema small and split big jobs into steps.
- Trusting valid output as correct output. A reply can match the schema and still be wrong. A valid
priority: 1says nothing about whether the ticket is urgent. Schemas check shape, not truth.
Where this fits
Structured outputs give the model a reliable way to speak to your code. The next step is using that channel to request actions, which is tool calling. Everything there rests on the pattern from this chapter: a schema, a parse, a validation, and readable errors on failure.
Exercise
A model returns {"category": "bug", "priority": 2, "summary": "App crashes", "owner": "sam"} for TICKET_SCHEMA. Does check() accept it? What one change to the schema would make the reply valid, and when would you not want that change?
Show answer
check() rejects it, because "owner" is not listed in properties and additionalProperties is False, so it reports "$.owner: not allowed". Adding an "owner" property to the schema, or removing the additionalProperties restriction, would make the reply valid. You would not want to loosen the schema if downstream code relies on an exact set of fields, since unexpected fields could be a sign the model is drifting from your instructions.
Exercise
Why does get_structured send the validation errors back to the model instead of just retrying the same prompt?
Show answer
The same prompt tends to produce the same mistake. The error messages tell the model which fields failed and why, so it can correct them. The max_attempts cap keeps the retries from running forever.