Structured outputs & JSON mode

In one sentence

Don't ask for JSON, enforce it: strict schema mode masks every token that would break your schema, so output always parses. It guarantees shape, not truth, so still validate values and retry.

Analogy: A paper form with labeled boxes and checkboxes instead of a blank page: every field comes back in the right place, but nothing stops someone from writing a wrong number in a box.

The grammar guarantees shape token by token; only your validators can check whether the values are right.

How it works

  • Prompt-only JSON breaks at scale; JSON mode always parses but doesn't guarantee your keys or types.
  • Strict mode compiles the schema into a grammar: constrained decoding masks invalid tokens before sampling.
  • Keys generate in schema order, so put a reasoning field before the answer; rigid schemas can lower quality.
  • Use enums for classification so labels can't be invented, and nullable fields for absent values.
  • Allow 1–2 retries with the validation error; if over ~1% of calls need one, fix schema or prompt.

Check yourself

Answer to mark it learned; your answers aren't scored.

You moved ticket extraction from "reply in JSON" to a strict schema with order_id: str. Parse errors are gone, but records now carry an order_id even when the ticket mentions none. Most likely cause and fix?

Go deeper

Full explanation

Structured outputs make the model return data your code can consume. Three levels of guarantee:

  1. Prompt only ("reply in JSON"): works most of the time, and at a million calls "most" means thousands of stray code fences, trailing prose and missing keys.
  2. JSON mode (response_format: json_object): always syntactically valid JSON, but any JSON. Your keys and types are not guaranteed.
  3. Strict schema (OpenAI Structured Outputs; Gemini, Anthropic and vLLM offer equivalents): constrained decoding. The schema is compiled into a grammar, and at every step the tokens that would violate it are masked out before sampling. The output always matches types, required keys and enums.

In code you declare a Pydantic model; the SDK turns it into JSON Schema and parses the reply back into a typed object.

What it does not give you is correct values: a schema-valid invoice can still carry a hallucinated total. So validate semantics (Pydantic validators, cross-field checks), retry with the error message, and handle refusals and truncation.

Design rules:

  • Enums (Literal[...]) for classification, so labels can't be invented.
  • Reasoning field first. Keys are generated in schema order; an answer before reasoning commits before thinking. A rigid schema with no room to reason can lower quality.
  • Nullable, not omitted. Strict mode requires every key, so let absent values be null.
Code Strict schema with Pydantic, validation and retry
pythonStrict schema with Pydantic, validation and retry
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError, field_validator

client = OpenAI()
MODEL = "gpt-4.1-mini"  # any model with Structured Outputs

class Triage(BaseModel):
    # Keys are generated in order: gather evidence first, decide second
    reasoning: str = Field(description="1-3 sentences of evidence from the ticket")
    category: Literal["billing", "bug", "how_to", "account", "other"]  # closed set
    priority: Literal["P1", "P2", "P3"]
    order_id: str | None  # strict mode needs every key: optional means nullable

    @field_validator("order_id")  # semantic rule the grammar cannot express
    @classmethod
    def looks_real(cls, v):
        if v is not None and not v.startswith("ORD-"):
            raise ValueError("order_id must look like ORD-123, or be null")
        return v

def triage(ticket: str, tries: int = 3) -> Triage:
    msgs = [{"role": "system", "content": "Triage the support ticket."},
            {"role": "user", "content": ticket}]
    for _ in range(tries):
        try:
            r = client.chat.completions.parse(model=MODEL, messages=msgs, response_format=Triage)
        except ValidationError as e:  # valid shape, wrong value: feed the error back
            msgs.append({"role": "user", "content": f"Fix this and answer again: {e}"})
            continue
        msg = r.choices[0].message
        if msg.refusal:  # safety refusals come back as text, not as your schema
            raise RuntimeError(msg.refusal)
        return msg.parsed
    raise RuntimeError("no valid output after retries")
Real example

An invoice pipeline extracts 50K PDFs a month. With only "return JSON" in the prompt, even a 1% parse-failure rate means ~500 broken records a month, each a manual fix. A strict schema makes parse failures impossible, but a validator that checks sum(line_items) == total still catches cases where the model misread a digit. Those get one retry with the validation error in the prompt, then go to a human review queue instead of the ledger.

Trade-offs +3 · −3

+ You gain

  • Parsing never fails: no regex, no stripping code fences.
  • Enums turn classification into a closed set of labels.
  • The schema doubles as a typed contract and documentation between teams.

− You pay

  • Guarantees shape, not truth: values can still be wrong or hallucinated.
  • A rigid schema with no room to think can lower quality on reasoning tasks.
  • Only a subset of JSON Schema is supported; on fine-tuned OpenAI models and some self-hosted engines, the first call with a new schema pays a compile delay.

Use it when

Whenever code consumes the output: extraction, classification, routing, tool arguments, agent state, LLM-judge scores. Default to strict schema; use JSON mode only where strict isn't available.

Avoid it when

Prose for humans (chat answers, long-form writing), where a schema adds nothing. If you need metadata too, wrap the prose in one string field.

Numbers to know 3
  • OpenAI eval: gpt-4o-2024-08-06 with Structured Outputs scored 100% on complex schema following; gpt-4-0613 scored under 40%.
  • Tam et al. 2024: stricter format constraints generally meant larger drops on reasoning tasks.
  • Rule of thumb: allow 1–2 retries with the validation error; if more than ~1% of calls need one, fix the schema or the prompt.
Common pitfalls 4
  • Trusting JSON mode to enforce your schema: it guarantees braces, not keys. On OpenAI it also errors unless "JSON" appears in the prompt.
  • Putting answer before reasoning: the model commits before it thinks.
  • Required fields with no null option: the model invents an order id rather than leave it empty.
  • Ignoring refusals and max_tokens truncation, which return text or cut-off JSON instead of your object.
Interview questions 2

Answer out loud first, then reveal.

JSON mode vs structured outputs: what's the difference, and how does the guarantee work?Show answer

JSON mode guarantees syntactically valid JSON, any JSON. Structured outputs guarantee my schema. The mechanism is constrained decoding: the provider compiles the schema into a grammar and, at each decoding step, masks every token that would make the output invalid, so the model only samples legal continuations. That gives me types, required keys and enums for free. What it can't guarantee is that the values are right, so I still validate semantics with Pydantic, retry with the error, and route repeated failures to review.

After switching to a strict schema, extraction accuracy dropped. Why, and what do you do?Show answer

Usually the schema took away the room to think, or forced an answer the model wasn't ready to give. Keys are generated in order, so I add a short evidence or reasoning field before the answer fields, make absent values nullable instead of forcing a guess, and move guidance into field descriptions. If the task needs long reasoning, I split it: free-text reasoning first, then a cheap structuring call. And I compare both versions on the same eval set, because the published results on format restrictions disagree.