Constrained decoding, or grammar-constrained generation, restricts the model vocabulary at each step so every token it emits keeps the output inside an allowed format, such as JSON, a regular expression or a formal grammar. Unlike a prompt that asks for JSON, a grammar makes invalid output impossible at the token level, so no repair step is needed afterwards. It is the right tool when the consumer of the output is code that cannot tolerate a single malformed token, and it is not a substitute for checking that the facts inside the output are true.
What you need
- The exact output format, written as a grammar or a schema
- An inference engine that supports constrained decoding, for example llama.cpp with GBNF
- A test input and a parser for the expected output
Step 1: Write the format as a grammar
Write the allowed format as a formal grammar, for example a GBNF grammar for the JSON shape you need, naming every field, its type and whether it is required. A grammar that is too loose lets bad output through; one that is too strict blocks valid answers.
Step 2: Load the grammar into the engine
Pass the grammar to the inference engine when you start generation, so the sampler only considers tokens that keep the output valid. Confirm the engine reports the grammar loaded, rather than silently ignoring it.
Step 3: Generate and parse without repair
Generate the output and parse it with a strict parser. If it parses on the first try, the constraint works; if it does not, the grammar and the parser disagree, and the grammar needs fixing, not the output.
Worked example: synthetic grammar check for a JSON reply
The table below is a synthetic example. It shows the expected result of constrained decoding; no text was generated.
| Check | Without grammar | With grammar |
|---|---|---|
| Valid JSON | 9 of 10 replies | 10 of 10 replies |
| Required field present | 8 of 10 | 10 of 10 |
| Repair step needed | Yes | No |
| Facts correct | Must still be checked | Must still be checked |
Expected result (UNTESTED). the grammar makes all 10 replies valid JSON with all required fields, and no repair step is needed. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- A grammar constrains the shape of the output, not the truth of the facts inside it; validate facts separately.
- Constrained decoding is an engine feature, not a prompt trick: the API you use must support it.
- A grammar that is too strict can force the model to emit a value rather than admit it does not know.
- Structured outputs in the OpenAI API are a managed form of the same idea, constraining output to a supplied JSON Schema.
