TL;DR
A language model writes one token at a time, and nothing in its training forces the result to be well formed. Structured output fixes that: before each token is chosen, a rule set computes which tokens would still allow the text to fit the required format, and every other token is removed from the choice. The result is text a program can parse on the first try, every time.
Builds on: Language Model, Context-Free Grammar, Softmax · Leads to: Tool Use
Where it's used
Tool calling. An assistant that books flights calls a function called book_flight with arguments such as a departure
airport, a date and a passenger count. The application runs the call only if the arguments parse and have the right types.
If the model writes a sentence like "Sure, I will book it" instead of the arguments, the call fails. Structured output makes
the model's reply always be the argument object.
Document extraction. A finance team wants the vendor name, invoice total and due date from every scanned invoice, stored as rows in a database. A single stray word before the answer, or a total written as "about 340 dollars", breaks the import. Constraining the total to be a number and the date to be a date string lets the import run unattended.
Routing and labelling. A support system sends each ticket to a queue. The model must answer with exactly one of low,
medium or high. A constrained decoder makes any other answer impossible, so the router never has to handle an unknown
label.
How it works
Take a tiny format: the output must be exactly one of the two strings {"ok": true} or {"ok": false}. The vocabulary has
five tokens: {"ok": (a prefix with the field name), true, false, }, and Sure. The model is an
ordinary Language Model that outputs one raw score, called a logit, for each token.
- Compile the format. The developer gives a schema or a grammar. A library turns it into a
small state machine with states
S0 (nothing written yet), S1 (the prefix is written), S2 (a value is written) and S3 (accept). Check: the machine accepts
{"ok": true}and rejectsSure. - Start in S0. The model scores all five tokens, and
Suregets the highest score (2.5), because a chat model likes to start with a preamble. The machine allows only{"ok":. Every other token is blocked, so the only choice left is that token. The output is{"ok":. Check: the output is still a prefix of a valid answer. - Choose the value in S1. The machine allows
trueandfalse. The model's scores for these are 2.0 and 1.0, and}andSureare blocked. The allowed scores are turned into probabilities (about 0.73 fortrue, 0.27 forfalse), andtrueis sampled from these probabilities. The output is{"ok": true. Check: the probabilities add to one. - Close the object in S2. Only
}is allowed. The output is{"ok": true}, and the machine moves to S3. Check: this string parses as JSON with a boolean fieldokset to true. - Stop in S3. The machine accepts, so the decoder allows the end-of-sequence token and stops. Nothing more is generated.
flowchart TD
A["Model gives a score for every token"] --> B["Format machine lists the allowed tokens"]
B --> C["Block every other token"]
C --> D["Turn the remaining scores into probabilities"]
D --> E["Sample one token"]
E --> F["Move the machine to its next state"]
F --> G{"Machine accepts?"}
G -- "no" --> A
G -- "yes" --> H["Stop and return the text"]
The math
Let be the vocabulary, let be the language accepted by the format, and let be the tokens written before step . The allowed set at step is the set of tokens for which the text can still be extended to a string in . Its complement is blocked.
Step 1 in symbols
The format is a machine with states and transitions giving the next state after token . A state is live if some continuation from it reaches the accept state. The allowed set is then
where is the machine's state after the tokens written so far. Walkthrough step 1 builds ; in steps 2 to 4 the decoder reads off at each state.
Steps 2 to 4 in symbols: mask and renormalise
Let be the raw logit for token . The masked distribution over the next token is
This is the same as setting every blocked logit to minus infinity before the Softmax: , so blocked tokens get zero probability and the allowed probabilities are rescaled to add to one. Check with step 3 of the walkthrough: , , , so the denominator is and .
Step 5 in symbols
After a token is sampled, the state updates to . The loop stops when is an accept state. Because every sampled token came from , every prefix is live, so the machine cannot reach a dead end.
Worked examples
State S1 allows true and false. The raw logits are true = 2.0, false = 1.0, } = 0.5, Sure = 3.0.
- Block
}andSure, since the state does not allow them. Only two logits remain: 2.0 and 1.0. - Compute the exponentials: and .
- Add them: .
- Divide: and .
- Check: .
The interpretation: Sure had the highest raw score, 3.0, and it is gone. Without the mask, Sure would be chosen about
of the time.
A ticket router must answer low, medium or high. The raw logits at the first token are low = 0.2, medium = 1.1,
high = 0.4, and Sure = 2.5. The allowed set is the three labels.
- Block
Sure. The remaining logits are 0.2, 1.1 and 0.4. - Exponentials: , , .
- Sum: .
- Probabilities:
low,medium,high. - Check: .
- The decoder samples
mediumin about half the runs, and the other labels in the rest. Every run returns a valid label.
The interpretation: the constraint did not decide the label. It only removed the invalid answer and let the model's own judgement pick among the valid ones.
An extractor must fill the field total with a number. The output so far is {"total": and the schema requires a number,
so the machine allows only tokens that start a number. The raw logits are " = 2.8 (a string start), N/A = 1.9 (a text
answer), 4 = 2.2, and 7 = 0.4.
- Block
"andN/A, since they start a string, not a number. The remaining logits are 2.2 and 0.4. - Exponentials: and .
- Sum: .
- Probabilities:
4,7. - The decoder samples
4. The number continues under the same rule, so the output might be{"total": 4followed by a decimal point and more digits.
The interpretation: the schema guarantees a number, but it cannot guarantee the right number. If the invoice says 470, the model may still write 4 and then 70. The format is correct and the value is wrong, which is why extraction pipelines still check values against the document.
Try it: a different field, quantity, allows only the tokens 3 (logit 0.5) and 8 (logit 1.5), and every other
token is blocked. What is the probability that 8 is sampled? Work it out: exponentiate both logits, add them, and divide.
Answer: , , sum , so . 8 is sampled about
73 times in 100.
Common mistakes and tradeoffs
It is tempting to think that a valid format means a correct answer. In fact the mask guarantees only the shape of the output. The number in Example 3 can be wrong and still be valid, because the mask checks grammar, not facts.
It is tempting to think that asking "reply only in JSON" in the prompt does the same job, because a model trained to follow instructions usually obeys it. In fact a prompt raises the probability of good output but does not guarantee it, because a sample can still drift into a preamble or a broken brace. A mask applied at every token is a guarantee for the format, as long as the decoder is correct.
It is tempting to think that the mask works on characters. In fact it works on tokens, and one token can cover several
grammar symbols, such as ": at the end of a field name. A decoder must check whether each whole token can be consumed by
the machine, and this is the main source of implementation bugs.
Constrained decoding costs time: the allowed set must be computed at each step, and deep nesting or large enumerations make this slower. It also changes what the model writes. Forcing a rare path can push the model into text it would not have written, which can lower the quality of the content inside the fields. Use it when a program reads the output and a parse error would break a pipeline. Do not use it for open-ended writing, where a free answer is the point. Alternatives include validating the output and retrying on failure, which costs extra calls, and fine-tuning the model on examples of the format.
History
Before 2020, most language-model applications produced free text, and programs that needed structure parsed it with regular expressions and hope. In 2021 a team led by Torsten Scholak published PICARD, which rejected partial outputs that could not lead to a valid SQL query during generation. This showed that a parser could steer decoding, not only check it afterwards.
In 2023 Brandon Willard and Rémi Louf described Outlines, a method that compiles regular expressions and JSON schemas into token masks ahead of time, so the mask is cheap to apply at each step. Around the same time model providers added JSON modes and later schema-enforced outputs, which made the technique a standard feature in production systems. It caught on because the failure it removes, a broken parse, is the most common reason a model's output cannot be used in a program.
Recap
- A language model scores every token at each step, and structured output blocks the tokens that would break the format.
- A format compiles into a state machine; the machine lists the allowed tokens in its current state.
- Blocking is applied before the softmax, so the allowed probabilities are renormalised to add to one.
- The format is guaranteed and the content is not, so values still need checking.
Read next: Tool Use, which builds on this to let a model call functions with typed arguments.
Check yourself
QuestionWhy is the mask applied before the softmax rather than after sampling?Show answer
If the decoder sampled first and then rejected blocked tokens, it would have to sample again, possibly many times, and a model that puts most of its probability on blocked tokens could take a long time to produce an allowed one. Masking first samples only from the allowed set, and the renormalised probabilities are exactly the model's relative preferences among the valid choices.
QuestionTwo tokens are allowed. Their logits are A = 1.0 and B = 0.0. What is the probability of A after masking?Show answer
Compute and . The sum is , so . Answer: about 0.731.
QuestionA weather tool has a parameter unit that must be celsius or fahrenheit. The model wants to write 'in Celsius, please'. What does a constrained decoder do?Show answer
At the start of the value, the machine allows only the first tokens of celsius and fahrenheit. The phrase "in Celsius"
starts with a token that is not allowed, so it is blocked. The decoder chooses among the allowed tokens instead, and the
output is one of the two enum values.
QuestionA schema-valid output contains a price of 0 for an item that costs 40. What went wrong, and what does this tell you about the method?Show answer
Nothing in the format went wrong: 0 is a valid number. The mask checks structure, not the value. The method guarantees that the output parses and matches the types; it does not check that the content matches the source document, so a separate check against the source is still needed.
Sources
- Willard and Louf, "Efficient Guided Generation for Large Language Models" (2023): https://arxiv.org/abs/2307.09702
- Scholak et al., "PICARD: Parsing Incrementally for Constrained Auto-Regressive Decoding from Language Models" (2021): https://arxiv.org/abs/2109.05093
- JSON, Wikipedia: https://en.wikipedia.org/wiki/JSON