Constrained generation: use grammars to limit valid outputs
Constrained generation limits which tokens a model may emit next, using format rules or other acceptance conditions to keep the result inside a defined output space. It is useful for machine-checkable requirements such as JSON structure, SQL grammar, or a fixed set of labels. But a string that passes a grammar is not necessarily meaningful or executable against a database. Constraints can enforce form; facts and business rules still need separate validation.
Constrained generation: use grammars to limit valid outputs
Constrained generation limits which tokens a model may emit next, using format rules or other acceptance conditions to keep the result inside a defined output space. It is useful for machine-checkable requirements such as JSON structure, SQL grammar, or a fixed set of labels. But a string that passes a grammar is not necessarily meaningful or executable against a database. Constraints can enforce form; facts and business rules still need separate validation.
What happens during generation?
In ordinary language-model decoding, each step scores possible next tokens and selects one to extend the output. With grammar-based constrained decoding, a parser or state machine checks the prefix generated so far and excludes candidate tokens that cannot continue according to the rules. The model chooses among the remaining candidates; the system updates its state with that token and repeats. Scholak et al. studied PICARD, which uses incremental parsing to reject inadmissible tokens while generating SQL.
This differs from post-hoc validation, which checks a completed output and then rejects or regenerates it if invalid. Constrained decoding narrows the choices during generation. It also differs from a natural-language prompt instruction such as “output only JSON”: that is a request, whereas a decoding constraint is a filter enforced by the generation system. Implementations vary by API and decoder, so do not assume every structured-output feature exposes or uses the same grammar mechanism.
What kinds of constraints can you express?
The simplest case is a finite set of labels or enum values. Regular expressions can describe limited patterns such as a URL or code shape, while JSON Schema describes fields and value types in an object. More complex nested structures can use formal grammars such as context-free grammars (CFGs). A grammar defines which strings are permitted; an input-dependent grammar can narrow valid values based on the current input. Geng et al. explored input-dependent grammars for information extraction, entity disambiguation, and parsing.
For example, suppose a customer message must receive exactly one of three labels:
allowed_label := "refund" | "shipping" | "other"This rule can prevent other strings from appearing, but it cannot determine which label reflects the customer’s actual intent. Forcing a choice when a message is ambiguous may create false certainty. If needed, include unknown or needs_review in the allowed values, then define evidence and human-review conditions as separate output fields and business rules. For designing JSON objects and field constraints, see the JSON Schema outputs guide.
How should you design and check a constraint?
**Specify what must be guaranteed.** Distinguish syntax such as brackets and commas from field names, types, allowed values, and real-world or business validity.
**Choose the simplest constraint.** Use an allow-list for fixed labels, a regular expression for a simple string pattern, and an API-supported schema or grammar for nested structures.
**Check that the constraint is satisfiable.** Contradictory rules or values incompatible with the input can leave no possible complete output. Check that the grammar is nonempty and has at least one valid result for each relevant input.
**Check tokenizer and decoder compatibility.** Models generate subword tokens, not grammar characters. Tokens may span grammar boundaries, so parsing and alignment must avoid rejecting tokens that can lead to a valid completion. Park et al. analyze why aligning grammar tokens with a model tokenizer matters for sound constrained decoding.
**Keep validation after generation.** Parse the structure and check application-specific rules. For SQL, verify not only grammar but also that tables and columns exist in the actual schema and that permissions are appropriate; execute only in a least-privilege environment.
**Evaluate failures and boundary cases.** Include ambiguous input, empty results, inputs for which every label is unsuitable, and cases that require refusal. Compare with an unconstrained baseline on format validity, semantic accuracy, naturalness, latency, and refusal behavior.
What trade-offs and costs should you consider?
Constrained generation can block invalid tokens early and reduce format errors, but a poorly designed constraint can make a correct answer impossible. Grammar-valid output can still contain a semantic error, false fact, nonexistent database field, or unsafe command. The application must check business conditions outside the grammar.
Parsing and state management add compute and latency, and implementation complexity depends on the grammar/tokenizer combination. Tight constraints can also push a model toward awkward wording because it must place allowed phrases rather than choose a natural expression for context. Use constraints when format is part of the actual contract, keep the allowed set as clear and small as practical, and evaluate expression quality alongside business accuracy.
Sources
[Scholak et al., “PICARD: Parsing Incrementally for Constrained Auto-Regressive Decoding from Language Models” (EMNLP 2021)](https://aclanthology.org/2021.emnlp-main.779/) — incremental parsing and rejection of inadmissible tokens for SQL generation.
[Geng et al., “Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning” (EMNLP 2023)](https://aclanthology.org/2023.emnlp-main.674/) — input-dependent grammars for information extraction, entity disambiguation, and parsing.
[Park et al., “Flexible and Efficient Grammar-Constrained Decoding” (ICML 2025)](https://proceedings.mlr.press/v267/park25l.html) — effects of aligning context-free grammars with subword tokenizers.