Structured Output from LLMs
Read a little, play a little. No scary maths, and no rush.
Prose is for humans; machines need shapes
"High priority, about the refund" is a lovely sentence and a useless API response. Downstream code needs {"priority": "high"} — exact keys, exact enums, no surprises. Structured output forces the model to speak JSON (or another schema), turning a storyteller into a reliable component.
JSON mode + validation, the standard recipe
resp = client.chat.completions.create(
model="gpt-4o-mini",
response_format={"type": "json_object"},
messages=[{"role": "user", "content": 'Return {"title": str, "priority": "low|high"}'}],
)
import json
from pydantic import BaseModel
class Ticket(BaseModel):
title: str
priority: str # low|high
ticket = Ticket.model_validate(json.loads(resp.choices[0].message.content))
Two layers do the work: the model is asked for JSON, then Pydantic validates it like any untrusted input — because models still occasionally emit malformed shapes, wrong enums, or extra keys.
JSON mode versus schema enforcement
There are two levels of help from the API, and the difference matters.
- JSON mode guarantees the reply is valid JSON. It does not guarantee your fields: you can still get
"urgent"where you allowed onlyloworhigh, or a missingtitle. - Schema-enforced output, offered by several providers under names like structured outputs, lets you pass a JSON Schema. The model's generation is constrained so the reply matches that schema's fields and allowed values.
Even with enforcement, keep the validation step. A schema can say total is a number; it cannot say the total must match the line items, or that a date cannot be in the future. Those business rules are yours to check.
Prompting for structure that parses
Name fields explicitly, list allowed enum values inline, and show one mini-example of perfect output. When validation fails, don't silently guess — retry once, pasting the validation error back ("priority must be low|high, got 'urgent'"). That feedback loop fixes most misses automatically.
Designing a schema the model can fill
- Use enums for categories.
"priority": "low" | "medium" | "high"beats a free-text field you then have to interpret. - Allow "unknown". If a field may be absent from the input, make it nullable. A required field with no evidence forces the model to invent something.
- Keep it flat and small. Ten clear fields fill more reliably than a deeply nested structure with forty.
- Describe fields that could be misread. "date: the invoice date, not the due date" removes a whole class of errors.
- Put reasoning before the verdict when a judgment is involved. A short
reasonfield placed beforedecisiongives the model room to work it out before committing.
A worked example: invoice extraction
A team pulls fields from scanned invoices into their accounting system. Their schema has vendor, invoice_date (nullable), total (number), and currency (an enum of the currencies they accept).
On a batch of 500 invoices, most pass at once. The failures teach the most: a few have no visible date, which the nullable field now handles honestly instead of guessing; a few return totals with a currency symbol inside the number, which the validator rejects and the retry fixes. Every failure is logged with the original document, so the team reviews a short list instead of discovering bad data weeks later in a report.
Tool calling, covered later in this track, uses the same idea: the model fills in a schema that describes a function's arguments.
Remember this
- Ask for shape, validate the shape, retry with the error message.
- Never let raw model text touch business logic unvalidated.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Practice this in an incident
End of Your First AI App
Take the section checkpoint
A short mixed quiz on all 3 chapters, to check you are ready to move on.
Related chapters
Spotted a mistake or want a topic covered? Report an issue