Skip to content
Goal: Deep understanding✓ Sources verified 2026-11-24JSON SchemaPydanticZod

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:

ApproachMechanismReliabilityWhen to use
Prompt constraintsWrite "please output JSON" in the prompt and give an exampleLow: may add explanatory text, miss fields, or get types wrongPrototyping
JSON modeGuarantees valid JSON, but not that it matches your schemaMediumCompatibility 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 schemaHighFirst 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) ​

ProviderUsageSDK helper
AnthropicRequest 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 periodPython client.messages.parse() takes a Pydantic model directly
OpenAIResponses API uses text.format (type: "json_schema", strict: true); Chat Completions uses response_format; function calling also supports strict: truePass 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
  1. Send it to the model: ContractFields.model_json_schema() or the SDK's parse method.
  2. Validate the model output: ContractFields.model_validate_json(text).
  3. 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 queue

Common pitfalls ​

  1. Relying on the schema without business validation: amounts, dates and party names can be "correctly formatted but made up". Add an evidence field that quotes the source, then check programmatically that the quote really exists in the source.
  2. Too little field description: description goes into the model's context. Spell out the unit, the format, and what to fill in when the value can't be found.
  3. Mishandling optional fields: the model invents values when it can't find them. Explicitly allow null and say in the prompt "use null if not found, don't guess".
  4. Truncated output: when extracting long lists, max_tokens runs out and the JSON is incomplete. Check stop_reason first.
  5. Unhandled refusals: a safety refusal won't return your schema, so it needs its own branch.

Common interview questions ​

  1. What are the differences in reliability between prompt constraints, JSON mode and Structured Outputs?
  2. How does constrained decoding guarantee valid JSON? Can it guarantee correct content?
  3. How do you handle structured output that fails validation? How many retries before handing over to a human?
  4. How do you stop the model from inventing field values? (evidence quotes + source comparison + confidence)
  5. Why define the schema with Pydantic? How does it tie in with FastAPI?

How it relates to my projects ​

  • The extract → validate steps 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_format to output_config.format between 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 ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section