Structured outputs: JSON mode, schemas, and how they fail
Structured outputs make a model return JSON that matches your schema. How constrained decoding works, what OpenAI, Claude, and Gemini support, and how it fails.
- Published
- Reading time
- 13 min read
In short
- There are three levels of structured output: asking for JSON in the prompt, JSON mode, which guarantees parseable JSON, and schema-constrained decoding, which guarantees the output matches a JSON Schema.
- Constrained decoding compiles the schema into a grammar and masks every token that would break it, so the model can only sample tokens that keep the output valid.
- Each provider supports a different subset of JSON Schema. OpenAI and Claude reject unsupported keywords with an error, and Gemini strips some of them without one.
- A schema guarantee still fails four ways: refusals, truncation at the token limit, schema features the provider ignores, and values that are valid JSON but wrong. Validate in code and retry with the error.
Structured outputs are an API feature that makes a model return JSON matching a JSON Schema you supply, enforced while the tokens are generated rather than checked afterward. Without them, an application that parses model output into objects breaks on a missing field, a trailing sentence, or a string where it expected a number.
There are three levels of guarantee, and they are often confused: prompting for JSON, JSON mode, and schema-constrained decoding. Only the last one guarantees the shape, and even that guarantee has four documented exceptions.
Three levels: prompting, JSON mode, and schemas
Each level guarantees more than the one before it, and only schema-constrained decoding guarantees that the fields and types match.
| Level | How you ask | What is guaranteed | What is not |
|---|---|---|---|
| Prompting for JSON | An instruction and an example in the prompt | Nothing | Parseable JSON, field names, types |
| JSON mode | json_object format on OpenAI | Output parses as JSON | Any particular schema |
| Schema-constrained decoding | A JSON Schema with strict: true or its equivalent | Output matches the schema | Correct values, completion within the token limit |
Prompting works more often than it used to, and it is still a probability. A model asked for JSON can wrap it in a Markdown code fence, add "Here is the result:", or drop a field it judged irrelevant. Code that parses this output needs a repair step, and the repair step needs tests.
JSON mode removes the parsing failures. OpenAI's structured outputs guide enables it with text.format set to { "type": "json_object" } and says it guarantees valid JSON but not adherence to a schema. It has an unusual requirement: the word "JSON" must appear somewhere in the context, or the API returns an error. The guide explains why. Without an instruction to produce JSON, the model may emit whitespace until it reaches the token limit.
Schema-constrained decoding is what providers now call structured outputs. OpenAI recommends it over JSON mode whenever the model supports it, and keeps JSON mode for older models such as gpt-4-turbo.
How constrained decoding works
Constrained decoding converts the schema into a grammar, tracks where the output is in that grammar after each token, and sets the probability of every token that would break the grammar to zero before sampling.
A model generates one token at a time by scoring every token in its vocabulary. Normally the sampler picks from all of them. With a constraint, a mask removes the tokens that cannot follow the current output. After {"status": ", a schema with "enum": ["open", "closed"] leaves only tokens that begin one of those two strings. The model still chooses between them by its own scores.
Willard and Louf described an efficient version of this in "Efficient Guided Generation for Large Language Models" (2023). They recast generation as transitions through a finite-state machine and build an index over the vocabulary in advance, so a regular expression or a context-free grammar can guide generation without scanning the vocabulary at every step. Their implementation is the open-source Outlines library, and later engines such as XGrammar build on the same idea.
Two properties of this mechanism explain most of what follows.
- Compilation has a cost. OpenAI notes that the first request with a new schema has additional latency, and later requests with the same schema do not. Claude caches compiled grammars for 24 hours from last use, and enforces complexity limits so compilation stays bounded.
- The grammar decides which tokens are legal, not which values are true. A mask can keep
"status"inside an enum. It cannot tell whether the ticket is actually open.
What OpenAI, Claude, and Gemini support
All three major APIs offer schema-constrained output, under different parameter names and with different subsets of JSON Schema. The details below are from each provider's documentation as of November 2026.
OpenAI: JSON Schema with strict mode
In the Responses API, structured outputs go in text.format with type: "json_schema", a name, the schema, and strict: true. In Chat Completions, the same schema goes in response_format. Support starts with the gpt-4o-2024-08-06 and gpt-4o-mini snapshots. Function calling uses the same engine when a tool sets strict: true, which the tool calling article covers.
{
"model": "gpt-4o-2024-08-06",
"input": "Extract the ticket: 'Login page 500s since 9am, high priority.'",
"text": {
"format": {
"type": "json_schema",
"name": "ticket",
"strict": true,
"schema": {
"type": "object",
"properties": {
"summary": { "type": "string" },
"priority": { "type": "string", "enum": ["low", "medium", "high"] },
"component": { "type": ["string", "null"] }
},
"required": ["summary", "priority", "component"],
"additionalProperties": false
}
}
}
}OpenAI's strict mode has three structural rules. Every object sets additionalProperties: false. Every property is listed in required, so an optional field is written as a union with null, as component is above. The root must be an object and cannot be anyOf. A schema that breaks the rules returns an error instead of degrading.
Recursive schemas through $defs and $ref are supported, and output keys follow schema order. The published limits are up to 5,000 object properties in total, 10 levels of nesting, 1,000 enum values across the schema, and 120,000 characters across property names, definition names, enum values, and const values.
Claude: JSON outputs and strict tool use
Claude has two entry points to the same grammar pipeline. JSON outputs use output_config.format with type: "json_schema" and return the JSON in a text block. Strict tool use sets strict: true on a tool definition and constrains the tool's input. Both are stable on the Claude API, Amazon Bedrock, Google Cloud, and Microsoft Foundry. The older output_format parameter is deprecated and now works only with the structured-outputs-2025-11-13 beta header.
Before native support, the common way to get JSON from Claude was to define one tool whose input schema was the shape you wanted and force the model to call it. Strict tool use replaces that pattern, and forcing is no longer an option on several current Claude models, which reject forced tool use with a 400 error.
Claude's subset is narrower than OpenAI's. Anthropic's structured outputs docs list these as unsupported:
- Recursive schemas,
oneOf(useanyOf),not, and external$ref. - Numeric constraints
minimum,maximum, andmultipleOf. - String constraints
minLengthandmaxLength. - Array constraints other than
minItemsof 0 or 1. additionalPropertiesset to anything exceptfalse.
An unsupported feature returns a 400 with details. Claude also has explicit complexity limits per request, counted across every strict schema together: 20 strict tools, 24 optional parameters, and 16 parameters that use anyOf or type arrays. A schema inside those limits can still fail with "Schema is too complex for compilation," and compilation times out at 180 seconds. Each optional parameter roughly doubles part of the grammar's state space, so making fields required is the first fix.
Claude's output keeps schema order with one exception: required properties come first, then optional ones. Code that depends on key order should mark every field required.
Gemini: JSON Schema on generateContent and Interactions
On generateContent, Gemini takes responseMimeType: "application/json" in the generation config together with a schema. The API reference points to responseJsonSchema, which accepts JSON Schema. The older responseSchema field takes a subset of the OpenAPI schema format. The structured output guide now shows the Interactions API, where response_format carries "mime_type": "application/json" and a schema field.
Gemini supports enum, format for dates and times, minimum and maximum, prefixItems, and enforced minItems and maxItems. It differs from the other two in how it treats the rest. minLength, maxLength, minProperties, maxProperties, uniqueItems, and contains are stripped during request normalization and ignored, with no error. A schema that says a string has at most 280 characters is accepted, and the limit is not enforced.
Oversized schemas return 400 INVALID_ARGUMENT. Google's suggested fixes match Anthropic's: less nesting and branching, more required fields, shorter property names, and complex constraints moved into descriptions.
Provider comparison
| OpenAI | Claude | Gemini | |
|---|---|---|---|
| Parameter | text.format or response_format, strict: true | output_config.format, or strict: true on a tool | responseJsonSchema with responseMimeType, or response_format in Interactions |
| Optional fields | Union with null, all fields required | Fields left out of required (24 per request) | Fields left out of required |
| Recursion | Supported | Not supported | Avoid through required fields |
| Numeric bounds | Supported | Rejected with 400 | minimum, maximum supported |
| String length | Check the guide per model | Rejected with 400 | Stripped without error |
| Unsupported keyword | Error | 400 error | Some stripped silently |
How structured outputs fail
A response from a strict schema can still be unusable in four ways, and only one of them shows up as an error status.
Refusals
When a model declines a request for safety reasons, the refusal takes precedence over the schema. On Claude the response has stop_reason: "refusal", a 200 status, billed tokens, and output that might not match the schema. On OpenAI the refusal arrives as a separate refusal content part that does not necessarily follow your format. Code that parses every 200 as schema-valid JSON breaks on the first refusal.
Claude adds a specific case. A schema property that asks for the model's step-by-step reasoning can trigger a reasoning_extraction refusal. Anthropic's advice is to ask for a short explanation instead and keep reasoning in thinking blocks.
Truncation at the token limit
A constrained response that hits the output limit stops mid-object, and the JSON does not parse. Claude reports stop_reason: "max_tokens". OpenAI's Responses API returns status: "incomplete" with incomplete_details.reason set to "max_output_tokens". The fix is a higher limit or a smaller schema, and retrying with the same limit fails the same way.
Arrays without a maximum are the usual cause. A model extracting "all line items" from a long invoice can produce more items than the limit allows.
Constraints the provider does not enforce
A keyword that a provider ignores produces output that matches the schema as compiled but not as written. Gemini strips maxLength. Claude's SDK helpers remove unsupported constraints such as minimum and move them into the field description, so the model sees them as instructions it may not follow. The Python and TypeScript helpers still validate the response against the original constraints, and the TypeScript helper skips validation when called with { transform: false }.
Claude also documents an enum casing gap. String enum and const values are not guaranteed to keep their capitalization, typically for the first letter of a word after a space, and the response completes with no error. Compare enum values case-insensitively, and avoid enum values that differ only in case.
Values that are valid and wrong
The schema constrains shape. A due_date can be a well-formed date that appears nowhere in the source, a priority can be a valid enum value that contradicts the text, and a required field can be filled with an invented value because the schema left no way to say "not found." The Gemini guide says it directly: the output is syntactically correct JSON, and you should still validate the values in your application.
Give the model a legal way to report missing data. A nullable field, or an enum value such as "unknown", gives the grammar an exit other than an invented value. Checking whether extracted values are supported by the source is a hallucination detection problem, and measuring it across a dataset belongs in your evaluation suite.
Does a schema cost accuracy?
It can. In "Let Me Speak Freely?" (2024), Tam and colleagues report a significant decline in reasoning performance under format restrictions, with stricter formats causing larger drops. Treat it as a reason to measure your own task with and without the schema, not as a fixed penalty.
Two schema habits reduce the effect. Let the model reason before it commits: Claude's grammar applies only to the final output, not to thinking blocks, and grammar state resets between sections. Keep fields in the order the model needs them, with evidence or a short explanation before the conclusion it supports.
Validate and retry with Pydantic or Zod
Treat the provider's guarantee as the first check and your own validator as the second. Define the shape once as a Pydantic model or a Zod schema, generate the JSON Schema from it, and validate every response against the original definition, including constraints the provider dropped.
from pydantic import BaseModel, Field, ValidationError, field_validator
class Ticket(BaseModel):
summary: str = Field(max_length=280) # not enforced by every provider
priority: str
component: str | None
@field_validator("priority", mode="before")
@classmethod
def normalize_priority(cls, v: str) -> str:
v = v.lower() # enum casing is not guaranteed on every provider
if v not in {"low", "medium", "high"}:
raise ValueError(f"unknown priority {v!r}")
return v
def extract(call_model, text: str, max_attempts: int = 2) -> Ticket:
"""call_model(prompt) returns (raw_text, stop_reason) from any provider."""
prompt = f"Extract the ticket from:\n{text}"
for attempt in range(max_attempts):
raw, stop = call_model(prompt)
if stop == "refusal":
raise RuntimeError("model refused; do not retry with the same input")
if stop in ("max_tokens", "max_output_tokens"):
raise RuntimeError("output truncated; raise the limit or shrink the schema")
try:
return Ticket.model_validate_json(raw)
except ValidationError as err:
if attempt == max_attempts - 1:
raise
# Send the specific error back, not a generic "try again".
prompt = f"{prompt}\n\nYour last answer failed validation:\n{err}\nReturn corrected JSON."
raise AssertionError("unreachable")Three choices in that loop matter more than the code.
- Branch on the stop reason before parsing. A refusal or a truncation is not a validation error, and sending it back for correction wastes a call.
- Retry with the error text. Pydantic and Zod both report which field failed and why, which gives the model something specific to fix.
- Cap the attempts. One retry fixes most semantic slips. A response that fails twice usually points to a schema or prompt problem that a third attempt will not solve.
The provider SDKs wrap the first half of this. Anthropic's Python SDK takes a Pydantic model in client.messages.parse() and its TypeScript SDK takes a Zod schema through zodOutputFormat(), and both return parsed_output. OpenAI's SDKs offer equivalent parse helpers, and Google's GenAI SDKs accept Pydantic and Zod schemas. The helpers translate the schema to the provider's subset, which is why the local validation step still has to run.
In an agent, the retry belongs inside the step that produced the output, and the step needs its own budget. The agent loop article covers where those budgets sit and why a validation failure should come back to the model as an error result rather than an exception.
Self-hosted models: grammars in vLLM
Open-weight inference servers implement the same masking, and they expose more of it. vLLM's structured outputs accept an OpenAI-style response_format with json_schema, and a structured_outputs extra parameter with five modes: choice, regex, json, grammar, and structural_tag.
completion = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Classify: 'The update broke my login.'"}],
extra_body={"structured_outputs": {"choice": ["positive", "negative", "neutral"]}},
)The backend defaults to auto, which picks between engines such as XGrammar and guidance per request, and can be pinned with --structured-outputs-config.backend. The older guided_json and guided_regex fields were removed in v0.12.0.
Self-hosting changes two things. The backend is now your choice, and vLLM warns that changing it can change which tokens are allowed and therefore the output, so pin it and treat a change as a model change. Regex dialects also differ between backends. For the wider choice of serving engine, see vLLM vs. SGLang.
Choosing a level
Use the strongest level the model supports, keep the schema small, and validate in code regardless.
- Use schema-constrained decoding for anything code parses: extraction, classification, routing decisions, and tool arguments.
- Use JSON mode only on models without schema support, and validate as if it were free text.
- Use plain text for answers a person reads. A schema adds compilation latency and, for reasoning-heavy tasks, possibly lower accuracy.
- Write the schema for the strictest provider you might route to. Required fields, no recursion, enums that differ by more than case, and length limits enforced in your validator work on all three APIs described here.
Log the stop reason, the validation result, and the retry count on every structured call. A rising validation failure rate after a model or schema change is the earliest sign that something drifted, and it never shows up as an HTTP error.
Frequently asked questions
What is the difference between JSON mode and structured outputs?
JSON mode guarantees that the response parses as JSON, but not that it has the fields or types you need. Structured outputs take a JSON Schema and constrain decoding so the response matches it. OpenAI recommends structured outputs over JSON mode wherever the model supports them.
How do I get structured output from OpenAI?
In the Responses API, set text.format to type: "json_schema" with a name, the schema, and strict: true. In Chat Completions, use response_format with type: "json_schema". Every object needs additionalProperties: false and every property listed in required, with optional fields written as a union with null.
Does Claude support structured outputs?
Yes. Claude supports JSON outputs through output_config.format with type: "json_schema", and strict tool use through strict: true on a tool definition. Both compile the schema into a grammar. The older output_format parameter and its beta header are deprecated.
Can structured outputs still return invalid data?
Yes. A refusal can ignore the schema, a response cut off at the token limit is incomplete JSON, some providers drop constraints such as minLength without an error, and a value can match its type and still be wrong. Check the stop reason, validate with Pydantic or Zod, and retry with the validation error.
Does constrained decoding make the model less accurate?
It can. A 2024 study by Tam and colleagues found a significant decline in reasoning performance under format restrictions, with stricter formats causing larger drops. Let the model reason before the structured answer, in a thinking block or a short field, and keep the schema to the fields you consume.
Sources
- 01Structured model outputsOpenAI API docs
- 02Structured outputsClaude API docs
- 03Strict tool useClaude API docs
- 04Structured outputGemini API docs
- 05Generating content (GenerationConfig)Gemini API reference
- 06Structured outputsvLLM docs
- 07Efficient Guided Generation for Large Language ModelsarXiv (Willard and Louf)
- 08Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language ModelsarXiv (Tam et al.)