Lesson 14.2 · 2 of 8 · 6 min read · Reviewed 24 Nov 2026
Constrained decoding and strict schema modes
By the end, you can
- Explain how constrained decoding forces output to match a schema.
- Know what strict schema modes guarantee, what they restrict and what you must still check.
Lesson 14.1 wrote a schema. Asking the model to follow it in the prompt usually works. Constrained decoding removes the “usually”, and where your provider supports it, it is the first tool to reach for. Lesson 14.6 covers the older tool-forcing pattern you will still meet in existing code.
How it works
A model writes one tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. at a time, choosing from a probability over its whole vocabulary. With constrained decoding, the serving system turns your schema into a grammar and, at every step, masks out any token that would make the output invalid. The model can only pick from what is left.
Worked example. The schema says priority is one of "low", "medium", "high". The output so far is:
{"customer_name": "Priya", "priority": "
| Candidate next token | Allowed? | Why |
|---|---|---|
low |
yes | starts a valid enum value |
med |
yes | starts medium |
high |
yes | valid enum value |
moderate |
no | not in the enum |
} |
no | would leave the string and object unfinished |
Even if the model leans towards “moderate”, that token has zero chance. The result always parses and always fits the schema.
Open-source libraries such as Outlines, llama.cpp grammars and vLLM’s guided decoding do the same thing for models you host. Hosted APIs expose it as a strict or structured outputStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types. mode, for the reply itself or for tool inputs.
Prompted, validated, constrained
| Approach | Shape guaranteed? | Your code still needs |
|---|---|---|
| Schema in the prompt | No | Parse, validate, retry |
| Tool schema, not strict | Very likely, not certain | Validate, retry |
| Strict mode (constrained) | Yes, for supported schemas | Business rules, spot checks |
What strict modes restrict
Building a grammar from any schema is hard, so strict modes usually accept a subset of JSON Schema. Details differ by provider; typical rules are:
additionalPropertiesmust befalseon every object.- Every property is listed in
required. Use a nullable type for optional values (14.3). - Some keywords are unsupported or ignored, such as complex
patterns, numeric ranges or string lengths. - Limits on nesting depth, number of properties or enum size.
- The first request with a new schema can be slower while the grammar is built; later ones reuse it.
Read your provider’s list before you design the schema. A schema that relies on an unsupported keyword either fails at request time or is silently loosened.
What it does not guarantee
- Correct values. The decoder enforces
"type": "number", not that 410.00 is the right total. - A finished reply. If the token limit is hit mid-object, you get a truncated result (14.8).
- An answer at all. A model can still refuse; strict modes typically report that separately rather than as schema-shaped data (14.8).
When to use it
Use strict mode whenever a program, not a person, reads the output and your provider supports it. Keep your validation layer, but move its focus from “does it parse?” to “is it right?”: totals, dates, cross-field rules and sample checks against the source (14.4).
Key points
- Constrained decoding masks out every next token that would break the schema, so the output always parses and fits the shape.
- Strict modes usually accept only a subset of JSON Schema, such as every property required and no extra properties.
- A guaranteed shape is not a guaranteed truth: values can still be wrong, so keep business checks.
Simulate constrained decoding with a mask
See how masking invalid tokens forces an enum field to a legal value even when the model prefers an illegal one.
You will have: A tiny decoder that prints the model's unconstrained choice and the constrained choice for an enum field.
Steps
- Read the toy vocabulary and the model's preference scores for the priority value.
- Complete allowed so a token is allowed only if the text so far plus the token is still a prefix of some enum value.
- Complete decode: at each step pick the highest-scoring allowed token, and stop when the text equals an enum value.
- Compare the free and constrained outputs.
Done when
- Unconstrained decoding prints 'moderate'.
- Constrained decoding prints a value from the enum.
- The script prints 'constrained: medium' and shows which tokens were masked at the first step.
Open in the Playground No API key needed.
Starter code (Python)
ENUM = ["low", "medium", "high"]
VOCAB = ["mod", "erate", "med", "ium", "lo", "w", "hi", "gh", "}"]
# Illustrative model preferences: higher means the model likes it more at this point.
SCORES = {"mod": 0.40, "erate": 0.35, "med": 0.30, "ium": 0.30, "lo": 0.10, "w": 0.05, "hi": 0.08, "gh": 0.04, "}": 0.02}
def free_decode():
# Without constraints the model follows its preferences: "mod" then "erate".
return "mod" + "erate"
def allowed(prefix, token):
# TODO: True if some enum value starts with prefix + token.
return True
def decode():
text = ""
masked_first = None
# TODO: loop up to 5 steps:
# candidates = [t for t in VOCAB if allowed(text, t)]
# on the first step, record the masked tokens (VOCAB minus candidates)
# pick the highest SCORES among candidates, append it, stop when text in ENUM
return text, masked_first
print("unconstrained:", free_decode())
value, masked = decode()
print("constrained:", value)
print("masked at step 1:", masked)
Show a solution
ENUM = ["low", "medium", "high"]
VOCAB = ["mod", "erate", "med", "ium", "lo", "w", "hi", "gh", "}"]
# Illustrative model preferences: higher means the model likes it more at this point.
SCORES = {"mod": 0.40, "erate": 0.35, "med": 0.30, "ium": 0.30, "lo": 0.10, "w": 0.05, "hi": 0.08, "gh": 0.04, "}": 0.02}
def free_decode():
# Without constraints the model follows its preferences: "mod" then "erate".
return "mod" + "erate"
def allowed(prefix, token):
return any(v.startswith(prefix + token) for v in ENUM)
def decode():
text = ""
masked_first = None
for step in range(5):
candidates = [t for t in VOCAB if allowed(text, t)]
if masked_first is None:
masked_first = [t for t in VOCAB if t not in candidates]
text += max(candidates, key=lambda t: SCORES[t])
if text in ENUM:
break
return text, masked_first
print("unconstrained:", free_decode())
value, masked = decode()
print("constrained:", value)
print("masked at step 1:", masked)