Level 2 Agentic Coding · Building with AI
Structured Output and JSON
How to get data your code can trust out of a language model. Describe the shape with a schema, let the API enforce it with constrained decoding, validate the result with Pydantic, and repair or retry when it fails.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 5 concepts →
- Quiz
- 5 questions ↓
Read first
Using LLM APIsThis leads to
Tool Use and Function CallingThe full path from zero — 5 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Large Language Models, Explained Simply
- Using LLM APIs
- Structured Output and JSON
Read them roughly in this order. See it on the concept map →
Why it matters
Language models write text. Programs need data. If you ask a model to pull the total out of an invoice, a person is happy with "The total comes to £1,250, due by the end of December." Your accounting code is not. It needs {"total": 1250.0, "currency": "GBP", "due_date": "2026-12-31"}, every time, with exactly those field names and types.
Structured output means getting model output in a precise, machine-readable shape, almost always JSON (JavaScript Object Notation: nested lists and key–value pairs written as text, the lingua franca of web APIs). It is what turns a model into a component you can build on. Information extraction (pulling fields out of invoices, emails, CVs, contracts and medical notes), classification with labels, routing, form filling, and the arguments of every tool call an agent makes all depend on it.
The good news is that this is now largely a solved problem. As of late 2026 the major APIs can guarantee that output matches a schema you supply. The remaining work is designing good schemas and validating the meaning of the values, which no API can do for you.
The intuition
Asking for structured data in plain words is like asking someone to write you a letter and hoping it contains the six facts you need, in the order you need them. Giving them a form with labelled boxes, some with tick-box choices, is far more reliable. A schema is that form.
There are three levels of reliability:
- Ask nicely. "Reply in JSON with fields vendor, total…" Usually works with good models. Occasionally you get a stray sentence before the JSON, a trailing comma, or
"total": "£1,250"instead of a number. - Validate and repair. Parse the reply, check it against the schema in code, and if it fails, send the error back and ask the model to fix it. Works with any model.
- Constrain the decoding. The API itself only allows tokens that keep the output valid. The output cannot be malformed.
You want level 3 where it is available, and level 2 always, because a schema-valid answer can still be wrong.
Key idea Describe the shape you want with a schema. Let the API enforce the syntax, and validate the meaning in your own code. Never feed unvalidated model output to code that acts on it.
How it works
JSON Schema and Pydantic
JSON Schema is a standard way to describe a JSON shape: which fields exist, their types, which are required, and allowed values. Writing it by hand is tedious, so in Python almost everyone uses Pydantic, a library that turns a class with type hints into a schema and validates data against it:
from typing import Literal, Optional
from pydantic import BaseModel, Field
class Invoice(BaseModel):
vendor: str
invoice_number: str
total: float = Field(ge=0, description="Amount due, in the invoice currency")
currency: Literal["GBP", "EUR", "USD"]
due_date: Optional[str] = Field(None, description="YYYY-MM-DD, or null if absent")
- Each line is a field with a type:
str,float,int,bool,list[str], or another model for nesting. Literal["GBP", "EUR", "USD"]is an enum: the value must be one of a fixed list. Enums are the best tool you have for reliable classification.Optional[...] = Nonemakes a field nullable, giving the model an honest way to say "not present" instead of inventing a value.Field(ge=0, description=...)adds constraints (here "greater than or equal to 0") and a description. Descriptions end up in the schema, so they act as instructions to the model.
Invoice.model_json_schema() produces the JSON Schema. Invoice.model_validate_json(text) parses a JSON string and checks every rule. On success you get a real Python object (invoice.total is a float). On failure you get a ValidationError listing exactly which fields are wrong and why. That is validation: checking data against rules before you trust it.
Level 1 and 2: prompt, validate, repair
With any model, you can put the schema in the prompt, ask for JSON only, and validate the reply. When validation fails, a repair loop sends the error message back to the model and asks for a corrected version. Models are good at fixing their own output when told precisely what's wrong, because Pydantic's errors are specific: "total: Input should be a valid number, unable to parse string as a number."
Two rules keep this loop safe: cap the number of attempts (two or three is plenty), and have a fallback when they run out, such as logging the input for human review. The code below implements it in about 25 lines. The Instructor library packages the same idea for many providers.
Level 3: constrained decoding
A language model produces each token by computing a probability for every token in its vocabulary and sampling one (see Decoding: Temperature, Top-k and Top-p). Constrained decoding adds one step: before sampling, it sets the probability of every token that would make the output invalid to zero.
To know which tokens are invalid, the provider compiles your schema into a grammar, essentially a state machine that tracks where you are in the JSON. After {"currency": " the grammar knows a string from the enum must come next, so only tokens that begin GBP, EUR or USD survive. After "total": only digits are allowed. After the last required field, only }. The model still chooses which valid token to write, so its intelligence is intact, but it can't write anything outside the schema.
Worked example with illustrative numbers. Suppose after {"currency": " the model's top next-token probabilities are £ 0.40, GBP 0.35, pounds 0.15, EUR 0.06, USD 0.04. The schema allows only GBP, EUR and USD. Masking leaves 0.35, 0.06 and 0.04, which sum to 0.45. Renormalising (dividing by 0.45) gives GBP 0.78, EUR 0.13, USD 0.09. The model now almost certainly writes GBP, which is what it meant by £ anyway.
Providers' names for this:
- Anthropic: structured outputs, via
output_config={"format": {"type": "json_schema", "schema": ...}}, or the SDK helperclient.messages.parse(..., output_format=Invoice)which takes a Pydantic class and returns a validated object. Tool definitions can setstrict: Trueso tool-call arguments always match their schema. - OpenAI: Structured Outputs, via
client.responses.parse(..., text_format=Invoice). An older "JSON mode" guarantees valid JSON but not your particular schema. - Open models: libraries such as Outlines, and servers such as llama.cpp and vLLM, offer grammar-constrained generation for models you run yourself (see Running Models Locally).
Schema support has limits: providers implement a subset of JSON Schema, and very large or deeply recursive schemas may be rejected. The first request with a new schema can also be slower while the grammar is compiled.
Designing schemas that work
The schema is a prompt as much as a data format. The patterns from Prompt Engineering apply:
- Use enums for categories.
Literal["refund", "exchange", "complaint", "other"]beats a free-textcategorythat comes back as "Refund request" one time and "refund" the next. Always include an"other"or"unknown"option. - Allow nulls. If a field might be missing from the source, make it optional. A required field forces the model to invent something.
- Order fields for thinking. The model writes fields in order. Put a
reasoningorevidencefield (for example, a quote from the source) before thedecisionfield, and the decision benefits from the reasoning, as in Chain-of-Thought and Reasoning Prompts. Put it after, and it is only a justification written once the decision is fixed. - Describe fields. Formats ("YYYY-MM-DD"), units ("in kilograms") and edge cases ("if several totals appear, use the one labelled 'amount due'") belong in field descriptions.
- Keep it flat and small. Deep nesting and dozens of fields raise the error rate. Two simpler calls often beat one huge schema.
Validating meaning, not just shape
Constrained decoding guarantees total is a non-negative number. It doesn't guarantee it is the right number. Add checks that use your domain knowledge:
- Pydantic validators for rules such as "due date is after invoice date" or "line items sum to the subtotal".
- Cross-checks against the source: does the extracted invoice number actually appear in the document?
- For important fields, measure accuracy on a labelled test set, field by field. Extraction often has one or two hard fields that drag down quality, and per-field numbers tell you where to focus (see Evaluating LLM Applications).
In code
A complete validate-and-repair loop, runnable offline. Install Pydantic first (pip install pydantic). The fake model's first reply has two errors, a currency symbol instead of a code and the total as a string with a pound sign. The loop sends the error back and the "model" corrects it.
import json
from typing import Literal, Optional
from pydantic import BaseModel, Field, ValidationError
class Invoice(BaseModel):
vendor: str
invoice_number: str
total: float = Field(ge=0, description="Amount due, in the invoice currency")
currency: Literal["GBP", "EUR", "USD"]
due_date: Optional[str] = Field(None, description="YYYY-MM-DD, or null if absent")
def extract(text, call_model, max_attempts=3):
prompt = (f"Extract the invoice fields as JSON matching this schema:\n"
f"{json.dumps(Invoice.model_json_schema())}\n\n<invoice>\n{text}\n</invoice>")
messages = [{"role": "user", "content": prompt}]
for attempt in range(1, max_attempts + 1):
reply = call_model(messages)
try:
return Invoice.model_validate_json(reply) # parse + validate
except ValidationError as err:
print(f"attempt {attempt}: {err.error_count()} error(s): "
f"{err.errors()[0]['loc']} {err.errors()[0]['msg']}")
messages += [{"role": "assistant", "content": reply},
{"role": "user", "content": f"That JSON was invalid:\n{err}\n"
"Reply with corrected JSON only."}]
raise RuntimeError("no valid JSON after retries")
# Offline stand-in: first reply has a wrong currency and a total with a symbol.
replies = iter(['{"vendor": "Acme Ltd", "invoice_number": "INV-0042", '
'"total": "£1,250.00", "currency": "£", "due_date": "2026-12-31"}',
'{"vendor": "Acme Ltd", "invoice_number": "INV-0042", '
'"total": 1250.0, "currency": "GBP", "due_date": "2026-12-31"}'])
fake_model = lambda messages: next(replies)
invoice = extract("ACME LTD ... Invoice INV-0042 ... Total due £1,250.00 by 31/12/2026",
fake_model)
print(invoice)
print(invoice.total * 1.2) # a real float, ready for arithmetic
# attempt 1: 2 error(s): ('total',) Input should be a valid number, unable to parse string as a number
# vendor='Acme Ltd' invoice_number='INV-0042' total=1250.0 currency='GBP' due_date='2026-12-31'
# 1500.0
model_validate_json also raises a ValidationError for text that isn't JSON at all, such as "Sure! Here's the JSON:" in front of it, so the same loop handles that case.
With native structured outputs the API does the constraining and the SDK does the validation. Anthropic's SDK (pip install anthropic, key in ANTHROPIC_API_KEY):
import anthropic
client = anthropic.Anthropic()
response = client.messages.parse(
model="claude-haiku-5-5", # extraction is a good job for a small model
max_tokens=2000,
messages=[{"role": "user", "content":
"Extract the invoice fields.\n<invoice>\nACME LTD ... Invoice INV-0042 "
"... Total due £1,250.00 by 31/12/2026\n</invoice>"}],
output_format=Invoice, # the Pydantic class from above
)
invoice = response.parsed_output # an Invoice instance
And OpenAI's (pip install openai, key in OPENAI_API_KEY):
from openai import OpenAI
client = OpenAI()
response = client.responses.parse(
model="gpt-6-luna", # check the models page for current ids
input="Extract the invoice fields.\n<invoice>\n...\n</invoice>",
text_format=Invoice,
)
invoice = response.output_parsed
Even with these, keep a try/except around the call. A reply cut off by max_tokens, or a refusal, can still fail to parse.
Common pitfalls
- Parsing with regular expressions. Pulling JSON out of chatty text with a regex works until the text contains a brace. Use the API's structured output or a proper parser plus validation.
- Required fields for optional facts. If half your invoices have no due date but the field is required, the model will invent dates. Make it nullable.
- Free-text categories. Labels drift ("Billing", "billing issue", "payments"). Use an enum.
- Trusting valid output. Schema-valid means well-formed, not correct. A perfectly formatted wrong total is still wrong. Validate meaning and measure accuracy.
- Putting the answer before the reasoning. Fields are generated in order. A
confidenceorexplanationfield after the answer can't improve the answer. - Unbounded repair loops. Always cap retries and handle the failure path.
Watch out Model output that controls actions (database writes, payments, emails, shell commands) must be validated as strictly as input from an untrusted user, because if the model read untrusted text it effectively is untrusted input. A document can contain instructions that steer the extraction. See Prompt Injection and LLM Security.
Where it leads
- Tool Use and Function Calling: tool calls are structured output where the schema is a function's parameters.
- AI Agents: agents chain many structured decisions together, so validation at each step matters.
- Retrieval-Augmented Generation: structured output for citations, such as a list of
{claim, source_id}pairs you can check. - Evaluating LLM Applications: per-field accuracy on a labelled set is the standard way to evaluate extraction.
- OCR and Document AI: extracting structured fields from scanned documents and PDFs.
A bit of history
Early users of GPT-3 got JSON by prompting with examples and hoping. Through 2023 a series of tools appeared to make it reliable: OpenAI's function calling (June 2023) gave models a structured way to emit arguments, and JSON mode (November 2023) guaranteed syntactically valid JSON. Open-source libraries such as Outlines and Guidance, and grammar support in llama.cpp, showed that constraining decoding with a grammar could guarantee a schema for open models. Instructor popularised the Pydantic validate-and-retry pattern. In August 2024 OpenAI launched Structured Outputs with schema-constrained decoding, and Anthropic followed with its own structured outputs in 2025. By then the question had moved from "how do I get valid JSON?" to "how do I design a schema that gets correct JSON?"
Try it
- Add a Pydantic validator to
Invoicethat rejects adue_datethat isn't inYYYY-MM-DDformat. (Hint:from pydantic import field_validator, or change the type todatetime.date, which Pydantic parses for you.) Make the fake model's second reply use31/12/2026and watch the loop catch it.- Design a schema for support emails with
category(enum),urgency(1–5),order_id(nullable) andsummary(at most 30 words). Where would you put areasoningfield, and why?- With a real API, extract invoices from five varied example texts, with and without native structured outputs. Count schema failures and wrong values separately.
Hint for 3: you will likely see zero schema failures with structured outputs but a few wrong values in both. Those are two different problems with different fixes.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Structured outputs (Claude)
How to constrain Claude's response to a JSON schema with output_config.format, or validate tool inputs with strict tools, including the Pydantic helper.
Structured Outputs (OpenAI)
Schema-constrained JSON from OpenAI models, with Pydantic examples, refusal handling and the supported subset of JSON Schema.
Pydantic documentation
The data-validation library almost every LLM tool uses for schemas: models, field types, validators and JSON Schema generation.
Instructor
A small library that wraps many LLM providers to return validated Pydantic objects, with automatic retries that feed validation errors back to the model.
Anthropic Courses
Notebook courses on the Claude API, prompt engineering, real-world prompting, prompt evaluations and tool use.
Claude Cookbooks
Runnable notebooks for real tasks with Claude: RAG, contextual retrieval, structured JSON, tool use, prompt caching, sub-agents and more.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/structured-output.md