Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 15 min · revision 3

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

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.

Python · toy_decoder.py
"""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}")
Terminal
python3 toy_decoder.py
Expected output
--- 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 value

Three 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, yes is masked and the probability is renormalised over tr, true and false. The grammar decides what is allowed; the model still decides which allowed value. Nothing here checks that true is the right answer.
  • With max_tokens=4 the 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:

  1. Truncation. If the token limit is reached, you get a valid prefix that does not parse. OpenAI's Responses API reports status: "incomplete" with incomplete_details.reason: "max_output_tokens"; Claude reports stop_reason: "max_tokens". Reasoning or thinking tokens count towards the same limit on both providers.
  2. Refusals. For safety reasons a model may decline. OpenAI returns a refusal content part instead of the JSON; Claude returns stop_reason: "refusal", and its documentation notes that the output may then not match your schema.
  3. 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.
  4. 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.
  5. 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.
  6. 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 is client.responses.parse(..., text_format=Model), read via response.output_parsed.
  • OpenAI Chat Completions: response_format: {type: "json_schema", json_schema: {name, schema, strict: true}}. The helper is client.chat.completions.parse(...), no longer under beta; it raises LengthFinishReasonError on a length stop, and a refusal appears in message.refusal.
  • Claude structured outputs: output_config: {format: {type: "json_schema", schema: {...}}}. The helper is client.messages.parse(..., output_format=Model), read via parsed_output. Keywords outside Claude's subset, such as minimum, 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 older output_format request parameter is deprecated.
  • Claude strict tool use: strict: true on a tool definition, when the structure is the input to a tool. Forcing the tool with tool_choice does not by itself constrain the arguments, and Claude Fable 5.2, Opus 5.5 and Sonnet 5.5 (and Fable 5.1) reject forced tool_choice with a 400.
  • Self-hosted (vLLM): the OpenAI-compatible response_format with a JSON Schema, or vLLM's structured_outputs options, 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

Practice check · 3 questions

Masks, grammars and provider limits

Use the toy decoder and the provider notes from this lesson.

Q1. At step 3 of the toy decoder the model's favourite token is `yes`. What happens to it?
Q2. Why do engines that support nested objects and arrays use a grammar with a stack rather than a plain finite-state machine?
Q3. A Pydantic model has `quantity: int = Field(ge=1)`, and you pass it to `client.messages.parse(output_format=Line)` in the Python SDK. What happens to the bound?
Practice only: not graded, not saved, not evidence.

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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check