Grammar-constrained decoding and domain validation
medium 6 minA parser can restrict the next tokens to those that keep a partial output compatible with a grammar.
Video lesson · Chapter 1 of 4
A legal word on the wrong receipt
Theory
Read or listen first. About 2 min.
What it is
A parser can restrict the next tokens to those that keep a partial output compatible with a grammar. At each generation step the engine masks ineligible vocabulary entries and samples among what remains. Token boundaries do not always match JSON characters, so a correct implementation tracks possible continuations at the tokenizer boundary. Supported schema features depend on the engine.
Why it exists
Constraints can eliminate malformed syntax without establishing that an amount came from a receipt or that an action is authorized. Use grammar constraints for shape, parse the completed output, then validate domain rules and evidence. An incomplete stream must not be committed merely because its prefix remains valid. Compare throughput and retry costs with post-generation parsing.
Generate a valid status that can still be wrong
Inside this chapter
Chapter sources- Prefix validity
- A partial prefix remains admissible when at least one completion can satisfy the supported grammar. It can be valid to continue generating without being valid to accept the prefix as a complete object.
The engine keeps track of which grammar states are reachable from the current prefix. As long as at least one completion is possible, generation continues. That is very different from the object being finished: a stream that stops at a valid prefix has produced an unfinished object. Commit only after the end of generation and a successful full parse.
Example. After an opening quote, a string prefix may still complete to paid. It cannot yet be accepted as the final status.
Continue versus accept
Output so far Could still complete validly? Acceptable as final? {"status":"yes no {"status":"payes (to paid)no {"status":"pxno, masked out earlier no {"status":"paid"}complete yes, if the parse succeeds Enum of paidandvoid. A valid prefix only earns the right to keep generating. - Allowed token sets
- Map a grammar state to eligible tokens and mask others before normalization. Constrained decoding can change the relative probabilities of the remaining options and incur runtime overhead for complex grammars.
At each step the grammar state determines a mask over the whole vocabulary. Disallowed tokens are removed (in practice their logits are set to negative infinity) and the remaining probabilities are renormalised. Because the model's preference among the survivors is preserved, a model that believed the invoice was paid will still pick paid. Complex grammars make computing the mask more expensive, which shows up as lower throughput.
Example. For an enum containing paid and void, the mask rules out a third label but cannot determine which of the two matches the invoice.
Another example. A ticket router constrains output to five queue names. Malformed labels disappear from the logs, yet the misrouting rate is unchanged, because the model's confusion between billing and refunds was never a formatting problem.
Masking, then renormalising
Illustrative: paid 0.3, void 0.1, others 0.6. After the mask, paid becomes 0.75 and void 0.25. The mask chose the set, not the right member. - Evidence and downstream rules
- Check completed output against source evidence and business constraints before acting. Use bounded recovery on malformed or incomplete results and preserve an explicit uncertain state when neither enum value is supported.
Constrained decoding guarantees the model can only say things the schema allows; it says nothing about which allowed thing is true. Keep a domain check against an independent source and give the schema an escape hatch, such as an
uncertainvalue or a nullable field, so the model is not forced to pick a confident wrong answer. Bound repair attempts on incomplete output.Example. The receipt is void while the model emits valid JSON with status paid. A source or ledger comparison must reject the proposed update.
Parsed is where checking starts
An explicit uncertain path stops the system forcing a choice between two enum values when neither is supported. - Constraint languages
- Engines accept constraints written as JSON Schema, regular expressions or context-free grammars and compile them into a state machine or parser that drives the token mask. Feature support differs: some schema keywords or recursive structures may be unsupported or slow, so check what your engine actually enforces.
Regular expressions compile to finite automata, which are cheap to step through. Nested JSON and recursive grammars need a parser with a stack, which costs more per token. Because token boundaries rarely match grammar symbols (one token might contain a quote, a colon and a space), engines precompute which tokens are compatible with each state. Test unusual schema features explicitly: an unsupported keyword may be silently ignored rather than enforced.
Example. A date field constrained by the pattern
\d{4}-\d{2}-\d{2}can only emit something shaped like 2025-03-14, though the pattern alone would still allow month 13.From a constraint to a mask - 1Write the constraintJSON Schema, regex or grammar
- 2Compileautomaton or parser
- 3Track statewhere in the structure we are
- 4Build masktokens that keep it valid
- 5Sampleadvance the state
Compilation usually happens once per schema and can be cached.
- Constrain or parse and retry
- The alternative to constrained decoding is free generation followed by parsing, with a retry on failure. Constraining removes malformed output but adds per-token work and can shift outputs; parse-and-retry is simple but pays a whole extra call whenever syntax fails. Compare both on your traffic.
Neither approach checks the content, so the evidence and domain checks stay the same either way. The decision is about throughput, latency spread and engine support. Measure the parse failure rate on real inputs first: if it is already near zero, constraints buy little; if it is high on long nested objects, they can save a lot.
Example. If 2% of free-form outputs fail to parse, parse-and-retry adds about 2% extra calls. If the grammar mask slows every token, constraining may cost more overall despite never retrying.
Grammar-constrained decoding
- No malformed syntax reaches the parser
- No whole-call retries for shape errors
- Needs engine support for your schema features
Parse, then retry on failure
- Works with any model endpoint
- Pays a full extra call per syntax failure
- Tail latency grows when failures cluster
How it works
Step through the idea, or press Play.
Grammar state. Track expected status value
Understand it
Worked example
Generate a valid status that can still be wrong
- 1
Track expected status value
The output has reached the enum field. The engine knows which continuations the supported grammar accepts.
- 2
Restrict possible continuations
Exclude tokens that cannot lead to paid or void. Continue until the full object parses.
- 3
Compare paid with a void ledger entry
Syntax succeeds but the business invariant fails. Store the discrepancy for review.
Follow the handoffs
- 1Grammar stateinside the status string
- 2Maskonly paths to paid or void
- 3Sample tokenmodel prefers pa
- 4Advance stateexpect id, then quote
The loop repeats until the object closes, then hands a complete value to the domain validator.
The status field, token by token
| Step | Output so far | Grammar allows next | Model picks |
|---|---|---|---|
| 1 | {"status":" | starts of paid or void | pa |
| 2 | {"status":"pa | id | id |
| 3 | {"status":"paid | closing quote | " |
| 4 | {"status":"paid" | closing brace | } |
| Check | complete object | ledger says void | reject |
Summary
The whole topic in one minute.
A grammar controls possible representations, not the truth of a business assertion.
Constraints can eliminate malformed syntax without establishing that an amount came from a receipt or that an action is authorized. Use grammar constraints for shape, parse the completed output, then validate domain rules and evidence. An incomplete stream must not be committed merely because its prefix remains valid. Compare throughput and retry costs with post-generation parsing.