Constrained Decoding: How Structured Outputs Work
Prompting an LLM for JSON fails eventually. Constrained decoding masks the model tokens against a grammar so the output parses every single time.
There are two ways to make a language model return JSON. The first is to ask nicely in the prompt, call json.loads(), and add retries for when it comes back wrapped in a code fence or prefixed with “Sure, here you go.” I wrote about that approach in getting reliable JSON out of an LLM, and for a lot of systems it is enough.
The second way does not rely on the model cooperating. It reaches into the decoding loop and removes every token that would break the format before the model can pick it. The output is not probably valid JSON that you re-ask for when it isn’t. It parses on the first try, every time, because the server never let an invalid token through.
That second approach is constrained decoding, also sold as “structured outputs” or “guided decoding.” This post is for engineers who treat an LLM as a component whose output their code has to parse: a classifier returning a label, an extractor pulling fields out of a document, a router choosing which tool to call. It is also for anyone running their own inference on vLLM or similar, where constrained decoding is a flag you turn on and a few tradeoffs you should understand first. I will cover how the mechanism actually works, why it costs almost nothing per token, how to use it across providers, and the ways it still bites.
The one idea: mask the tokens, then sample
A language model does not emit JSON, or text, or anything else directly. On each step it produces a vector of scores, one per token in its vocabulary, called logits. Normally the server turns those into probabilities and samples one token from the distribution. Constrained decoding adds a single step in between: before sampling, it looks at what the format allows next and sets the logit of every disallowed token to negative infinity. Those tokens now have zero probability, so sampling cannot choose them. The model picks the best allowed token instead.
That picture is the whole thing. Say the output so far is {"temperature": and your schema says temperature is a number. The model, left to itself, might most want to write the word warm, because in its training data “the temperature is warm” is a perfectly natural sentence. Constrained decoding does not argue with that preference. It just deletes warm, "hot", null, and Sure, from the list of things the model is allowed to say at this position, because none of them is the start of a JSON number. What is left are the numeric tokens, and the highest-scoring one wins.
The guarantee this buys you is specific and worth stating precisely: the output is guaranteed to be structurally valid. It will parse. It will match the schema’s shape. It does not guarantee the value is correct, and that distinction is where most of the real failure modes live. More on that below.
What “the format” actually is
“Set the logit of every disallowed token to negative infinity” assumes you know which tokens are disallowed. Working that out means expressing the format as something a machine can step through character by character. Three levels of expressiveness cover almost everything people use:
- A fixed set of choices. The output must be exactly one of
"approve","reject","escalate". This is the cheapest and most underused option. - A regular expression. The output must match a pattern: a date like
\d{4}-\d{2}-\d{2}, a run ID, a phone number. Regular expressions map cleanly onto a finite-state machine, which is exactly what you need to track “what can come next.” - A context-free grammar. The output must follow a recursive structure that a regex cannot describe. JSON is the headline example. You cannot match balanced, arbitrarily nested braces and brackets with a regular expression; that requires a grammar with a stack. SQL, arithmetic expressions, and most domain-specific languages are the same.
JSON Schema sits on top of these. A JSON Schema describing your object compiles down to a grammar that encodes the field names, the types, which fields are required, and any enums. Most libraries accept a schema or a Pydantic model and do that compilation for you.
Why it is nearly free per token
The naive version of this is slow. At every single decode step you would walk the entire vocabulary, which is 128,000 tokens or more on modern models, and test each candidate against the grammar to see if it keeps the output valid. Do that for every token of every request and the mask computation can cost more than the forward pass that produced the logits in the first place. The worst case for grammar checking is genuinely bad.
The trick that makes constrained decoding practical is that most of this work can be done once, before the first token, and then reused.
Outlines, the library that made this approach popular, compiles a regex or schema into a finite-state machine and precomputes, for each state, the set of tokens that keep the output on a valid path. Its authors describe the result as adding “little to no overhead to the token generation process” in the paper Efficient Guided Generation for Large Language Models (Willard and Louf, 2023). At runtime the engine knows its current state, so producing the mask is a lookup rather than a scan.
XGrammar pushes this further for full context-free grammars. It uses a pushdown automaton so it can handle nesting, and it splits the vocabulary into tokens whose validity is context-independent (decidable from the current position alone, so the mask is precomputed and cached) and a much smaller set that is context-dependent and must be checked against the full parse stack at runtime. The XGrammar paper (Dong et al., 2024) reports up to a 100x reduction in per-token mask overhead versus earlier methods, and near-zero overhead once the mask computation is overlapped with the GPU’s own work. That overlap matters: while the GPU runs the forward pass for the next token, the CPU can be preparing the mask, so the constraint costs no extra wall-clock time.
This is why, in a modern serving engine, turning on structured outputs is close to free for most schemas. The cost moved to compile time, and compile time is cached.
Using it: the same idea, three APIs
The mechanism is identical whether you call a hosted API or run your own server. What changes is how you pass the schema.
Through a provider’s API. OpenAI’s structured outputs use response_format with a JSON Schema, and the constraint is enforced on their servers the same way:
from openai import OpenAI
from pydantic import BaseModel
class Reading(BaseModel):
temperature: float
unit: str
client = OpenAI()
resp = client.chat.completions.parse(
model="gpt-4o",
messages=[{"role": "user", "content": "It's 72F in the lab."}],
response_format=Reading,
)
print(resp.choices[0].message.parsed) # Reading(temperature=72.0, unit='F')On your own vLLM server, the OpenAI-compatible way. Point the same client at your endpoint and pass a JSON Schema in response_format. vLLM enforces it with whichever backend it picks.
On your own vLLM server, the explicit way. vLLM exposes guided decoding directly. In older releases these are extra_body parameters; the offline API wraps them in GuidedDecodingParams inside SamplingParams, and newer releases are moving the naming toward structured_outputs, so check the version you run:
# Force exactly one label - the cheapest, most reliable constraint.
completion = client.completions.create(
model="my-model",
prompt="Classify the sentiment: 'shipping was late but the product is great'\n",
extra_body={"guided_choice": ["positive", "negative", "mixed"]},
)
# Force a regex shape (an ISO date).
extra_body={"guided_regex": r"\d{4}-\d{2}-\d{2}"}
# Force a full JSON Schema.
extra_body={"guided_json": Reading.model_json_schema()}As of recent releases, vLLM defaults its guided-decoding backend to auto, which usually selects XGrammar and falls back to Outlines for features XGrammar does not support. Red Hat’s write-up, Structured outputs in vLLM, notes that this selection changes over time as optimizations land, and that per-request backend selection is not available in vLLM’s V1 engine, so you choose the backend when you start the server, not per call.
If you are building the schema from code, derive it from your Pydantic model with model_json_schema() rather than hand-writing JSON Schema. Your validation layer and your decoding constraint then come from the same source of truth, which is the point I keep coming back to in reliable JSON out of an LLM: describe the shape once, and use that description everywhere.
The subtle part: tokens do not line up with the grammar
Here is the detail that makes this harder to implement than it sounds, and worth knowing even if you never write a decoding backend.
The grammar is defined over characters. The model produces tokens, and a token is usually several characters, chosen by byte-pair encoding for compression, not to respect any grammar’s boundaries. A single token like {" or ": or , " can straddle a structural boundary in your JSON. So the automaton cannot simply ask “what character comes next”; it has to ask, for each candidate token, “if I appended this whole token, would the output still be on a valid path, and which state would I land in?”
That mapping from the model’s token vocabulary onto grammar transitions is the real work, and it is specific to each tokenizer. It is also why you cannot reuse a compiled grammar across models with different tokenizers, and why the first request with a new, large schema can pay a noticeable compilation cost while that mapping is built. Libraries cache the compiled artifact keyed on the grammar and the tokenizer, so you pay it once.
Where structure ends and correctness begins
Constrained decoding guarantees the shape. It guarantees nothing about whether the content is right, and most of the trouble people hit comes from expecting more than the shape.
Valid is not correct. A schema that requires {"temperature": number, "unit": string} will happily accept {"temperature": 9999, "unit": "banana"}. The parser is satisfied; the data is nonsense. Constrained decoding removes an entire class of parsing bugs, which is real and valuable, but it does not do your validation for you. Keep validating semantics, ranges, and cross-field invariants after parsing.
Forcing a format can lower answer quality. This one surprises people. If you force a model to emit JSON and do its reasoning at the same time, you can get worse answers than if you let it think in prose first. The paper Let Me Speak Freely? (Tam et al., EMNLP 2024) found measurable drops on reasoning-heavy tasks under strict format restrictions. The fix is simple enough once you see the cause: give the model room to reason, then constrain only the final answer. In practice that means a schema with a free-text reasoning field before the answer field, or a two-step flow where the model answers in natural language and a second, constrained call extracts the fields. I use the reasoning-field pattern in the structured verdicts for LLM-as-a-judge scoring, where the explanation genuinely improves the score that follows it.
Unbounded strings still run on. The grammar for a string field constrains the quotes and escaping, not the length. A model that wants to ramble inside a string field can still produce 2,000 tokens of it. Set maxLength in the schema where it makes sense, and always keep a max_tokens cap as a backstop, because a constraint that forbids the stop token until some structure closes can, with a stubborn model, generate for a long time.
Not every schema feature is supported. Backends differ on regex lookahead, recursive $ref, and some JSON Schema keywords. vLLM’s auto mode exists partly to route around these gaps, but a schema that leans on exotic features can fail to compile or silently get a looser constraint than you think. Test the actual constraint, not just that the call succeeds.
Key order gets frozen. JSON Schema with required fields typically forces the keys to appear in a fixed order. That is usually fine, but it is another way the constrained distribution differs from what the model would produce unprompted, and it interacts with the reasoning-before-answer ordering above. Put the fields you want the model to “think through” first, in the order you want it to think.
What I would do differently depending on the job
The three levels of constraint are not interchangeable, and reaching straight for a full JSON Schema is a common overreach.
If the decision is “which of these buckets,” use guided_choice with an explicit list. It is the strongest constraint, the cheapest to compile, and it makes an invalid answer impossible rather than improbable. This is what I reach for first in routing and tool-selection code, including the tool picker behind an MCP server, where the valid set of tools is known and small.
If the output is a single scalar with a shape, a regex is lighter than a one-field object and says exactly what you mean.
Save full JSON Schema for genuinely structured records, and when you use it, design the schema for the model’s sake as much as the parser’s: a reasoning field up front, sensible maxLength bounds, enums instead of free strings wherever the set is closed. The schema is a prompt as much as a constraint.
And if you are streaming the structured output to a UI so it fills in as it generates, the constraint guarantees the final buffer is valid but every intermediate buffer is still a truncated prefix. Parsing those prefixes is a separate problem I covered in parsing partial JSON while an LLM streams.
Where this fits in my work
Most of the structured pieces of Archi, the RAG copilot I worked on for CMS operations at CERN, lean on this. Pulling fields out of JIRA tickets and logbook entries, deciding which retrieval tool to call, tagging a document with a fixed set of categories: all of it reads better and breaks less when the model is constrained to the shape the downstream code expects, instead of being asked politely and re-asked on failure.
The reason I find it worth understanding at the token level, rather than as a black-box flag, is that it sits right on the serving path I care about as an inference engineer. Once you see that a structured output is just a logit mask applied before sampling, the questions that matter become clear: which backend is my server using, what does it fall back to, what does a cold schema cost to compile, and am I accidentally hurting answer quality by forcing the format too early. Those are answerable. “Why did the model return broken JSON again” is not, and constrained decoding is how you stop asking it.
Diagrams by M. Hassan Ahmed, released under CC0. No external image was used for this post; the figures are original work by the author.