Constrained Decoding and Its Limits
Watch a toy decoder mask tokens a grammar forbids, learn how OpenAI and Claude expose schema-constrained output, and list precisely what it does not guarantee: truncated replies, refusals, wrong values and unsupported schema features.
Contentsand lesson path
On this page
- Why it matters
- How a grammar steers sampling
- What it guarantees, and what it does not
- Requesting it from each provider
- Check your understanding
- Apply it
- Review prompt
Lessons of Structured Outputs
- Why Free Text Breaks Pipelines Concept · 10 min
- Designing a Schema for an Extraction Task Worked example · 20 min
- Constrained Decoding and Its Limits Concept · 15 min
- Lab: Enforced Schemas Across Two Providers Lab · 25 min
- Validation, Repair and Retry Budgets Worked example · 20 min
- Check: Schema and Failure Scenarios Knowledge check · 6 questions
What you will learn
- Request schema-constrained output from a provider and explain what constrained decoding does and does not guarantee.
Prerequisites: LLM API Integration
01. Why it matters
Schema-constrained output is often described as "guaranteed JSON". That phrase is true in a narrow sense and misleading in a broad one. If you know the mechanism, you know where the guarantee ends, and you write the checks that cover the rest. If you do not, you remove validation because "the API guarantees it", and the first truncated reply or refusal takes the pipeline down. This lesson shows the mechanism on a toy example, maps it to the provider parameters, and lists what it does not promise.
02. How a grammar steers sampling
At each step a model produces a score (a logit) for every token in its vocabulary. Softmax turns the scores into probabilities and the sampler picks a token. Constrained decoding adds one step before sampling: a grammar compiled from your schema says which tokens may come next, and every other token's logit is set to minus infinity. Its probability becomes zero, and the remaining probability is spread over the allowed tokens.
The grammar has to track where in the output it is. For a small, flat schema a finite-state machine is enough. JSON with nested objects and arrays needs memory of which brackets are still open, so engines parse against a context-free grammar, which needs a stack (formally, a pushdown automaton) rather than a fixed set of states; XGrammar and llguidance are two such engines. A further complication is that tokens do not line up with JSON syntax: true may be one token, or tr followed by ue, so the engine must allow any token that keeps the output a valid prefix.
The toy decoder below makes all of this visible for the schema {"active": boolean}. The "model" is a list of made-up scores per step, and decoding is greedy so the output is the same every run. It needs only the Python standard library.
"""A toy constrained decoder for the schema {"active": boolean}. Not a real model."""
import json
import math
# Grammar: in each state, the tokens allowed next and the state each one leads to.
GRAMMAR = {
"start": {"{": "key"},
"key": {'"active"': "colon"},
"colon": {":": "value"},
"value": {"true": "close", "false": "close", "tr": "rest-of-true"},
"rest-of-true": {"ue": "close"},
"close": {"}": "done"},
"done": {"<end>": None},
}
# Made-up scores (logits) of the "model" at each step; higher means more likely.
LOGITS = [
{"Sure": 3.0, "{": 2.5},
{'"is_active"': 2.0, '"active"': 1.5},
{":": 4.0},
{"yes": 2.0, "tr": 1.2, "true": 1.0, "false": -1.0},
{"ue": 3.0, "}": 0.5},
{"}": 3.0},
{"<end>": 3.0},
]
def decode(max_tokens: int) -> str:
state, out = "start", []
for step, logits in enumerate(LOGITS[:max_tokens]):
allowed = GRAMMAR[state]
# Mask: every token the grammar forbids gets -inf, so exp() gives 0.
masked = {t: (s if t in allowed else -math.inf) for t, s in logits.items()}
total = sum(math.exp(s) for s in masked.values())
probs = {t: math.exp(s) / total for t, s in masked.items() if t in allowed}
choice = max(probs, key=probs.get) # greedy, to keep the demo repeatable
wanted = max(logits, key=logits.get)
shown = " ".join(f"{t}={p:.2f}" for t, p in probs.items())
print(f"step {step}: model wants {wanted:12} after mask: {shown}")
if choice != "<end>":
out.append(choice)
state = allowed[choice]
return "".join(out)
for limit in (7, 4):
print(f"--- max_tokens={limit}")
text = decode(limit)
try:
print(f"result: {text} -> parsed {json.loads(text)}")
except json.JSONDecodeError as err:
print(f"result: {text} -> JSONDecodeError: {err.msg}")python3 toy_decoder.py--- max_tokens=7
step 0: model wants Sure after mask: {=1.00
step 1: model wants "is_active" after mask: "active"=1.00
step 2: model wants : after mask: :=1.00
step 3: model wants yes after mask: tr=0.52 true=0.42 false=0.06
step 4: model wants ue after mask: ue=1.00
step 5: model wants } after mask: }=1.00
step 6: model wants <end> after mask: <end>=1.00
result: {"active":true} -> parsed {'active': True}
--- max_tokens=4
step 0: model wants Sure after mask: {=1.00
step 1: model wants "is_active" after mask: "active"=1.00
step 2: model wants : after mask: :=1.00
step 3: model wants yes after mask: tr=0.52 true=0.42 false=0.06
result: {"active":tr -> JSONDecodeError: Expecting valueThree things to notice:
- At step 0 the model prefers
Sure, the start of a chatty preamble. The mask removes it, so{is chosen. At step 1 the drifted key"is_active"is removed the same way. This is why enforced output cannot contain preamble, fences or renamed keys. - At step 3,
yesis masked and the probability is renormalised overtr,trueandfalse. The grammar decides what is allowed; the model still decides which allowed value. Nothing here checks thattrueis the right answer. - With
max_tokens=4the output stops at{"active":tr. Every token was allowed, yet the result is not valid JSON. The grammar only shapes the tokens that are generated; it cannot make generation finish.
03. What it guarantees, and what it does not
For a request the provider accepts, and a response that ends normally, the output follows the schema: right keys, right types, allowed enum values, valid syntax. Everything outside that sentence is your job:
- Truncation. If the token limit is reached, you get a valid prefix that does not parse. OpenAI's Responses API reports
status: "incomplete"withincomplete_details.reason: "max_output_tokens"; Claude reportsstop_reason: "max_tokens". Reasoning or thinking tokens count towards the same limit on both providers. - Refusals. For safety reasons a model may decline. OpenAI returns a
refusalcontent part instead of the JSON; Claude returnsstop_reason: "refusal", and its documentation notes that the output may then not match your schema. - Wrong values. A valid date can be the wrong date, and a valid total can belong to another invoice. Constrained decoding has no idea what the document says.
- Rules the schema cannot state. Totals that must add up, a due date after the invoice date, an invoice present only when the status is
ok: these need validators in code. - Unsupported schema features. Each provider supports a subset of JSON Schema. Unsupported keywords, or a schema too complex to compile, return a 400 error rather than being enforced.
- Small surprises. Claude's documentation warns that enum capitalisation can occasionally differ from the schema, and recommends comparing enums case-insensitively.
Constraints can also affect quality. A schema that forces an answer before the evidence, or squeezes nuanced text into a short enum, gets valid but worse output. Field order and honest exits (lesson 2) are part of the fix.
04. Requesting it from each provider
The request shapes differ, and older examples on the web use names that have since changed:
- OpenAI Responses API:
text: {format: {type: "json_schema", name: "...", schema: {...}, strict: true}}. The Python SDK helper isclient.responses.parse(..., text_format=Model), read viaresponse.output_parsed. - OpenAI Chat Completions:
response_format: {type: "json_schema", json_schema: {name, schema, strict: true}}. The helper isclient.chat.completions.parse(...), no longer underbeta; it raisesLengthFinishReasonErroron a length stop, and a refusal appears inmessage.refusal. - Claude structured outputs:
output_config: {format: {type: "json_schema", schema: {...}}}. The helper isclient.messages.parse(..., output_format=Model), read viaparsed_output. Keywords outside Claude's subset, such asminimum, return a 400 when sent raw; the helper instead moves them into the field's description and checks them when it validates the reply. The olderoutput_formatrequest parameter is deprecated. - Claude strict tool use:
strict: trueon a tool definition, when the structure is the input to a tool. Forcing the tool withtool_choicedoes not by itself constrain the arguments, and Claude Fable 5.2, Opus 5.5 and Sonnet 5.5 (and Fable 5.1) reject forcedtool_choicewith a 400. - Self-hosted (vLLM): the OpenAI-compatible
response_formatwith a JSON Schema, or vLLM'sstructured_outputsoptions, backed by XGrammar or guidance.
Read model names from configuration, for example ANTHROPIC_MODEL=claude-sonnet-5-5, and check each provider's models page; snapshots are retired on a schedule. Do not set temperature for Claude: from API version 2026-10-21, which the anthropic 2.x SDKs send, Claude no longer accepts temperature, top_p or top_k at all, even at their default values.
05. Check your understanding
06. Apply it
For the skill project, write a one-page note for your team:
- the exact request parameter you will use for your provider, and the SDK version you tested with;
- the stop reasons or statuses your code will check before parsing, and what it does with each;
- every rule your schema cannot express, with the validator that checks it.
07. Review prompt
Without notes: explain how a mask changes the probabilities at one decoding step, and why a valid prefix can still fail to parse. List the six gaps in the guarantee, and give the request parameter for schema-constrained output on OpenAI's Responses API and on Claude.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.