Structured outputs and JSON Schema
The moment model output feeds into code rather than a human, prose becomes a liability. You need fields, types and enums you can trust. "Please reply in JSON" used to be the best you could do, followed by a regex and a prayer. Today the major providers offer structured outputs: you hand over a JSON Schema, and the model is constrained to produce output that matches it. This doc covers how that works and where the sharp edges still are.
Why it matters
Extraction, classification, routing, form filling and agent plans all depend on parseable output. Without schema enforcement, even a strong model occasionally adds a friendly preamble, wraps JSON in a markdown fence, invents a field name or truncates mid-object, and each of those is a production incident at scale. Structured outputs turn a probabilistic format into a contract, which lets you delete a lot of defensive parsing code.
How it works
There are three generations of technique, and you will still see all three in codebases.
- Prompt-only: instructions plus examples, then parse and retry on failure.
- JSON mode: the provider guarantees syntactically valid JSON but not your schema.
- Schema-constrained decoding: the provider compiles your JSON Schema into a grammar and, at each decoding step, masks out tokens that would violate it. The model can only sample tokens that keep the output valid.
Rendering diagram…
OpenAI explained when it launched the feature that the first request with a new schema is slower because the schema is preprocessed into a grammar, and later requests reuse it. Only a subset of JSON Schema is supported; strict mode requires every property to be listed in required and additionalProperties: false. Optional fields are expressed as a union with null.
Provider surfaces in 2026
- OpenAI:
response_format/text.formatwithtype: "json_schema"andstrict: true, plusstrict: trueon function definitions. The SDKs accept Pydantic or Zod models directly throughparsehelpers. Refusals come back in a separate refusal field rather than as malformed JSON. - Anthropic: two features that can be combined. JSON outputs use
output_config.formatwithtype: "json_schema"and a schema, and strict tool use addsstrict: trueto a tool definition so tool inputs match the schema. The earlieroutput_formatparameter and beta header moved tooutput_config.formatand no longer need a beta header. The docs note structured outputs cannot be combined with citations. - Google Gemini supports a response schema with a JSON MIME type. Open-weight serving stacks typically offer grammar-constrained decoding too.
Reference architecture
A robust extraction service still validates, because a schema cannot express all business rules.
Rendering diagram…
Code
This Python example uses OpenAI's Responses API with a Pydantic model. The SDK converts the model to a strict JSON Schema and parses the result back into a typed object.
from typing import Literal
from pydantic import BaseModel, Field
from openai import OpenAI
client = OpenAI()
class LineItem(BaseModel):
description: str
quantity: int
unit_price: float
class Invoice(BaseModel):
vendor: str
invoice_number: str
currency: Literal["USD", "EUR", "GBP", "INR", "other"]
due_date: str | None = Field(description="ISO 8601 date, or null if absent")
items: list[LineItem]
text = """ACME Tools Ltd, Invoice INV-2291. Due 2026-11-15.
3 x torque wrench @ 42.50 GBP, 1 x calibration service @ 120.00 GBP"""
response = client.responses.parse(
model="gpt-5-mini",
input=[
{"role": "system", "content": "Extract invoice fields. Use null for anything missing."},
{"role": "user", "content": text},
],
text_format=Invoice,
)
invoice = response.output_parsed
total = sum(i.quantity * i.unit_price for i in invoice.items)
print(invoice.vendor, invoice.currency, total)
The equivalent Anthropic request sends a normal Messages call with output_config={"format": {"type": "json_schema", "schema": Invoice.model_json_schema()}}, after making sure the schema meets the provider's supported subset. Either way, the arithmetic and business checks happen in your code, not the model.
Trade-offs and pitfalls
- Valid is not correct. The schema guarantees shape, not truth. A model can still put the wrong date in a perfectly valid
due_date. Validate values and spot-check with evals. - Schema subset limits. Not every JSON Schema keyword is supported, and complex or deeply nested schemas can hit provider complexity limits. Keep schemas flat and explicit.
- Field order matters. Models generate fields in schema order. Put a
reasoningorevidencefield before theanswerfield if you want the model to work through it first, and after it if you only want justification. - Truncation. If
max_tokensis hit, output is incomplete regardless of schema. Check the stop reason. - Enums beat free text. A
Literalorenumfield removes a whole category of normalization bugs. Include anotherorunknownvalue so the model is not forced to guess. - Latency on new schemas. The first call with a new schema can be slower while it is compiled. Avoid generating schemas dynamically per request.
- Feature conflicts. Some providers disallow combining structured outputs with other features (for example citations on Anthropic). Read the limitations section.
Checklist
- Every machine-read output uses schema-constrained decoding, not prompt-only JSON.
- Schemas are defined once in code (Pydantic or Zod) and reused.
- Optional fields are explicit nullables, and enums include an escape value.
- The stop reason and refusal field are checked before parsing.
- Business rules are validated after parsing, with a repair loop.
- Evals measure field-level accuracy, not just parse success.