Constrained decoding explained: how structured outputs force LLMs to emit valid JSON
Structured outputs promise JSON that always parses. The trick is constrained decoding: the engine compiles your schema into a grammar and masks every token that would break it. This guide builds a tiny version in Python and shows the costs and traps.
- Reading time
- 17 min
- Sections
- 8
- Code examples
- 3
- Tables
- 2
- Sources
- 8
- Published
- 25 Nov 2026
- What changed
- OpenAI launches Structured Outputs with strict JSON Schema
- Why it matters
- Constrained decoding turns "valid JSON" from a hope into a guarantee, apart from refusals and truncation.
- What to do
- Turn on strict mode where you parse output
Ask a language model for JSON and most of the time you get JSON. "Most of the time" is the problem. A pipeline that processes a million records a day cannot afford a few thousand replies that start with "Sure, here is the JSON" or stop one brace short. Structured outputs fix this at the source. Instead of hoping the model complies, the serving engine only lets it choose tokens that keep the output valid against a schema.
The technique behind it is called constrained decoding, or grammar-constrained decoding. It is now standard across hosted APIs and open-source engines. OpenAI, Anthropic and Google offer it in their APIs, and open-source engines such as vLLM and llama.cpp ship it through libraries such as XGrammar, Outlines and Guidance. This article explains how a schema turns into a token mask, builds a working toy version in Python, and covers the costs and failure modes that matter in production.
What happened
OpenAI launches Structured Outputs with strict JSON Schema (6 August 2024)
OpenAI added Structured Outputs to its API. The announcement says that on its evaluation of complex JSON Schema following, gpt-4o-2024-08-06 with Structured Outputs scored 100%, compared with below 40% for gpt-4-0613. Without the decoding constraint, the new model alone scored 93%. OpenAI describes the method directly: the JSON Schema is converted into a context-free grammar, and after each token the engine masks out tokens that would break it. The first request with a new schema pays a preprocessing cost; OpenAI says typical schemas take under 10 seconds and complex ones up to a minute.
XGrammar paper describes a fast structured generation engine (22 November 2024)
Yixin Dong, Tianqi Chen and colleagues posted "XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models". Its key idea is to split the vocabulary into tokens whose validity can be checked ahead of time and tokens that must be checked at run time against the current parse state, plus a persistent stack to speed up the runtime checks. The abstract claims up to 100x speedup over existing solutions. XGrammar is one of the backends in vLLM and other engines.
JSONSchemaBench measures real-world schema support (18 January 2025)
Saibo Geng, Michał Moskal, Harsha Nori and co-authors released JSONSchemaBench, built from 10,000 real-world JSON schemas. They compared six frameworks: Guidance, Outlines, llama.cpp, XGrammar, OpenAI and Gemini. Their main finding is that support for real schemas varies widely between engines, and that hard schemas from GitHub and JSON Schema Store expose gaps everywhere. The numbers are in the comparison section below.
Claude structured outputs reach general availability
Anthropic launched structured outputs as a public beta in November 2025; the beta header is structured-outputs-2025-11-13. Its documentation now lists the feature as generally available on all models, with the request shape output_config.format of type json_schema. The docs say "Compiled grammars are cached for 24 hours from last use" and set limits of 20 strict tools, 24 optional parameters and 16 union-typed parameters per request, with a compilation timeout of 180 seconds.
How a schema becomes a token mask
Constrained decoding has three parts: a grammar, a parser state and a mask.
The grammar. A JSON Schema describes allowed values: an object with a sentiment field whose value is one of three strings, say. The engine converts that schema into a formal grammar. Simple constraints, such as an enum or a regular expression, fit a finite-state machine (FSM). Nested or recursive structures, such as a JSON tree of unknown depth, need a context-free grammar (CFG) with a stack. OpenAI's announcement makes this point: its CFG approach handles recursive schemas that FSM-only methods struggle with.
The parser state. As tokens are generated, the engine feeds them through the grammar and tracks where it is: "inside an object, after the key, expecting a string".
The mask. Before each sampling step, the engine computes which vocabulary tokens could legally come next from the current state. It sets the logits of every other token to minus infinity. After softmax those tokens have probability zero, and the remaining probabilities are renormalised:
p'_i = p_i · m_i / Σ_j p_j · m_j, where m_i = 1 if token i is allowed, else 0.
An everyday analogy: a form on a website that only offers the valid options in a drop-down. You still choose, but you cannot type something the form will reject. The model still ranks the options; the mask only removes the ones that break the schema.
Why tokens make this hard
Grammars work on characters; models emit tokens, and a token can span several grammar symbols. In a typical BPE vocabulary, {" or "} may be a single token, and a word like positive may be one token while pos is another. So the engine must check, for each token, whether appending all its characters keeps the output a valid prefix of some string in the language. With vocabularies around 128,000 tokens, doing this naively for every token at every step is too slow. That is why engines precompute: Outlines builds an index from FSM states to allowed tokens, and XGrammar precomputes masks for context-independent tokens and checks only the rest at run time. A bitmask for 128,000 tokens takes 128,000 / 8 = 16,000 bytes per state. If BPE details are new to you, the site's guide to BPE tokenizers and the BPE simulation explain how these multi-character tokens arise.
A working toy implementation
The following Python script implements the core loop for a tiny schema. The allowed outputs are {"s":"pos"}, {"s":"neg"} and {"s":"neu"}. The toy vocabulary includes helpful tokens, harmful ones such as Sure, and a tempting one, positive, that the schema does not allow.
VALID = ['{"s":"pos"}', '{"s":"neg"}', '{"s":"neu"}']
vocab = ['Sure', '{"s":"', '{"', 's":"', 'pos', 'neg', 'neu',
'positive', '"}', '"', '}', ' ']
def allowed(prefix):
# a token is allowed if prefix + token is still a prefix of a valid output
return [t for t in vocab if any(v.startswith(prefix + t) for v in VALID)]
def renormalise(probs, allowed_tokens):
mass = sum(probs.get(t, 0.0) for t in allowed_tokens)
return {t: round(probs.get(t, 0.0) / mass, 4) for t in allowed_tokens}, mass
step1 = {'Sure': 0.40, '{"s":"': 0.35, '{"': 0.15, ' ': 0.10}
print(allowed('')) # ['{"s":"', '{"']
print(renormalise(step1, allowed(''))) # ({'{"s":"': 0.7, '{"': 0.3}, 0.5)
step2 = {'positive': 0.50, 'pos': 0.30, 'neg': 0.12, 'neu': 0.05, '"': 0.03}
print(allowed('{"s":"')) # ['pos', 'neg', 'neu']
print(renormalise(step2, allowed('{"s":"')))
# ({'pos': 0.6383, 'neg': 0.2553, 'neu': 0.1064}, 0.47)
Walk through the numbers. At step 1 the model gives 40% to Sure and 10% to a space, so half its probability mass would start an invalid reply. The mask keeps {"s":" and {", whose combined mass is 0.35 + 0.15 = 0.50, and renormalises them to 0.35 / 0.50 = 0.70 and 0.15 / 0.50 = 0.30. Notice that two different tokenisations of the same text are both allowed; real engines must handle that too.
At the value step, the model's favourite token is positive with 0.50. The schema only allows pos, so the mask removes it. The allowed mass is 0.30 + 0.12 + 0.05 = 0.47, and pos becomes 0.30 / 0.47 = 0.6383. The output is valid, but the model was pushed away from what it wanted to say. Lesson: name enum values the way the model naturally writes them. An enum of positive, negative, neutral would fit this model better than pos, neg, neu.
Without the constraint, and treating the steps as independent with a 0.9 chance of closing correctly, the chance of a valid reply on this path would be 0.35 × 0.47 × 0.9 = 0.148. With the constraint it is 1, unless generation is cut off.
The distortion problem
Masking makes every output valid, but it does not sample from "the model's distribution restricted to valid outputs". Park and colleagues call this out in "Grammar-Aligned Decoding" (NeurIPS 2024): constrained decoding can "distort the LLM's distribution". A two-step example shows why.
Suppose the only valid outputs are ab and c. The model gives a probability 0.9 and c 0.1 at the first step, but after a it gives b only 0.01, because it rarely wants to write ab. The true probability of each valid output is P(ab) = 0.9 × 0.01 = 0.009 and P(c) = 0.1. Normalised over valid outputs, that is 0.009 / 0.109 = 0.0826 for ab and 0.9174 for c. Token masking decides greedily step by step: at step 1 both a and c are allowed, so it picks a with 0.9, then forces b. It returns ab 90% of the time, the output the model considered least likely.
The paper proposes ASAp (adaptive sampling with approximate expected futures) to correct this using earlier samples. In practice, most teams reduce the problem by designing schemas the model finds natural, putting free-text reasoning fields before the constrained answer fields, and evaluating outputs rather than only validating them.
Engines and APIs compared
JSONSchemaBench gives the clearest public comparison. Its Table 4 reports two numbers per engine: empirical coverage (the share of schemas for which the engine produced valid output in the test) and compliance rate. Open-source engines were tested with Llama-3.2-1B; OpenAI and Gemini used their own models, so the paper warns those numbers are not directly comparable.
| Dataset | Guidance | llama.cpp | Outlines | XGrammar | OpenAI |
|---|---|---|---|---|---|
| GlaiveAI | 0.96 | 0.95 | 0.95 | 0.93 | 0.89 |
| GitHub Easy | 0.86 | 0.75 | 0.59 | 0.79 | 0.29 |
| GitHub Medium | 0.69 | 0.57 | 0.29 | 0.52 | 0.12 |
| GitHub Hard | 0.41 | 0.39 | 0.03 | 0.28 | 0.09 |
| JSONSchemaStore | 0.30 | 0.38 | 0.09 | 0.33 | 0.06 |
Values are empirical coverage from the paper's version 3 (February 2025). OpenAI's compliance rate on schemas it accepts was high (1.00 on most suites), but it accepted fewer schemas, which is why its coverage is low. All of these engines have shipped many releases since, so treat the table as a snapshot of the problem, not a current ranking.
Speed is the other axis. In the same paper, with Hugging Face Transformers as the backend, median grammar compilation time on GitHub Hard was 0.01 s for Guidance and 0.30 s for XGrammar, and median time per output token was 35.88 ms and 65.20 ms respectively. With llama.cpp as the backend, Outlines needed a median 8.05 s to compile GitHub Medium schemas. Compilation is a one-off cost per schema that caching hides; per-token overhead is paid on every token.
How to call it
| Platform | How you request it | Notes from the docs |
|---|---|---|
| OpenAI API | response_format with type: json_schema and strict: true |
Subset of JSON Schema; first use of a schema adds latency |
| Claude API | output_config.format with type: json_schema; strict: true per tool |
Grammars cached 24 hours; limits of 20 strict tools, 24 optional and 16 union parameters |
| vLLM | structured_outputs with choice, regex, json, grammar or structural_tag |
Backend chosen by --structured-outputs-config.backend, default auto |
Against a vLLM server, a JSON-constrained request through the OpenAI-compatible client looks like this, following the vLLM documentation's extra_body pattern:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
schema = {"type": "object",
"properties": {"sentiment": {"enum": ["positive", "negative", "neutral"]}},
"required": ["sentiment"], "additionalProperties": False}
resp = client.chat.completions.create(
model="HuggingFaceTB/SmolLM2-1.7B-Instruct",
messages=[{"role": "user", "content": "Classify: the delivery was late again."}],
extra_body={"structured_outputs": {"json": schema}},
)
print(resp.choices[0].message.content)
The site's structured outputs tool page and vLLM page cover setup, and the serving topic shows where the constraint sits in a serving stack.
Continue learning
How this article connects
7 pages link to or from it. Drag to turn, click a dot to open it.
- vLLM
- Structured outputs
- llama.cpp reaches 1.0: how GGUF, quantization, ggml backends and llama-s
- Inside a large language model: tokens, attention, sampling and the KV ca
- Model serving: inference servers, autoscaling and LLM serving engines
- Building MCP tools with Python SDK 2.3: typed tools, safe errors and the
- How BPE tokenizers work: training merges, byte-level fallback and choosi
Use cases and examples
1. Ticket classification at volume. A support platform labels incoming tickets with a model behind vLLM. Using our toy numbers, an unconstrained reply follows the valid path only about 15% of the time, and even a well-prompted model that is right 99% of the time leaves 10,000 broken replies in a million. With a choice or enum constraint, every reply parses; what remains to monitor is whether the label is correct, which needs evaluation, not validation.
2. Agent tool calls. An agent framework sends tool definitions with strict: true so arguments always match each tool's schema. On the Claude API this works for up to 20 strict tools per request, per the documentation. A schema error then becomes impossible, and failures show up as wrong argument values instead, which the ReAct tool-calling simulation lets you trace step by step. For building the tools themselves, see the MCP Python SDK tutorial.
3. Extraction with a reasoning field. A finance team extracts invoice totals. A schema with only total forces the model to commit to a number at the first value token. Adding a notes string before total lets it write its working inside valid JSON first, provided notes comes earlier in the output (Anthropic's docs say required properties appear first, followed by optional ones, so both should be required). The distortion example shows why this matters: the narrower the choice at a step, the more the mask can bend it, so the team measures field accuracy on a labelled sample before and after the change.
4. Local models on a laptop. A developer runs a small GGUF model with llama.cpp and uses its grammar support to produce config files. In JSONSchemaBench, llama.cpp covered 0.95 of GlaiveAI schemas but 0.39 of GitHub Hard schemas with a 1B model, so complex schemas may need simplifying. The llama.cpp 1.0 article covers that runtime.
What it means in practice
Constrained decoding turns "valid JSON" from a hope into a guarantee, apart from refusals and truncation. It does not guarantee correct values, and it can bend the model's choices when the schema fights its habits. The engineering work moves from writing retry loops for parse failures to designing schemas the model finds natural, caching compiled grammars, and evaluating content. Schema support also differs between engines and APIs. Each supports a subset of JSON Schema, and hard real-world schemas still fail in some engines, so test your actual schemas on your actual engine. For how decoding fits into the wider model, see inside a large language model.
What to do now
- Turn on strict mode where you parse output. Use
strict: trueor the provider's JSON Schema format instead of prompt-only instructions. - Write enums in the model's own words. Prefer
positiveoverpos; our toy example lost half the model's preferred mass to a short enum. - Put free-text fields before narrow fields. A reasoning or notes field ahead of the answer reduces distortion.
- Keep schemas within platform limits. On the Claude API that means at most 20 strict tools, 24 optional and 16 union parameters per request.
- Warm the grammar cache. Send one request per new schema at deploy time so users do not pay the compilation latency.
- Handle refusals and truncation. Check
stop_reasonor the finish reason; a cut-off reply can still be invalid. - Benchmark your own schemas. Run your real schemas through your engine, as JSONSchemaBench did, before relying on coverage.
- Evaluate values, not just shape. Add accuracy checks on the fields, because a valid object can still hold a wrong number.
Risks and open questions
Valid is not correct. OpenAI's own announcement notes that values can still be wrong, such as a mistake in a maths step. Schema compliance can hide errors that free text would have made visible.
Distribution distortion. Token masking can push outputs toward choices the model considered unlikely, as the two-step example shows. Methods such as ASAp address this, but they are not standard in production engines.
Schema coverage gaps. Every engine supports only part of JSON Schema. Unsupported keywords may be dropped or rejected, and the SDKs may move constraints such as minimum into descriptions instead of enforcing them.
Latency spikes on new schemas. Compilation can take seconds or more for complex schemas, which matters for systems that generate schemas on the fly.
Watch next: whether engines adopt distribution-aligned constrained sampling by default, and whether newer JSONSchemaBench runs show the coverage gap on hard schemas closing.
Frequently asked questions
Is JSON mode the same as structured outputs?
No. A plain JSON mode aims only for syntactically valid JSON. Structured outputs enforce a specific schema: required fields, types and enum values. If your code depends on field names, you need the schema version.
Does constrained decoding slow generation down?
It adds a one-off compilation cost per schema and a small per-token cost for computing and applying masks. JSONSchemaBench measured median compilation from about 0.01 s to over 8 s depending on engine and schema set. Caching compiled grammars removes the repeat compilation cost.
Can the output still be invalid?
Yes, in a few cases. If the model refuses or hits the token limit, the reply may stop before the JSON is complete. Anthropic's documentation lists refusal and max_tokens stop reasons as cases to handle.
Does it make the model less accurate?
It can, when the schema forces choices the model would not make. The grammar-aligned decoding paper shows the distribution can be distorted. Natural field names, reasoning fields before answers, and evaluation keep the effect small.
Which open-source backend should I use?
vLLM picks one automatically by default, and supports several. Coverage and speed differ by schema type, so the best test is your own schemas. JSONSchemaBench is a useful starting point for comparison.
Summary
Structured outputs work by constrained decoding: the schema is compiled into a grammar, the engine tracks the parse state, and at every step it masks tokens that would break the grammar, then renormalises the rest. Our toy example showed half of the model's first-step mass going to invalid tokens, and the constraint removing it. The costs are grammar compilation, per-token mask work and a possible distortion of the model's preferences, which a two-step example showed can flip a 92% outcome to 10%. Hosted APIs from OpenAI and Anthropic and engines such as vLLM, XGrammar, Outlines and llama.cpp all offer the feature, with different schema coverage. Design schemas the model finds natural, cache grammars, handle refusals and truncation, and evaluate the values, not only the shape.
Sources
- Official OpenAI: Introducing Structured Outputs in the API
- Web Anthropic: Structured outputs documentation
- Docs vLLM: Structured outputs
- Paper arXiv: XGrammar: Flexible and Efficient Structured Generation Engine for LLMs
- Paper arXiv: Efficient Guided Generation for Large Language Models (Outlines)
- Paper arXiv: JSONSchemaBench: A Rigorous Benchmark of Structured Outputs
- Paper arXiv: Grammar-Aligned Decoding
- Web Tessl: Anthropic brings structured outputs to the Claude Developer Platform
Cite this article
Kelahmet, Ö. C. (2026, November 25). Constrained decoding explained: how structured outputs force LLMs to emit valid JSON. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/constrained-decoding-structured-outputs-json-schema
BibTeX
@online{kelahmet2026constrained,
author = {Kelahmet, {\"O}zer Cem},
title = {{Constrained decoding explained: how structured outputs force LLMs to emit valid JSON}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/constrained-decoding-structured-outputs-json-schema}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.