Search

Search papers and lessons

Structured Output

Level 3 · 11 min read

Structured output forces a language model to write text that always fits a fixed format, such as JSON that matches a schema, by blocking every token that would break the format.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Probability
  • Losses & regularization
  • Pre-training
  • Programming languages
  • ReadReady to readNot yet

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.

  1. 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 rejects Sure.
  2. Start in S0. The model scores all five tokens, and Sure gets 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.
  3. Choose the value in S1. The machine allows true and false. The model's scores for these are 2.0 and 1.0, and } and Sure are blocked. The allowed scores are turned into probabilities (about 0.73 for true, 0.27 for false), and true is sampled from these probabilities. The output is {"ok": true. Check: the probabilities add to one.
  4. 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 field ok set to true.
  5. 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

Definition: Allowed set

Let VV be the vocabulary, let L\mathcal{L} be the language accepted by the format, and let y<ty_{\lt t} be the tokens written before step tt. The allowed set at step tt is the set of tokens vv for which the text y<t vy_{\lt t}\,v can still be extended to a string in L\mathcal{L}. Its complement is blocked.

Step 1 in symbols

The format is a machine with states qq and transitions δ(q,v)\delta(q, v) giving the next state after token vv. A state is live if some continuation from it reaches the accept state. The allowed set is then

At={ v∈V:δ(qt−1,v) is live }A_t = \{\, v \in V : \delta(q_{t-1}, v) \text{ is live} \,\}

where qt−1q_{t-1} is the machine's state after the tokens written so far. Walkthrough step 1 builds δ\delta; in steps 2 to 4 the decoder reads off AtA_t at each state.

Steps 2 to 4 in symbols: mask and renormalise

Let zvz_v be the raw logit for token vv. The masked distribution over the next token is

pt(v)=exp⁡(zv)∑u∈Atexp⁡(zu)for v∈At,pt(v)=0otherwise.p_t(v) = \frac{\exp(z_v)}{\sum_{u \in A_t} \exp(z_u)} \quad \text{for } v \in A_t, \qquad p_t(v) = 0 \quad \text{otherwise.}

This is the same as setting every blocked logit to minus infinity before the Softmax: exp⁡(−∞)=0\exp(-\infty) = 0, so blocked tokens get zero probability and the allowed probabilities are rescaled to add to one. Check with step 3 of the walkthrough: At={true,false}A_t = \{\text{true}, \text{false}\}, ztrue=2.0z_{\text{true}} = 2.0, zfalse=1.0z_{\text{false}} = 1.0, so the denominator is e2+e1≈10.11e^{2} + e^{1} \approx 10.11 and p(true)≈0.73p(\text{true}) \approx 0.73.

Step 5 in symbols

After a token yty_t is sampled, the state updates to qt=δ(qt−1,yt)q_t = \delta(q_{t-1}, y_t). The loop stops when qtq_t is an accept state. Because every sampled token came from AtA_t, every prefix is live, so the machine cannot reach a dead end.

Worked examples

Example
Example 1: the two-token choice (tiny)

State S1 allows true and false. The raw logits are true = 2.0, false = 1.0, } = 0.5, Sure = 3.0.

  1. Block } and Sure, since the state does not allow them. Only two logits remain: 2.0 and 1.0.
  2. Compute the exponentials: e2.0≈7.389e^{2.0} \approx 7.389 and e1.0≈2.718e^{1.0} \approx 2.718.
  3. Add them: 7.389+2.718=10.1077.389 + 2.718 = 10.107.
  4. Divide: p(true)=7.389/10.107≈0.731p(\text{true}) = 7.389 / 10.107 \approx 0.731 and p(false)=2.718/10.107≈0.269p(\text{false}) = 2.718 / 10.107 \approx 0.269.
  5. Check: 0.731+0.269=1.0000.731 + 0.269 = 1.000.

The interpretation: Sure had the highest raw score, 3.0, and it is gone. Without the mask, Sure would be chosen about e3/(e3+7.389+2.718+e0.5)≈0.63e^{3} / (e^{3} + 7.389 + 2.718 + e^{0.5}) \approx 0.63 of the time.

Example
Example 2: a priority label (standard)

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.

  1. Block Sure. The remaining logits are 0.2, 1.1 and 0.4.
  2. Exponentials: e0.2≈1.221e^{0.2} \approx 1.221, e1.1≈3.004e^{1.1} \approx 3.004, e0.4≈1.492e^{0.4} \approx 1.492.
  3. Sum: 1.221+3.004+1.492=5.7171.221 + 3.004 + 1.492 = 5.717.
  4. Probabilities: low ≈0.214\approx 0.214, medium ≈0.525\approx 0.525, high ≈0.261\approx 0.261.
  5. Check: 0.214+0.525+0.261=1.0000.214 + 0.525 + 0.261 = 1.000.
  6. The decoder samples medium in 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.

Example
Example 3: a number in an invoice (realistic)

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.

  1. Block " and N/A, since they start a string, not a number. The remaining logits are 2.2 and 0.4.
  2. Exponentials: e2.2≈9.025e^{2.2} \approx 9.025 and e0.4≈1.492e^{0.4} \approx 1.492.
  3. Sum: 9.025+1.492=10.5179.025 + 1.492 = 10.517.
  4. Probabilities: 4 ≈0.858\approx 0.858, 7 ≈0.142\approx 0.142.
  5. The decoder samples 4. The number continues under the same rule, so the output might be {"total": 4 followed 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: e1.5≈4.482e^{1.5} \approx 4.482, e0.5≈1.649e^{0.5} \approx 1.649, sum 6.1316.131, so p(8)≈0.731p(8) \approx 0.731. 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 e1.0≈2.718e^{1.0} \approx 2.718 and e0.0=1e^{0.0} = 1. The sum is 3.7183.718, so p(A)=2.718/3.718≈0.731p(A) = 2.718 / 3.718 \approx 0.731. 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