Home / Chapter 5 · Agents
Last edited · 8 min read
Structured output
Structured output in strict mode doesn’t ask the model for a format; it enforces it: at every step the sampler zeroes the probability of tokens that would break the schema. You get a guarantee of syntax, not of correct content.
In plain wordsA form instead of free text. The model can’t skip a required field or add one of its own, and from a dropdown it can only pick one of the listed options. But the form checks the shape, not the content: in a text field the model can write anything, and from the dropdown it can pick the wrong option. When the right one is missing, it picks the nearest.
Step through generation. See where the mask cuts tokens and where it lets almost everything through, and stop at step 8
Schema: {"explanation": string, "label": "spam" | "scam" | "ok"}
Illustrative probabilities, simplified token boundaries. Struck-through tokens break the schema and get zero; the remaining probabilities are rescaled to 100%.
Follow the schema through the server step by step: what is built once per schema and what happens at every token
Same schema as above. The automaton and the vocabulary are heavily simplified, and the probabilities are illustrative.
How constrained decoding works
- A regular expression or a schema without recursion can be turned into a finite automaton. A recursive schema (such as a comment whose replies are also comments), and context-free grammars in general, need a pushdown automaton: one with a stack that remembers how many levels are still to be closed. Then some tokens depend on what is on the stack and can’t be checked in advance: XGrammar checks those at every step, and for JSON they are under 1% of the vocabulary.
- Don’t change the schema without need: a different list of
enumvalues is a new schema, so the first request with it waits for compilation again (at OpenAI only with fine-tuned models, as of October 2026). Build the schema in code the same way every time, with sorted values and a fixed field order: the same list in another order may mean a new compilation. When the list changes with every request, such as IDs from a database, measure the compilation delay. If it is too long, replace the enum with a plain string, list the IDs in the prompt and check the answer in code.
JSON mode, structured output and tool calling
- JSON mode guarantees valid JSON, but not conformance to a schema. Strict mode guarantees the schema:
json_schemawithstrict: truein OpenAI’s API,output_config.formatin Anthropic’s. - Tool calling is the same JSON in a different role: the model writes a tool name and arguments (see “Tools (function calling)”). Without strict mode the format is only learned, so the arguments usually, but not always, match the schema.
strict: trueon a tool definition turns on the same masking. In OpenAI’s Responses API, tools are strict by default when the schema allows it and otherwise silently fall back to best effort (the response showsstrict: false), so set the flag explicitly. - Strict modes support a subset of JSON Schema. OpenAI requires every field to be listed in
required(an optional field is a type that allowsnull) and every object to haveadditionalProperties: false, with limits of 5,000 properties and 10 levels of nesting. Anthropic doesn’t support, among other things, recursive schemas or string length limits, and allows at most 20 strict tools per request, 24 optional parameters and 16 union-typed parameters across all strict schemas. Beyond these limits the API returns “Schema is too complex for compilation”.
What the guarantee doesn’t cover
- Content. The model can still write a wrong invoice number or a made-up date in a valid format. Business rules (ranges, totals, whether IDs exist) are checked by code, and the error goes back to the model with a specific message, with a cap on retries.
- The completeness of a list. When the model has to label emails A, B and C, an array of results accepts A, A, B, because strict modes don’t support
uniqueItems. Make the email IDs required properties of an object, such as{"A": "spam", "B": "ok", "C": "scam"}: then each appears exactly once. But every new list is a new schema to compile. - A response cut off by the length limit (
stop_reason: "max_tokens",finish_reason: "length") or a refusal: OpenAI returns it in a separaterefusalfield, Anthropic asstop_reason: "refusal". In either case the content may not match the schema. Check the stop reason before parsing. - Letter case in enums at Anthropic. String
enumandconstvalues can come back with different capitalisation (“Conversation Topic 3” for “Conversation topic 3”), with a normal stop reason and no error, in JSON outputs and strict tool use alike. Compare them case-insensitively and avoid values that differ only in case. - What the model wanted to say. When the most likely answer lies outside the schema, the mask pushes the model into the nearest allowed one, like phishing in the widget: it lands on “scam”, and without that value it would land on “spam”. Add an escape hatch: an “other” or “unknown” value and a comment field.
- Reasoning quality. The model writes left to right, so a decision written before the justification can’t use it, and the justification can no longer change it. Put a short justification field (for example
explanation) before the decision field and list both inrequired: Anthropic writes required properties before optional ones (OpenAI keeps the schema’s order and requires every field anyway). A reasoning model’s thinking doesn’t replace this order: on a task it judges simple, it may think briefly or not at all (see “Reasoning models”), and the reasoning-token count inusageshows whether it did. OpenAI gives the same advice for GPT-5 atminimaleffort: a brief explanation at the start of the answer (2025). Don’t ask the model to repeat its reasoning in the JSON: on newer Claude models areasoningfield or a request for step-by-step thinking can trigger areasoning_extractionrefusal, and Anthropic advises keeping reasoning in the thinking block (as of October 2026). In the “Let Me Speak Freely?” study (2024), format restrictions lowered scores on reasoning tasks. The result is contested: a re-run with matched prompts (.txt, “Say What You Mean”) found no drop. In the “Structure Tax” study (2026), where the format was set in the prompt with no mask, the drop came mostly from field order: answer-first schemas sharply cut accuracy on multi-step maths, most in small models. Other work measures a cost from the mask itself, mainly with small models and tight schemas (Reddy et al., 2026). When your evals show a drop, let the model answer freely and extract the structure with a second, cheap call. - The field order in your code. What counts is the order in the schema you actually send. For example, from
record Rating(String explanation, String decision)the OpenAI and Anthropic Java SDKs build a schema with"properties": {"decision": …, "explanation": …}, because they sort fields alphabetically, even with the@JsonPropertyOrderannotation (as of October 2026). The model then picks the decision first and justifies it only afterwards. Check the order in the logged request.
Check yourself
How do you guarantee that a model returns JSON matching a schema, and what does that guarantee not cover?
In strict mode the schema is compiled into a grammar, and at every step the sampler zeroes out tokens that would break it. The JSON matches the schema unless the length limit cuts it off or the model refuses, which the stop reason shows. At Anthropic, enum values can also come back in a different letter case, so compare them case-insensitively. The guarantee covers syntax, not content: values are validated in code. The schema gets an escape hatch, because a tight enum pushes the model into the nearest option, and a short justification field goes before the decision, because the model writes left to right. Strict tool calling works the same way.
Po polsku
W trybie ścisłym schemat kompiluje się do gramatyki, a w każdym kroku sampler zeruje prawdopodobieństwo tokenów, które by ją złamały. JSON pasuje do schematu, chyba że limit długości utnie odpowiedź albo model odmówi, co widać po powodzie zatrzymania. U Anthropic wartości enum mogą też wrócić z inną wielkością liter, więc porównuje się je bez jej rozróżniania. Gwarancja dotyczy składni, nie treści: wartości waliduje kod. Schemat dostaje wyjście awaryjne, bo ciasny enum wpycha model w najbliższą opcję, a pole z krótkim uzasadnieniem stoi przed decyzją, bo model pisze od lewej do prawej. Tool calling w trybie strict działa tak samo.
Follow-up questions (4)
- Can enforcing a format lower quality?
- Yes, when the schema asks for the decision before the reasoning or has no “other” option. What helps: a short justification field before the decision, also with a reasoning model, or two steps: a free-form answer first, then extraction.
- JSON mode, structured output or tool calling: when do you use which?
- Structured output when the answer feeds your code. Tool calling when the model has to choose an action from several, with strict mode for the arguments. JSON mode only where there is no strict mode.
- How do you enforce a schema on a self-hosted model?
- vLLM and SGLang have built-in constrained decoding engines (including XGrammar and llguidance): the schema turns into an automaton, and the automaton into a token mask at every step. The per-token overhead is small; the cost is compiling each new schema. With a reasoning model, start the server with a reasoning parser (e.g. --reasoning-parser in vLLM); otherwise the grammar applies from the first token and cuts off the thinking.
- The JSON parses, but the data is wrong. What next?
- Validation in code (constrained types, business rules) and a retry with a specific error message, with a cap on attempts. A recurring error is a signal to change the schema or the prompt, and the case goes into the eval set.
Sources
- OpenAI docs: Structured Outputs
- Claude docs: Structured outputs
- OpenAI Cookbook: GPT-5 prompting guide (Minimal reasoning, 2025)
- Willard, Louf: Efficient Guided Generation for Large Language Models (arXiv)
- Dong et al.: XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models (arXiv)
- Tam et al.: Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models (arXiv)
- .txt: Say What You Mean, a response to “Let Me Speak Freely?”
- Reddy et al.: The Hidden Cost of Structured Generation in LLMs (ICML 2026)
- Kumar et al.: Structure Tax: How Structured Output affects LLMs Performance (arXiv, 2026)
- victools jsonschema-generator: Order of Object Properties (the schema generator in the OpenAI and Anthropic Java SDKs)