Structured Output: Getting LLMs to Return Reliable, Validatable JSON
The core of the "output" step in the pipeline: extraction results are pushed back into the customer's systems, so they must be validatable structured data.
Core concepts
Three approaches, from least to most reliable:
| Approach | Mechanism | Reliability | When to use |
|---|---|---|---|
| Prompt constraints | Write "please output JSON" in the prompt and give an example | Low: may add explanatory text, miss fields, or get types wrong | Prototyping |
| JSON mode | Guarantees valid JSON, but not that it matches your schema | Medium | Compatibility with older APIs |
| Schema-constrained decoding (Structured Outputs / strict tool use) | Tokens are constrained by the JSON Schema during generation, so output always matches the schema | High | First choice in production |
How it works
- Constrained decoding: the server compiles the JSON Schema into a grammar and masks out any candidate token that would violate it, so the result is always structurally valid.
- Structurally valid ≠ correct content: a schema only guarantees fields and types. Whether the amount is the amount in the source text, or whether a date makes sense, still needs business validation. The OpenAI docs explicitly note that applications must still handle refusals, incomplete responses and business rules a schema can't express.
- Schemas are a subset: each provider supports only a subset of JSON Schema (e.g. requirements around
additionalProperties, recursion and some format keywords). Check the official "supported schemas" list before writing a complex schema.
The two providers' official APIs (verified 2026-11)
| Provider | Usage | SDK helper |
|---|---|---|
| Anthropic | Request parameter output_config.format with type: "json_schema"; plus strict: true on tool definitions (strict tool use). The earlier output_format parameter and beta header still work during the transition period | Python client.messages.parse() takes a Pydantic model directly |
| OpenAI | Responses API uses text.format (type: "json_schema", strict: true); Chat Completions uses response_format; function calling also supports strict: true | Pass Pydantic in Python, Zod in JS |
In practice
Define the schema with Pydantic, reuse one definition in three places
python
from pydantic import BaseModel, Field, field_validator
from decimal import Decimal
from datetime import date
class ContractFields(BaseModel):
party_a: str = Field(description="Full legal name of party A, as written in the contract")
party_b: str
amount: Decimal = Field(description="Total contract amount, in CNY")
payment_days: int = Field(ge=0, le=365, description="Payment term (days)")
sign_date: date | None = None
evidence: list[str] = Field(description="Source text snippet for each field, for human review")
@field_validator("party_a", "party_b")
@classmethod
def not_placeholder(cls, v: str) -> str:
if v.strip() in {"", "未知", "N/A"}:
raise ValueError("Party name missing")
return v- Send it to the model:
ContractFields.model_json_schema()or the SDK's parse method. - Validate the model output:
ContractFields.model_validate_json(text). - Use it as the FastAPI response model: the frontend gets the same structure.
When validation fails: regenerate with the errors included
python
from pydantic import ValidationError
for attempt in range(2):
raw = await llm.generate(messages, schema=ContractFields.model_json_schema())
try:
return ContractFields.model_validate_json(raw)
except ValidationError as e:
messages += [
{"role": "assistant", "content": raw},
{"role": "user", "content": f"The output above failed validation: {e.errors()}. Fix only these fields and output again."},
]
raise NeedHumanReview("Structured output failed validation twice") # goes to the human review queueCommon pitfalls
- Relying on the schema without business validation: amounts, dates and party names can be "correctly formatted but made up". Add an
evidencefield that quotes the source, then check programmatically that the quote really exists in the source. - Too little field description:
descriptiongoes into the model's context. Spell out the unit, the format, and what to fill in when the value can't be found. - Mishandling optional fields: the model invents values when it can't find them. Explicitly allow
nulland say in the prompt "use null if not found, don't guess". - Truncated output: when extracting long lists,
max_tokensruns out and the JSON is incomplete. Checkstop_reasonfirst. - Unhandled refusals: a safety refusal won't return your schema, so it needs its own branch.
Common interview questions
- What are the differences in reliability between prompt constraints, JSON mode and Structured Outputs?
- How does constrained decoding guarantee valid JSON? Can it guarantee correct content?
- How do you handle structured output that fails validation? How many retries before handing over to a human?
- How do you stop the model from inventing field values? (evidence quotes + source comparison + confidence)
- Why define the schema with Pydantic? How does it tie in with FastAPI?
How it relates to my projects
- The
extract → validatesteps of the AI Document Review Pipeline: the Pydantic schema, retry-with-errors and human handoff on this page are the core of W3.
To be verified / may go stale
- Anthropic's structured output parameter moved from the beta
output_formattooutput_config.formatbetween 2025-11 and 2026; check the official page for which models are supported. - The JSON Schema subset each provider supports keeps growing. Check the docs before using complex schemas (recursion,
oneOf).
Sources
- Anthropic Docs: Structured outputs —
output_config.format,stricttools,messages.parse() - OpenAI Docs: Structured model outputs —
text.format,strict: true, refusal handling, difference from JSON mode - OpenAI: Introducing Structured Outputs in the API (2024) — explanation of constrained decoding
- Pydantic Docs: Models —
model_validate,model_validate_json - Pydantic Docs: JSON Schema —
model_json_schema()
