Skip to content
Skip to lesson
Back to Topics
LearnApplied LLM Engineering & RAGStructured Output Generation
MediumLLM Agents & Tool Use22 min read

Structured Output Generation

An evaluation log needs a typed run ID and status, yet prompting for JSON still produces chat. Mask illegal tokens during decoding, align subwords with grammars, and verify claims against trusted records.

On this page

Ask a language model to extract eval_id and status from a benchmark log and return JSON. Nine times out of ten, it complies. On the tenth run, right as an overnight evaluation sweep finishes, it replies:

unconstrained-reply.txt
Sure! Here is the data: { 'eval_id': 'eval-17' }

json.loads crashes at character zero on Sure!, single quotes violate RFC 8259, and status is missing altogether. Adding "Respond ONLY with valid JSON, no preamble" shifts the odds without changing the mechanism. An autoregressive model predicts next over its full vocabulary rather than returning a typed object, and conversational tokens like Sure often outscore {.

fixes this inside the sampler itself.[1] Before drawing each token, the runtime queries a compiled grammar for every vocabulary token that can legally extend the current prefix, sets all other logits to −∞-\infty, and renormalizes softmax over the surviving candidates.

Side-by-side comparison of next-token probabilities before and after grammar masking. Before masking, raw logits [1.4, 0.8, 0.2, -0.4] give Sure 49.6%, opening brace 27.2%, The 14.9%, and opening bracket 8.2%. Adding the grammar mask (0 for opening brace, negative infinity for invalid tokens) collapses 100% of renormalized probability mass onto opening brace.
Before masking, softmax turns the raw logits for Sure (1.4), { (0.8), The (0.2), and [ (-0.4) into 49.6%, 27.2%, 14.9%, and 8.2%. Setting every continuation outside the schema's start state to negative infinity leaves { with 100% probability before sampling.

In that four-token slice, only { can open a JSON object, so masking hands it 100% of the probability mass before sampling starts. Real tokenizers also contain merged tokens such as {"eval_id", which remain legal whenever they keep the prefix on a valid path. Fixing syntax crashes raises three harder questions: how does a character-level grammar stay aligned with multi-character subword tokens, why can a schema-valid object still fail local validation or contradict the source log, and how should production code handle truncation, refusals, and retries? We trace one evaluation log throughout: "Evaluation eval-17 failed on math-500 after symbolic-verifier timed out."

Why prompting for JSON fails and what decoding constraints add

A prompt like "Extract eval_id and status from this log. Return JSON." expresses a preference while leaving every vocabulary token open. In production, unconstrained replies break parsers in five recurring ways: conversational preambles (Here is the JSON: ...), Markdown code fences (triple-backtick json wrappers), schema drift ("status": null violating a required enum), invented keys ("benchmark_id" instead of "eval_id"), and malformed syntax such as trailing commas or single quotes.

Different API tiers close different portions of that gap:

Interface tierStructural guaranteeTypical implementation
Prompt-based ("respond in JSON")None (best-effort formatting)Standard chat endpoints
JSON modeTargets JSON syntax; still check incomplete and refusal statesOpenAI json_object mode
Strict function callingConstrains tool arguments to a supported schema subsetProvider tool APIs with strict mode enabled
Hosted structured outputsConstrains response text to a provider-supported schema subsetOpenAI, Claude, Gemini structured outputs
Grammar-guided inference runtimeEnforces the exact grammar compiled by the backendOutlines, SGLang, vLLM, llama.cpp

JSON mode enforces syntax alone: {"author": "alice"} is valid JSON while omitting both eval_id and status, and top-level arrays or scalars pass json.loads unless rejected.[2] Backends also differ in schema coverage: llama.cpp's schema converter can silently skip unsupported keywords,[3] Claude's native JSON outputs (output_config.format) and strict tools can still return refusals or hit token limits, and Gemini pairs its schema subset with post-generation validation.[4][5] Python's json.loads adds two hazards of its own: silently overwriting duplicate keys (last value wins) and accepting non-standard NaN or Infinity.[6] Strict parser hooks ahead of a strict model close all of those gaps in one pass:

json-syntax-versus-schema.py

def reject_constant(value: str):
    raise ValueError(f"nonfinite JSON number: {value}")

def finite_float(value: str) -> float:
    result = float(value)
    if not math.isfinite(result):
        raise ValueError("JSON number exceeds finite float range")
    return result

def unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
    result: dict[str, object] = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key}")
        result[key] = value
    return result

def load_record(raw: str):
    return json.loads(
        raw,
        object_pairs_hook=unique_object,
        parse_constant=reject_constant,
        parse_float=finite_float,
    )
Syntax and schema are separate
JSON-only result: rejected by schema
structured record: {'eval_id': 'eval-17', 'status': 'failed'}
parser rejected: duplicate JSON key: eval_id
parser rejected: nonfinite JSON number: NaN

load_record blocks duplicate keys and NaN at parse time before any dictionary reaches application code, and TriageRecord catches missing fields, extra keys, and invalid enum values right afterward.

How grammar-guided decoding works

Post-generation parsing catches syntax errors only after the model spends tokens on a broken reply. A constrained decoder tracks parser state at every decode step and masks illegal tokens before sampling:

Diagram showing Logits + state machine, Mask illegal tokens to -inf, Sample token from legal set, and Legal end token sampled?.

Reaching an accepting state allows <eos> without forcing it (trailing whitespace or optional fields may remain legal), and hitting max_output_tokens can still halt generation mid-object.

From schema to logit masking

At decoding step tt, the sampler transforms the raw logit vector zt∈R∣V∣z_t \in \mathbb{R}^{|\mathcal{V}|} before :

  1. Parser state: Track StS_t in a Deterministic Finite Automaton (DFA) for regular expressions and fixed-depth schemas, or a stack-based parser for arbitrarily recursive JSON.
  2. Legal token subset: Identify Vvalid(St)⊆V\mathcal{V}_{\text{valid}}(S_t) \subseteq \mathcal{V}, keeping only tokens that leave a completable prefix (and allowing <eos> only when StS_t is accepting).
  3. Logit mask and renormalization: Set mt(v)=0m_t(v) = 0 if v∈Vvalid(St)v \in \mathcal{V}_{\text{valid}}(S_t) and −∞-\infty otherwise, then apply softmax to zt′=zt+mtz'_t = z_t + m_t (at temperature 1): P(yt=v∣x<t)=exp⁡(zt′(v))∑u∈Vexp⁡(zt′(u))={exp⁡(zt(v))∑u∈Vvalid(St)exp⁡(zt(u))if v∈Vvalid(St)0otherwiseP(y_t = v \mid x_{<t}) = \frac{\exp(z'_t(v))}{\sum_{u \in \mathcal{V}} \exp(z'_t(u))} = \begin{cases} \frac{\exp(z_t(v))}{\sum_{u \in \mathcal{V}_{\text{valid}}(S_t)} \exp(z_t(u))} & \text{if } v \in \mathcal{V}_{\text{valid}}(S_t) \\ 0 & \text{otherwise} \end{cases}

If Vvalid(St)\mathcal{V}_{\text{valid}}(S_t) is ever empty (due to a tokenizer mismatch or unsatisfiable rule), the decoder must halt with an error rather than dropping the mask.

Deterministic finite-state parser states S0 through S3 mapped directly to rows of the precomputed valid-token bitmask M[S_t, v] over six vocabulary tokens ({, key:, pass"}, fa, Sure, <eos>), showing 1 for grammar-legal continuations and 0 for masked tokens.
Compiling a schema turns grammar rules into a state machine (S0 -> S1 -> S2 -> S3) and a valid-token bitmask M[S_t, v]. Each decoding step reads the binary row for its current state to mask the vocabulary before softmax.

Here is that vectorized masking step in NumPy on our opening four tokens:

from-schema-to-logit-masking.py
import numpy as np

def softmax(vec: np.ndarray) -> np.ndarray:
    finite = np.isfinite(vec)
    if not np.any(finite):
        raise ValueError("no legal token with a finite logit")
    shifted = np.where(finite, vec - np.max(vec[finite]), -np.inf)
    exp_scores = np.where(finite, np.exp(shifted), 0.0)
    return exp_scores / np.sum(exp_scores)

tokens = ["Sure", "{", "The", "["]
logits = np.array([1.4, 0.8, 0.2, -0.4], dtype=float)
legal_mask = np.array([False, True, False, False])

before_probs = softmax(logits)
masked_logits = np.where(legal_mask, logits, -np.inf)
after_probs = softmax(masked_logits)
Output
before softmax (%): {'Sure': 49.6, '{': 27.2, 'The': 14.9, '[': 8.2}
masked logits: {'Sure': -inf, '{': 0.8, 'The': -inf, '[': -inf}
after softmax (%): {'Sure': 0.0, '{': 100.0, 'The': 0.0, '[': 0.0}
chosen token: {

"Sure" drops from 49.6% to 0.0%, and whenever multiple tokens remain legal, softmax preserves their relative odds intact across the valid subset.

The tokenizer alignment problem

Masking logits is cheap; computing legal_mask quickly across a real vocabulary is the hard part. Grammars match characters or bytes, whereas models emit that span multiple JSON delimiters (","status":"failed") or split a UTF-8 codepoint mid-character. Checking only the first character fails: the decoder must walk every byte of a candidate token through the automaton from StS_t and reject the whole token if any byte overshoots.[1]

After {"status":", expecting "failed":

  • fa is legal (advances two characters inside "failed").
  • iled"} is legal after fa (completes the string and closes the object).
  • iled"}! is illegal: its first six characters match, yet ! overshoots into an error state.

Walking 128,000 vocabulary strings per decode step would crush throughput, so modern engines precompute and partition vocabulary lookups:

Regular expressions vs. context-free grammars

Which formalism you need depends on nesting depth, not output length. A DFA handles regular expressions, enums, and fixed-depth JSON objects (including arbitrarily long arrays of flat objects like \[(\{\}(,\{\})*)?\]) in constant working memory. Only arbitrarily deep recursive nesting requires a stack-aware Context-Free Grammar (CFG) to balance open delimiters.

Build an incremental DFA token decoder

The figure and script below compile a tiny language accepting only {"status":"passed"} and {"status":"failed"} into a character-level DFA and trace every candidate token completely through it.

Whole-token parser branches for passed and failed records. From the shared prefix opening brace status colon quote, the passed branch consumes passed then closing quote brace and enables end-of-sequence. The failed branch consumes fa, keeps end-of-sequence blocked, accepts iled closing quote brace to complete, and rejects iled closing quote brace exclamation as an overshooting whole token.
Both accepted strings share {"status":". From fa, the token iled"} reaches the final brace cleanly, whereas iled"}! overshoots at ! and is masked out as a whole token.
finite-language-token-guide.py

def advance_token(state: int, token: str) -> int | None:
    if token == '<eos>':
        return state if state in ACCEPTING else None
    if not token:
        return None
    cur = state
    for ch in token:
        if ch not in DFA[cur]:
            return None
        cur = DFA[cur][ch]
    return cur

def decode(max_steps: int = 8) -> tuple[str, list[str]]:
    state, prefix, trace = 0, '', []
    for _ in range(max_steps):
        legal = [tok for tok in VOCAB if advance_token(state, tok) is not None]
        if not legal:
            raise ValueError('grammar has no representable continuation')
        tok = max(legal, key=lambda item: SCORES[item])
        trace.append(tok)
        if tok == '<eos>':
            return prefix, trace
        state = advance_token(state, tok)
        assert state is not None
        prefix += tok
    raise ValueError('token budget ended before complete output')
Incremental DFA whole-token decoder
tokens: ['{"status":"', 'fa', 'iled"}', '<eos>']
record: {"status":"failed"}
overshooting token next state: None

Even though iled"}! scores 8.0 versus 1.0 for iled"}, advance_token rejects it at !, and <eos> (7.0) stays masked at fa_state until the object closes.

Token boundaries and token healing

When a prompt ends right on a quote or colon ('{"status":"'), greedy tokenization cuts across a merged token like '":"passed' that the model strongly prefers. Token healing backs up one prompt token and restricts the first generated token to start with the trimmed text, restoring the natural merge without changing the prompt string:[1][7]

token-healing-boundary.py

prompt = '{"status":"'
naive_tokens = greedy_tokenize(prompt, VOCAB)
trimmed_prefix, required_start = naive_tokens[:-1], naive_tokens[-1]
healed_candidates = [tok for tok in VOCAB if tok.startswith(required_start)]
Token boundary healing
naive prompt tokens: ['{"status', '":"']
healed prefix: ['{"status'] required continuation start: '":"'
healed candidates: ['":"', '":"passed']

Libraries and serving stacks

Local runtimes (Outlines, llama.cpp, SGLang, vLLM) compile grammars and apply masks inside your inference worker; hosted APIs compile schemas server-side. In Outlines, reuse a compiled Generator across requests to amortize compilation, and still validate its raw string output locally:[9]

outlines.py
class EvalStatusUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    eval_id: str
    status: Literal["queued", "passed", "failed", "unknown"]
    failing_task: str | None

model_name = "HuggingFaceTB/SmolLM2-135M-Instruct"
model = outlines.from_transformers(
    AutoModelForCausalLM.from_pretrained(model_name),
    AutoTokenizer.from_pretrained(model_name),
)
eval_generator = Generator(model, EvalStatusUpdate)
raw = eval_generator("Extract eval_id, status, and failing_task: Evaluation eval-17 failed on math-500.", max_new_tokens=120)
record = EvalStatusUpdate.model_validate_json(raw)

High-concurrency serving engines keep mask generation from stalling continuous batches. SGLang introduced RadixAttention to reuse the across shared system prompts and schema prefixes (cutting ) alongside compressed FSM jump-forward across constant substrings.[10] Today both SGLang and vLLM default to XGrammar or llguidance, overlapping CPU bitmask computation (under 40 microseconds per token in XGrammar) with the GPU forward pass over the already-accepted prefix.[8][11][12] Serial step time is tgpu+tcpu+tsamplet_{\text{gpu}} + t_{\text{cpu}} + t_{\text{sample}}; with overlap, sampling waits only for max⁡(tgpu,tcpu)+tsample\max(t_{\text{gpu}}, t_{\text{cpu}}) + t_{\text{sample}}.

Deep dive: Serving backend APIs and schema-compiler quirks

Function calling vs. structured outputs

Both tool definitions and structured extraction APIs use JSON Schema, yet they serve different host roles:

DimensionFunction calling (tool use)Structured outputs
Core purposeAgent action selection and executionStructured data extraction and transformation
Control flowModel proposes a tool; host runs it and feeds back the observationTerminal JSON record consumed directly by application code
Return formatTool name plus JSON argument objectJSON document matching the response schema
Side effectsHost validates permissions before executing the toolHost decides how to store or act on the parsed record

Function calling for tool arguments

Use function calling when an agent needs live state before answering. Setting "strict": True enforces the argument schema on the wire (GetEvalStatusArgs.model_json_schema() with ConfigDict(extra="forbid", strict=True)), and local Pydantic validation rejects extra keys like force_rerun: true before host code checks caller permissions:

strict-tool-arguments.py
from pydantic import BaseModel, ConfigDict, ValidationError

class GetEvalStatusArgs(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    eval_id: str

tool_definition = {
    "type": "function", "name": "get_eval_status", "strict": True,
    "description": "Fetch current benchmark status for an evaluation run.",
    "parameters": GetEvalStatusArgs.model_json_schema(),
}
Output
tool: get_eval_status strict: True
validated args: {'eval_id': 'eval-17'}
extra arg rejected: extra_forbidden

Structured outputs for typed records

Use structured outputs for extraction and classification pipelines. OpenAI's strict mode requires every property in required and "additionalProperties": false, so optional fields become required nullable unions (failing_task: str | None with no default).[15][16] That lets the model report missing evidence as null without omitting the key or inventing a task name:

typed-eval-record.py
class EvalStatusUpdate(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    eval_id: str
    status: Literal["queued", "passed", "failed", "unknown"]
    failing_task: str | None

schema = EvalStatusUpdate.model_json_schema()
update = EvalStatusUpdate.model_validate({"eval_id": "eval-17", "status": "failed", "failing_task": None})
A required nullable field
required: ['eval_id', 'status', 'failing_task']
closed object: True
nullable task: None
omitted task: rejected

Always validate against your original Pydantic class locally rather than the wire schema sent to the provider. Some SDK adapters strip unsupported numeric bounds (minimum, maximum) from the wire schema and append them to description prose.[4] A description nudges generation without masking illegal values, so -1 passes the wire check and is caught only by your local model:

wire-schema-drift.py
wire_schema["properties"]["retry_count"].pop("minimum")
wire_schema["properties"]["retry_count"]["description"] = "Must be at least 0"
candidate = {"retry_count": -1}

wire_int = TypeAdapter(int).validate_python(candidate["retry_count"], strict=True)
Wire constraints versus local constraints
local minimum: 0
wire minimum present: False
candidate fits wire integer shape: True
local rejection: greater_than_equal

When calling hosted APIs such as OpenAI's client.responses.parse(..., text_format=EvalStatusUpdate), check response.status == "completed", inspect every message part for part.type == "refusal", and confirm response.output_parsed is not None (buffering streaming deltas until completion before validating).

Passing schema validation still verifies shape alone. Host code must separately verify caller access and compare claims against trusted records:

separate-format-from-semantic-validation.py
EVAL_DB = {"eval-17": {"suite": "nlp-eval", "status": "failed", "failing_task": "math-500"}}

def decide_update(allowed_suites: set[str], update: TriageRecord) -> str:
    trusted = EVAL_DB.get(update.eval_id)
    if trusted is None or trusted["suite"] not in allowed_suites:
        return "deny"  # Avoid revealing whether an unauthorized eval_id exists
    if update.status != trusted["status"]:
        return "review: contradicts eval log"
    return "show"
Shape, truth, and access
format check: {'eval_id': 'eval-17', 'status': 'failed'}
authorized and true: show
other suite: deny
authorized but false: review: contradicts eval log

false_claim satisfies TriageRecord cleanly, yet decide_update catches that eval-17 actually failed in EVAL_DB and routes the contradiction for review.

Systems trade-offs: latency, reasoning quality, and schema design

Grammar constraints add measurable compilation and decoding work. Knowing which stage pays each cost keeps schemas fast and accurate:

Where latency comes from

BottleneckUnderlying causeServing impactMitigation
Schema compilationBuilding a grammar and tokenizer indexHigher cold-start TTFTReuse compiled artifacts; measure cold and warm distributions separately
Per-token grammar workAdvancing parser state and applying the maskAdds to TPOT unless overlapped with GPUBenchmark on your backend at realistic batch sizes
Schema prompt overheadField descriptions and injected schema textExtra prefill tokensMeasure prompt token counts and prefix-cache hit rates
Grammar complexityDeep nesting, wide unions, optional branchesLarger state tables or dropped keywordsProfile representative schemas; flatten where needed

Reasoning accuracy and evidence spans

Tam et al. (2024) found that strict formatting templates lowered reasoning accuracy on several benchmarks compared with free-form answers, while classification sometimes improved.[17] Benchmark your own tasks on current models, and note that reasoning models decouple thinking from formatting: internal reasoning runs unconstrained, and the schema mask activates only for the final answer.[18]

For non-reasoning models, placing an evidence_quote field before decision encourages grounding. Verify that the quote appears verbatim in the source and matches the complete eval_id with word boundaries (?<![\w-]) (so eval-170 never satisfies a citation for eval-17). Notice also what quote verification leaves unchecked: a true quote can still accompany an unjustified decision like halt_release.

validate-visible-evidence-before-decision.py

def verify_evidence_span(payload: dict[str, str], source: str) -> EvalDecision:
    record = EvalDecision.model_validate(payload)
    if record.evidence_quote not in source:
        raise ValueError("quote is not an exact span of the source")
    pattern = r"(?<![\w-])" + re.escape(record.eval_id) + r"(?![\w-])"
    if not re.search(pattern, record.evidence_quote):
        raise ValueError("eval ID does not appear in evidence")
    return record
Check the quote against the source
decision: rerun_suite | quote in source: True
invented quote: quote is not an exact span of the source
true quote with wrong action accepted by quote check: halt_release

Flattening recursive structures

When a backend rejects recursive schemas (or stack overhead matters), represent a tree as a flat array of nodes with parent_id links. A flat array is a regular language that any DFA compiles cleanly, shifting structural validation (unique IDs, single root, valid parents, and connectedness via root traversal) into host code:

reconstruct-a-flat-tree-after-validation.py

def validate_tree(nodes: list[FlatNode], max_nodes: int = 100):
    if not 1 <= len(nodes) <= max_nodes:
        raise ValueError("node count outside allowed range")
    by_id = {n.node_id: n for n in nodes}
    if len(by_id) != len(nodes) or any(not n.node_id.strip() for n in nodes):
        raise ValueError("node IDs must be unique and nonempty")
    roots = [n.node_id for n in nodes if n.parent_id is None]
    if len(roots) != 1:
        raise ValueError("expected one root")
    children = {n.node_id: [] for n in nodes}
    for n in nodes:
        if n.parent_id is not None:
            if n.parent_id not in by_id:
                raise ValueError("unknown parent")
            children[n.parent_id].append(n.node_id)
    pending, visited = [roots[0]], set()
    while pending:
        current = pending.pop()
        if current in visited:
            raise ValueError("cycle detected")
        visited.add(current)
        pending.extend(children[current])
    if len(visited) != len(nodes):
        raise ValueError("disconnected nodes or cycles present")
    return roots[0], children
Output
root ID: root | child IDs: ['n1', 'n2']
invalid tree: disconnected nodes or cycles present

Every parent pointer in cyclic resolves to an existing ID, yet traversing from root visits only 1 of 3 nodes and catches the disconnected a <-> b cycle immediately.

Failure modes and production recovery

Even when every emitted token obeys the compiled grammar, generation can stall on legal whitespace, truncate before closing the object, hit a refusal, or emit a bogus permission boolean.

A grammar constrains local syntax without measuring progress toward completion: optional whitespace rules allow repeated newlines until max_output_tokens runs out. Low logits on legal tokens never cause a dead end by themselves because softmax renormalizes positive mass over whatever legal set remains; true dead ends occur only when the legal set is empty. Enforce strict token and wall-clock caps, and keep clear field semantics in the prompt (skip pasting duplicate JSON Schema text when the API already injects it).

Version schemas in application code

Attach schema_version in your validation layer ({"schema_version": "2", "payload": EvalStatusUpdate.model_validate(raw).model_dump()}) rather than asking the model to emit it. A model-generated version string is untrusted text and cannot tell downstream storage which validator actually ran.

Route each stop condition to its own recovery path

Inspect the stop reason instead of blindly retrying with a looser prompt:

Recovery cascade branching on API completion status. Completed responses go to strict JSON parsing, local Pydantic validation, and caller access and evidence checks. Truncated max_output_tokens responses check budget and deadline for one same-schema retry at 400 tokens and fail on a second stop. Refusal or content filter stops immediately, and invalid schema triggers code repair.
Each completion outcome follows its own recovery path. Only a length truncation (max_tokens) that stays within budget and latency limits qualifies for a single retry at 400 tokens; refusals stop retries, bad schemas require an adapter fix, and completed outputs still face schema and host checks.
  1. Completed candidate: Decode strictly, validate with local Pydantic, and verify source facts and caller permissions.
  2. Token limit: Retry once with the exact same schema and a larger token cap only if the retry fits the model limit, remaining deadline (including local validation time), and remaining cost budget. (Chat Completions signals finish_reason: "length"; Responses signals status: "incomplete" with incomplete_details.reason: "max_output_tokens".)[15]
  3. Refusal or content-filter stop: Halt automatic retries immediately and return a safe refusal.
  4. Unsupported or invalid schema: Fix the schema or SDK adapter in code; retrying identical input fails identically.
  5. Local validation failure: Check whether a wire adapter dropped a rule or the prompt misled a value; if retrying once with an error message, strip secrets and internal permissions from the feedback.
retry-on-truncation.py

def extract_with_single_retry(client, input_text: str) -> EvalStatusUpdate:
    for attempt, budget in enumerate((120, 400)):
        response = client.create(input=input_text, text={"format": FORMAT}, max_output_tokens=budget)
        output = response.get("output", [])
        content = [p for item in output if item.get("type") == "message" for p in item.get("content", [])]
        if any(p.get("type") == "refusal" for p in content):
            raise RuntimeError("safety refusal: request blocked by model")
        status = response.get("status")
        if status == "incomplete":
            reason = (response.get("incomplete_details") or {}).get("reason")
            if reason == "max_output_tokens" and attempt == 0:
                continue
            raise RuntimeError(f"halted prematurely: {reason}")
        if status != "completed":
            raise RuntimeError(f"unexpected completion status: {status}")
        messages = [item for item in output if item.get("type") == "message"]
        if len(messages) != 1 or messages[0].get("status") != "completed":
            raise RuntimeError("expected one completed output message")
        if len(content) != 1 or content[0].get("type") != "output_text":
            raise RuntimeError("expected one structured text item")
        return EvalStatusUpdate.model_validate(load_record(content[0]["text"]))
    raise RuntimeError("retry budget exhausted")
Retry only a length stop
retry preserved schema: {'eval_id': 'eval-17', 'status': 'failed', 'failing_task': 'math-500'}
budgets: [120, 400]
refusal routed: safety refusal: request blocked by model; calls=1
content filter: halted prematurely: content_filter; calls=1
second length stop: halted prematurely: max_output_tokens; calls=2

Never trust permission booleans emitted by a model

A schema-valid payload like {"eval_id": "eval-17", "action": "rerun_suite", "approved": true} tells you only that approved is a boolean. Reading model-generated flags as authorization grants creates an instant privilege-escalation bug. Ignore self-attested booleans and check verified session credentials and stored approvals in host state:

ignore-self-attested-approval.py

def check_approval(proposal: ModelEvalProposal, stored_request: tuple[str, str] | None) -> str:
    if proposal.action != "rerun_suite":
        return "deny: unsupported action"
    if stored_request != (proposal.eval_id, proposal.action):
        return "deny: missing approval for this request"
    return "approval matched; continue host checks"
Output
deny: missing approval for this request
deny: missing approval for this request
approval matched; continue host checks

Practice: build a benchmark-digest validator

Combine these layers on a nightly evaluation report:

"math-500 recovered to target score after prompt tuning. humaneval-plus remains degraded. gpqa-diamond has no recorded run today."

Requirements:

  1. Return {"mentions": [{"suite": "...", "status": "passed|degraded|failed|unknown"}, ...]} under strict structured outputs.
  2. Represent zero suite mentions as {"mentions": []}, never null or a missing key.
  3. Reject duplicate suite entries in host code (array position carries no timestamp, so a last-wins dict comprehension silently masks conflicting statuses) and flag suites outside the registered catalog (math-500, humaneval-plus, mmlu-pro) for review.
benchmark-digest-validator.py

def unknown_suites(digest: BenchmarkDigest) -> list[str]:
    return [m.suite for m in digest.mentions if m.suite not in KNOWN_SUITES]

def check_unique_suites(digest: BenchmarkDigest) -> None:
    seen: set[str] = set()
    for mention in digest.mentions:
        if mention.suite in seen:
            raise ValueError(f"duplicate suite summary: {mention.suite}")
        seen.add(mention.suite)
Output
mentions: 3 | unknown suites: ['gpqa-diamond']
empty mentions: []
tempting dict conversion: {'math-500': 'failed'}
identity check: duplicate suite summary: math-500

{"mentions": []} distinguishes an empty report from a failed extraction, unknown suites like gpqa-diamond surface cleanly without crashing the parser, and check_unique_suites catches conflicting entries before a dictionary comprehension silently hides them.

Summary: four layers of structured reliability

  1. Grammar-guided decoding masks illegal tokens before softmax to enforce syntax and supported schema rules at token generation time.
  2. Strict JSON parsing and local Pydantic models catch duplicate keys, nonfinite numbers, and numeric bounds stripped by wire adapters.
  3. Host verification compares extracted claims against trusted stores and derives access decisions exclusively from authenticated application state.
  4. Stop-reason recovery retries a single token-limit cutoff when budgets allow while halting on refusals and fixing bad schemas in code.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.At temperature one, four next-token candidates have exponentiated weights 1, 4, 6 and 9. The grammar permits only the first and third. What is their masked distribution in the original candidate order?
2.A grammar accepts exactly the balanced strings over the two characters [ and ], with no limit on nesting depth. From the accepted prefix [[, try token A (]]) and token B (]!]) separately. Which tuple gives the legality of A, the legality of B, and whether the end-of-sequence token (EOS) is allowed at the original prefix?
3.A completed extraction record requires exactly eval_id, status and nullable failing_task. Its source says eval-316 failed but names no task. Which candidate preserves both field presence and the evidence gap?
4.The original JSON Schema for a job's workers field is {"type":"integer","maximum":6}. Both adapters send {"type":"integer","description":"Up to 6 workers"} to the backend. After generation, adapter A validates the field against the schema it sent. Adapter B validates it against the original schema. Which adapters accept a completed record with workers set to the number 8?
5.A completed record names code-eval and eval-528 with status failed. The caller is permitted access only to code-eval; its evaluation database says eval-528 passed. What is the first failed host predicate and the resulting record outcome?
6.A flat tree contains R(parent=None), U(parent=V), V(parent=U) and W(parent=R). IDs are unique, parent IDs exist and node count is within the allowed limit. Which result follows the taught root traversal check?
7.A measured token-step profile has GPU forward time 7 ms, CPU mask time 11 ms and sampling time 2 ms. Both stages use the same already accepted prefix and may overlap perfectly. What are serial and overlapped completion times?
8.Four requests have each finished their first call. Each has an 18-second deadline and a total budget of 10 cost units. The wrapper allows one same-schema retry after a token-limit stop. The retry needs 720 output tokens (model limit 800) and costs 4 units. The call takes 5 seconds, followed by 2 seconds for validation. A hit its token limit after 12 seconds and spent 5 units. B hit its token limit after 8 seconds and spent 8 units. C received a refusal after 7 seconds and spent 3 units. D hit its token limit after 10 seconds and spent 2 units. Which requests may retry?
9.The trusted retention log reads eval-73 checkpoints are 34 days old. eval-730 checkpoints are 12 days old. A record for eval-73 proposes pruning its checkpoints and quotes eval-730 checkpoints are 12 days old. The citation must be an exact span containing the target's complete evaluation ID. The retention rule permits pruning checkpoints at least 30 days old. Check two things separately. Does the citation pass for the target evaluation? Do the log and rule support pruning that evaluation's checkpoints?
10.A digest candidate has two summaries for cataloged math-500: degraded and passed. Its shape and enum checks pass. A separate report has no suite mentions. Which pair follows the taught identity and empty-report rules?

10 questions remaining.

References

Efficient Guided Generation for Large Language Models

Willard, B. T. & Louf, R. · 2023 · arXiv preprint

https://arxiv.org/abs/2307.09702

Introducing Structured Outputs in the API

OpenAI · 2024

https://openai.com/index/introducing-structured-outputs-in-the-api/

llama.cpp Grammars Documentation

ggml-org · 2026

https://github.com/ggml-org/llama.cpp/blob/master/grammars/README.md

Structured outputs

Anthropic · 2026

https://platform.claude.com/docs/en/build-with-claude/structured-outputs

Structured outputs

Google · 2026

https://ai.google.dev/gemini-api/docs/structured-output

json: JSON encoder and decoder

Python Software Foundation · 2026

https://docs.python.org/3/library/json.html

llguidance: Super-fast Structured Outputs

Guidance Contributors · 2026

https://github.com/guidance-ai/llguidance

XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models

Dong, Y., Ruan, C. F., Cai, Y., et al. · 2024

https://arxiv.org/abs/2411.15100

Generator API

Outlines Developers · 2026

https://dottxt-ai.github.io/outlines/latest/features/core/generator/

SGLang: Efficient Execution of Structured Language Model Programs.

Zheng, L., et al. · 2023

https://arxiv.org/abs/2312.07104

SGLang Structured Outputs Documentation

SGLang Project · 2026

https://docs.sglang.io/docs/advanced_features/structured_outputs

Structured Outputs

vLLM Contributors · 2026

https://docs.vllm.ai/en/latest/features/structured_outputs/

Structured Generation Backends

Outlines Developers · 2026

https://dottxt-ai.github.io/outlines/latest/features/advanced/backends/

llama.cpp: Inference of LLaMA model in pure C/C++

Gerganov, G. · 2023

https://github.com/ggml-org/llama.cpp

Structured model outputs

OpenAI · 2026

https://developers.openai.com/api/docs/guides/structured-outputs

Strict Mode

Pydantic Contributors · 2026

https://pydantic.dev/docs/validation/latest/concepts/strict_mode/

Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models

Tam, Z. R., Wu, C.-K., Tsai, Y.-L., et al. · 2024

https://arxiv.org/abs/2408.02442

Reasoning models

OpenAI · 2026

https://developers.openai.com/api/docs/guides/reasoning

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.