Most of the agent reliability conversation is about the wrong layer. Teams talk about retries, checkpointing, eval suites, and orchestration patterns — all critical, none of them the lowest-level guarantee in your stack. The quiet architectural shift of the last eighteen months is that the contract between an LLM and the rest of your system has moved from trust to grammar.
We’re talking about constrained decoding: the inference-engine trick that makes it physically impossible for a model to emit a token that violates your schema. It’s the mechanism underneath every provider’s “100% structured outputs” claim, and it’s becoming more load-bearing every quarter as agents turn tool calls, routing decisions, memory writes, and sub-agent messages into structured traffic. This is the missing substrate under our agent reliability engineering argument: before you can be reliable across steps, each step has to produce output your code can actually consume.
The Five Layers of Structured Output
“Structured output” is not one technique. It’s a stack of increasingly strong guarantees, and knowing which layer you’re on determines how seriously you can trust the result.
| Layer | Technique | Guarantee | When to use |
|---|---|---|---|
| 1 | Prompting (“return JSON”) | None | Prototypes, capable models |
| 2 | JSON mode | Syntactically valid JSON, no schema | Throwaway tools |
| 3 | Schema validation (post-hoc + retry) | Valid after retry | Extraction with retry budget |
| 4 | Grammar-constrained decoding | Tokens that violate the grammar get zero probability | Tool args, routing, plans |
| 5 | Precomputed FSM token masks | Same as 4, at near-zero overhead | High-throughput self-hosted |
Layer 4 is where the real story is. The engine compiles a JSON Schema into a formal grammar — a finite-state machine, context-free grammar, or pushdown automaton — and at every decode step masks out any token that would break the structure. The model cannot emit {"intent": 42" because the token for the stray quote never survives masking. That’s the difference between “prompted to be well-formed” and “well-formed by construction.”
OpenAI shipped this in August 2024 with response_format: {"type": "json_schema", "json_schema": {...}, "strict": true}, reporting a 100% pass rate on their complex-schema eval versus under 40% for gpt-4-0613. Anthropic mirrors it with output_config.format for JSON and strict: true on tool definitions, surfacing Pydantic and Zod types straight through the SDK. Gemini exposes the same via response_schema plus responseMimeType: "application/json".
On the open-source side this is a solved performance problem. XGrammar and Microsoft’s llguidance generate token masks in tens of microseconds — roughly 40–50 µs of CPU per token, often faster than unconstrained generation because a fully-determined next token skips sampling entirely. The “latency cost” argument for prompt-only JSON is dead.
What “100% Schema Compliance” Doesn’t Guarantee
Here’s the part the marketing slides over. The guarantee is narrow and specific: the output will parse, and it will validate against your schema. That is all.
It does not cover:
- Semantic correctness. A schema with
"confidence": {"type": "number"}always returns a number. Nothing stops it from returning0.9999when the honest answer is0.3. - Refusal dressed up as valid JSON. A model under safety pressure can return a schema-valid object whose string field contains “I cannot assist with that request.” The grammar is satisfied; your pipeline is not.
- Hallucinated but well-typed values. A free-form
"country": {"type": "string"}field will happily receive a plausible-but-wrong string. Enums are your only hard rail here. - Advisory constraints. Numeric range annotations and string formats behave as guidance, not token masks, on most engines.
This is the single most important mental model shift for teams adopting these features. Constrained decoding guarantees the shape of the contract, never the meaning. Your semantic eval layer — assertion checks, LLM-as-judge, golden datasets — does not become optional just because the JSON always parses. It becomes cheaper, because it no longer has to filter malformed output before it can evaluate meaning.
The Reasoning Tax
There’s a real cost to clamping every token, and it’s easy to miss until you benchmark. Constraints don’t just block invalid output — they can push the model off its highest-probability reasoning path, because forcing a token sequence through a narrow grammar slot changes the logits that follow.
The CRANE paper (ICML 2025) found constrained decoding measurably degrades results on symbolic reasoning and code generation, and showed that alternating constrained and unconstrained windows recovers up to 10 percentage points. The lesson that stuck with us: reasoning should happen in free text; only the emitted artifact should be constrained.
That’s why the 2026 pattern is a split output — a free-form reasoning channel that terminates at a sentinel, followed by a tightly masked structured block. You can see OpenAI’s Harmony format and DeepSeek’s XML tool-call convention both converging on exactly this shape: think first, then emit. The industry learned the CRANE lesson before most teams finished reading it.
The Shift: From Parse Safety to Contract Surface
Here’s the trend that makes this a deep dive rather than a feature writeup. Structured generation started as a parsing convenience — “stop returning broken JSON.” It’s now the interface layer of the entire agent stack.
Consider what actually moves between components in a modern agent: tool call arguments, routing intents, plan steps, memory writes, sub-agent handoffs, evaluator verdicts, guardrail verdicts. All of it is schema-shaped traffic. The moment that’s true, constrained decoding stops being about your parser and becomes about inter-component compatibility. A tool argument that’s valid by construction is a tool argument that can’t crash the next node in the graph.
The strongest evidence of this trend is XGrammar-2, released in May 2026. Its headline feature — Structural Tag, a composable DSL for describing arbitrary output structures — exists precisely because agent harnesses now nest reasoning, tool calls, and final responses inside a single generation. XGrammar-2 is integrated into SGLang, vLLM, TensorRT-LLM, and MLC-LLM, and adopted by xAI, Databricks, and DeepSeek. The performance numbers it ships with (up to 80× efficiency gains over v1, a 100× reduction in repetition-state preprocessing) tell you this is now a product problem, not a research problem.
The consequence for how you build: a durable-execution runtime like the ones in our Temporal vs Restate vs Hatchet vs Inngest comparison can only replay a step exactly-once if the step’s inputs and outputs are deserializable. Durable execution and structured output are two halves of the same guarantee — determinism of state, determinism of shape.
The Playbook
Opinionated rules we’ve settled on after running these in production:
- Constrain tool arguments, routing, and plan emission. Anything a machine consumes goes through Layer 4. Free text is for humans.
- Keep grammars flat and enumerable. Deep nesting and giant enum sets inflate compilation and mask cost for no reliability gain.
- Leave reasoning unconstrained. Use the free-text → sentinel → structured-block pattern. Don’t force a reasoning chain through a JSON slot.
- Validate semantics separately. Schema validity is a necessary condition, never a sufficient one.
Here’s the complete pattern, runnable as-is:
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field
client = OpenAI()
class Route(BaseModel):
"""Where to send this customer request."""
intent: Literal["check_order", "refund", "escalate", "answer"]
confidence: float = Field(description="0-1 confidence in the routing decision")
order_id: str | None = Field(
default=None, description="Order id if the user mentioned one"
)
# Schema validity is not correctness. This is the layer structured
# output doesn't replace.
def validate_semantics(route: Route) -> Route:
if route.intent == "refund" and not route.order_id:
raise ValueError("refund intent requires an order_id")
return route
response = client.chat.completions.parse(
model="gpt-4.1-mini",
messages=[
{
"role": "system",
"content": (
"Route customer requests. Be conservative: only pick "
"'refund' when the user explicitly asks for money back."
),
},
{
"role": "user",
"content": "I'd like a refund for order #8842 — the widget arrived broken.",
},
],
response_format=Route,
)
route = validate_semantics(response.choices[0].message.parsed)
print(route.model_dump())
Same guarantee, self-hosted layer, one flag:
vllm serve meta-llama/Llama-3.3-70B-Instruct \
--guided-decoding-backend xgrammar
Where It Still Breaks
Three known failure modes, in rough order of how often they bite:
- Streaming consumers break the atomicity assumption. A structured block isn’t “valid” until the final token lands. If you parse incrementally mid-stream, you’re back to hand-rolling partial-state logic.
- Long outputs leave the masked tail deprioritized. Constraints force high-probability tokens out of a narrow beam, and on some backends the valid-token set gets progressively worse the longer the generation runs.
- Post-hoc validation without masking. Model gateways that “validate and retry” (Layer 3) still cost you the failed generation’s tokens and latency. The production win comes from masking before sampling, not retrying after.
What We’re Watching Next
The interesting frontier is constraints escaping JSON entirely. XGrammar-2’s Structural Tag already handles arbitrary nesting — reasoning traces with embedded structured blocks, regex and literal composition, model-specific tool-call dialects as first-class grammars. Watch for two things over the next few quarters: grammar definitions becoming content-addressed (shared, cached, versioned across services the way MCP tool schemas did), and constrained decoding becoming a dial you tune rather than a switch you flip, with per-region masking decisions informed by the same signal your inference engines already collect.
The throughline is unglamorous but consistent: the agent stack keeps converting vibes into contracts. Constrained decoding is how the lowest-level of those contracts stops being a suggestion and starts being a guarantee.