Structured JSON Outputs & Constrained Grammar Decoding (FSM Masking)
How production APIs guarantee 100% valid JSON Schema outputs with zero syntax crashes: compiling JSON Schema into a Finite State Machine (FSM), O(1) vocabulary bitmasking before softmax, and defensive fenced-JSON extraction.
Constrained Decoding uses a Finite-State Machine (FSM) or grammar mask to set invalid vocabulary logits to −∞ at every decoding step, guaranteeing 100% schema-valid JSON.
Asking an LLM nicely to 'return valid JSON only' still fails 2%–5% of the time in production, crashing downstream parsers and APIs.
Modern software talks in typed JSON, not chat prose — Constrained Decoding is the bridge that turns stochastic LLMs into 100% schema-reliable API components!
Understanding FSM bitmasking (Outlines, XGrammar, llguidance, OpenAI/Gemini Structured Outputs) explains both why first-time schema compilation adds a small warmup latency and why reasoning fields should come BEFORE final_answer keys in JSON!
Knowing how constrained schemas affect model reasoning quality — and when to fall back to fenced ```json extraction — keeps data-extraction pipelines crash-free.
Hot production AI systems question: 'How does OpenAI / vLLM Structured Outputs guarantee 100% JSON Schema compliance at every token without retrying failed generations?'
How does FSM Constrained Decoding prevent the LLM from emitting 'Sure! Here is your JSON:' at the very first token?
- Explain how Constrained Decoding compiles a JSON Schema or CFG into a Finite State Machine (FSM) over the tokenizer vocabulary
- Trace how pre-computed per-state vocabulary bitmasks set every invalid token's logit to −∞ before softmax in O(1) lookup time
- Distinguish Prompt-Only JSON (~88% reliable) vs. JSON Mode (valid JSON syntax) vs. Strict Structured Outputs (exact keys, types & enums)
- Implement a defensive fenced-JSON codeblock extractor for unconstrained models and reasoning traces
Imagine a train (the LLM) that wants to wander off the tracks to say 'Sure! Here is the JSON:'. Constrained Decoding puts steel guardrails (an FSM Bitmask) around the tracks at every single step: when the schema expects an integer after "age": , the bitmask instantly blocks every letter, quote, and emoji to , leaving only digits 0-9 open — so the LLM's intelligence picks the right number while the FSM guarantees the exact syntax!
1. How FSM Constrained Decoding Masks Logits Before Softmax
Trace the 3-stage pipeline below: the FSM tracks the exact grammar state, looks up the allowed vocabulary bitmask in , and masks invalid tokens to before sampling.
Inside Outlines / XGrammar / OpenAI Structured Outputs
- Compile Schema Once (Cached): Convert your Pydantic / JSON Schema into a Regex/CFG and index which of the 128,000 BPE tokens are legal from each grammar state .
- Apply Bitmask at Each Decode Step:
- Sample & Advance FSM: Sample from and transition on the emitted token!
- Bonus Speedup (Fast-Forward / Jump-Forward Decoding): Whenever the JSON schema forces a fixed literal like
{"status": ", there is only 1 legal token — engines like SGLang/Outlines inject it directly without even running the 70B GPU forward pass!
p_i = softmax(z_i + log M(s)_i)
log(1) = 0 → raw logit z_i passes through untouched!
"reasoning": string field BEFORE "verdict": enum in your JSON Schema so the model thinks BEFORE committing to the enum!2. Prompt-Only vs. JSON Mode vs. Strict JSON Schema
Not all JSON options are equal — understand the three reliability tiers before shipping to production.
The 3 Reliability Tiers
- Tier 1 — Prompt-Only (
"Reply ONLY in JSON"): Fails ~5–15% of the time by wrapping output in ```json fences, adding apologies, or dropping commas. - Tier 2 — JSON Mode (
response_format: json_object): Guarantees valid JSON syntax (JSON.parsenever crashes), but does NOT guarantee your exact keys, nesting, or enum values! - Tier 3 — Strict JSON Schema (
strict: true/ FSM): Guarantees 100% compliance with required keys, types, enums, and nested arrays.
3. Defensive Fenced-JSON Codeblock Extraction
Toggle between Markdown Fenced and Unfenced Prose in the mini-lab below to see how a defensive extractor recovers clean JSON when using unconstrained or open-weights models!
json ... `` wrappers and extracts the strict JSON payload.3-Step Defensive Extraction Pattern
- Match fenced block first: Search for
json\s*([\s\S]*?)\s*(or generic ``` fences) and strip the delimiters. - Fallback brace scan: If no fences exist, locate the outermost
{ ... }or[ ... ]slice. - Validate with Pydantic / Zod: Never trust raw
json.loads()alone — always validate field types and ranges!
Worked Example: Why JSON Key Ordering Changes Accuracy
Classifying support tickets into "billing" | "bug" | "other" with a strict JSON Schema.
The LLM must pick category on token #3 with zero prior reasoning — forcing a snap guess!
explanation merely rationalizes whatever guess it already locked in!JSON Codeblock Extractor Simulator
Sure! Here is the result:
```json
{"ticker": "NVDA", "signal": "BUY"}
```
Hope that helps!How does FSM Constrained Decoding guarantee 100% valid JSON without retrying failed generations?
Wait — if an LLM is strictly forced into a JSON Schema on a hard math question with {"answer": number} (no reasoning field), why does accuracy often DROP compared to free-text CoT?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Yes! That is why Outlines and XGrammar pre-index the exact BPE token vocabulary against the character-level FSM — allowing multi-character tokens like ": " whenever every character inside that token follows a valid FSM path!
Finite-State Machine (FSM) Constrained JSON Logit Masker
Watch the grammar FSM advance token-by-token and set every schema-violating vocabulary logit to −∞ before softmax.
reasoning BEFORE answer keys!Typed Data Extraction & Classification APIs
Extracts invoices, resumes, and clinical notes directly into Pydantic/Zod objects with zero parsing crashes.
Structured Function-Call Arguments
Guarantees valid JSON argument payloads for downstream APIs (multi-step agent orchestration is covered in /learn/agentic-ai).
import torch
# FSM-Guided Constrained Decoding: Mask Invalid Vocabulary Logits to -inf at Every Step
VOCAB = ["{", '"status":', '"ok"', '"error"', "}", "hello"]
# Finite-State Machine transitions: state -> allowed token IDs
FSM_ALLOWED = {
0: [0], # must start with "{"
1: [1], # key '"status":'
2: [2, 3], # enum value '"ok"' or '"error"'
3: [4], # closing "}"
}
def constrained_step(raw_logits: torch.Tensor, state: int) -> int:
mask = torch.full_like(raw_logits, float("-inf"))
allowed = FSM_ALLOWED[state]
mask[allowed] = 0.0
return int(torch.argmax(raw_logits + mask).item())
torch.manual_seed(1)
tokens = [VOCAB[constrained_step(torch.randn(len(VOCAB)), s)] for s in range(4)]
print("Guaranteed valid JSON:", "".join(tokens))
json_object) guarantees your specific schema keys.reasoning field BEFORE the label field?