FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Structured Outputs

How schemas convert probabilistic text generation into validated application contracts.

Freshness: current•15 min read•LLM Application Engineering

Key Learning Outcomes

  • ✓Define output schemas
  • ✓Separate syntax from semantics
  • ✓Handle validation failures
Full Technical Reference Document

Mental model

Structured outputs enforce syntactic schema conformance during autoregressive generation by compiling a JSON Schema or Context-Free Grammar (CFG) into a finite-state machine that masks invalid next-token logits to negative infinity. While constrained decoding eliminates malformed JSON syntax errors at the serialization boundary, it cannot verify factual truth, arithmetic consistency, or domain authorization, which still require downstream application validation.

JSON Schema Contract
Compile CFG / FSM State Graph
Apply Token Logit Bitmask
Stream or Repair Partial Payload
Enforce Pydantic v2 & Domain Invariants
Conceptual teaching model synthesized from:Structured OutputsPydantic V2 Architecture & Rust Core Data ValidationJSON parser for incomplete streams - AI SDK UIjsonrepair: Repair invalid JSON documents

Learning outcomes

  • Explain how constrained decoding engines derive per-step vocabulary bitmasks from a Context-Free Grammar or finite-state automaton.
  • Quantify the latency trade-off between cold-start grammar compilation and steady-state bitmask application during token decoding.
  • Diagnose why strict JSON schemas placed too early in generation degrade multi-step reasoning accuracy and how to preserve scratchpad capacity.
  • Build a layered validation pipeline combining native schema enforcement, jsonrepair fallback recovery, and strict Pydantic v2 semantic validators.

Theory

Unconstrained language models sample next tokens from raw vocabulary logits zt∈R∣V∣z_t \in \mathbb{R}^{|V|} across a vocabulary of size ∣V∣|V| (typically 100,000 to 150,000 tokens). Even well-prompted models occasionally emit trailing commas, unescaped quotes, or markdown code fences that break json.loads(). Constrained decoding engines—such as OpenAI's CFG compiler or XGrammar's pushdown automaton—eliminate syntactic drift inside the inference engine itself.

At each decoding step tt, the active grammar state sts_t defines the set of syntactically legal tokens A(st)⊆VA(s_t) \subseteq V that can validly extend the current JSON prefix toward a complete document. The engine constructs a binary mask vector Mt∈{0,−∞}∣V∣M_t \in \{0, -\infty\}^{|V|} and adds it to the raw logit vector before softmax normalization:

P(xt=v∣x<t,st)=exp⁡(zt,v+Mt,v)∑w∈Vexp⁡(zt,w+Mt,w),Mt,v={0v∈A(st)−∞v∉A(st)P(x_t = v \mid x_{<t}, s_t) = \frac{\exp(z_{t,v} + M_{t,v})}{\sum_{w \in V} \exp(z_{t,w} + M_{t,w})}, \quad M_{t,v} = \begin{cases} 0 & v \in A(s_t) \\ -\infty & v \notin A(s_t) \end{cases}

Because tokens outside A(st)A(s_t) receive −∞-\infty pre-softmax logit weight, their post-softmax sampling probability collapses strictly to zero. As soon as token xtx_t is sampled, the automaton advances deterministically to state st+1=δ(st,xt)s_{t+1} = \delta(s_t, x_t).

Token Prefix Trie & Grammar-Guided Masking

CFG Grammar State: Expecting: String KeyJSON Schema Enforced
Allowed Vocabulary Tokens (Logits Retained)
"name""age""status""role"
Masked Out Tokens (Logits = -∞)
"{"":"","123false
Valid Tokens4 tokens
Masked Tokens5 masked
Syntax Error Rate0.00% (Guaranteed)
Outlines Regex EngineFSM Ahead-of-Time

Cold-Start Compilation vs Steady-State Decode Overhead

Converting an arbitrary JSON Schema (with nested objects, anyOf unions, regex string patterns, and required fields) into token-level transition tables requires scanning the entire model vocabulary against grammar states. This introduces two distinct latency regimes:

  1. Cold-start FSM compilation: Compiling a fresh schema can take 50 ms to over 2,000 ms on first request depending on schema complexity, regex NFA size, and vocabulary cardinality. Serving systems amortize this by hashing normalized schemas and caching compiled finite-state automata in memory.
  2. Steady-state decode masking: Once cached, per-step bitmask lookup and GPU logit masking execute in roughly 30 to 80 microseconds per token when overlapped asynchronously on CPU threads alongside GPU forward passes.

Consider an extraction service running a 128,256-token vocabulary model generating 250 JSON output tokens per call at a 15 ms inter-token latency (ITL). On a cold schema miss taking 450 ms to compile the FSM, total request latency equals 450 + 250 * 15 = 4,200 ms, adding a 12% latency spike solely from grammar compilation. Once cached, steady-state bitmask application adds only 250 * 0.06 = 15 ms (0.4% of decode time) while eliminating JSON retry loops that previously consumed 1.8x extra tokens on parse failures.

Reasoning Interference and Scratchpad Placement

Forcing a model to emit rigid schema fields immediately at token 0 interferes with multi-step reasoning. When the first required key is "decision": "approve" | "reject", the model must commit to the categorical label before generating any justifying token computation, degrading accuracy on math, policy evaluation, and multi-hop extraction tasks. Providing an explicit leading "reasoning_steps" field—or invoking a reasoning model that emits hidden chain-of-thought tokens prior to the JSON payload—restores compute depth before the final structured verdict is masked.

Trade-offs

Engineering teams choose between provider-native grammar constraints, streaming partial parsers, and post-hoc repair based on latency budgets, schema portability, and model family support.

ApproachSyntax ReliabilityCold-Start / Compute CostReasoning ImpactBest Fit Workload
Native CFG / FSM Constrained Decoding100% grammar compliantModerate cold-start compile, near-zero steady-state overheadCan hurt accuracy if answer keys precede reasoning fieldsProduction extraction, typed tool arguments, strict pipelines
Streaming Partial JSON ParserCloses open brackets mid-streamNegligible CPU parse per chunkNoneLive UI rendering of partially streamed cards or tables
Prompted JSON + jsonrepair + PydanticHigh after repair, not 100%Zero engine compile; small post-hoc CPU costPreserves free-form scratchpads before JSONLegacy open-weight APIs or heterogeneous multi-model fallbacks

Failure modes and misconceptions

  • Equating valid JSON syntax with semantic validity: A grammar guarantees invoice_total is an integer and currency matches "USD" | "EUR", yet the model can still hallucinate "invoice_total": 999999 or invent an inactive vendor_id. Always follow schema parsing with Pydantic v2 cross-field validators and database foreign-key lookups.
  • Ignoring model refusal signals: Strict schemas on safety-critical prompts must permit an explicit refusal union branch or check the API's dedicated message.refusal field; otherwise logit masking traps the model into outputting fabricated placeholder values to satisfy required keys.
  • Unbounded dynamic schemas defeating FSM caching: Generating unique JSON Schemas per user (for instance embedding dynamic user-specific enum lists of 500 database IDs inside the schema) causes perpetual cache misses and repeated cold-start compilation timeouts.
  • Putting verdict fields before rationale fields: Placing "approved": true | false first in properties forces premature commitment before the model's autoregressive forward passes compute intermediate arithmetic or policy checks.
  • Trusting repaired truncated output silently: Libraries like jsonrepair fix missing closing braces and quotes cleanly, yet if finish_reason == "length", closing a truncated array hides missing trailing items unless truncation is detected explicitly.

Decision scenario

An accounts-payable ingestion pipeline extracts line items, tax rates, and totals from supplier PDFs across three model providers: a primary API supporting strict JSON Schema decoding and a secondary open-weights fallback endpoint without grammar masking. Engineering observes occasional schema compilation stalls when vendor IDs are injected into schema enums and catches silent arithmetic mismatches where sum(line_items) != total_cents. To stabilize the pipeline, keep the JSON Schema static (validating vendor_id syntax via regex while checking active vendor existence in Postgres) so the FSM cache stays warm at a 99.9% hit rate. Require a leading calculation_notes field before total_cents, route fallback completions through jsonrepair only when finish_reason == "stop", and enforce exact arithmetic reconciliation inside a Pydantic v2 @model_validator before posting ledger entries.

Implementation example

This Python validator handles primary JSON parsing, guarded jsonrepair fallback recovery on non-truncated responses, and strict Pydantic v2 cross-field semantic verification.

python
import json
from typing import Literal
from jsonrepair import repair_json
from pydantic import BaseModel, Field, model_validator
​
class LineItem(BaseModel):
sku: str = Field(..., pattern=r"^[A-Z0-9_-]{3,24}$")
qty: int = Field(..., gt=0, le=10000)
unit_cents: int = Field(..., ge=0)
​
class InvoiceExtraction(BaseModel):
calculation_notes: str = Field(..., min_length=10, max_length=600)
currency: Literal["USD", "EUR", "GBP"]
items: list[LineItem] = Field(..., min_length=1)
subtotal_cents: int = Field(..., ge=0)
​
@model_validator(mode="after")
def verify_line_item_arithmetic(self) -> "InvoiceExtraction":
expected = sum(item.qty * item.unit_cents for item in self.items)
if expected != self.subtotal_cents:
raise ValueError(f"Arithmetic mismatch: items={expected}, got={self.subtotal_cents}")
return self
​
def parse_and_verify_invoice(raw_text: str, finish_reason: str) -> InvoiceExtraction:
if finish_reason != "stop":
raise RuntimeError(f"Incomplete generation rejected: finish_reason={finish_reason}")
try:
payload = json.loads(raw_text)
except json.JSONDecodeError:
payload = json.loads(repair_json(raw_text))
return InvoiceExtraction.model_validate(payload)

Knowledge check

Reflect before revealing the guide

Why can a response that passes 100% CFG logit-masked decoding still fail production business invariants, and how do schema ordering and Pydantic v2 validators address both gaps?

Prerequisites & Related Concepts (5)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next