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:
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 tokens over its full vocabulary rather than returning a typed object, and conversational tokens like Sure often outscore {.
Structured output generation 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 , 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.](https://assets.leetllm.com/v1/e5b375508797/agents/structured-output-constrained-generation/illustrations/_generated/probability_mask_dark.png)
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 tier | Structural guarantee | Typical implementation |
|---|---|---|
| Prompt-based ("respond in JSON") | None (best-effort formatting) | Standard chat endpoints |
| JSON mode | Targets JSON syntax; still check incomplete and refusal states | OpenAI json_object mode |
| Strict function calling | Constrains tool arguments to a supported schema subset | Provider tool APIs with strict mode enabled |
| Hosted structured outputs | Constrains response text to a provider-supported schema subset | OpenAI, Claude, Gemini structured outputs |
| Grammar-guided inference runtime | Enforces the exact grammar compiled by the backend | Outlines, 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 Pydantic model close all of those gaps in one pass:
import json
import math
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class TriageRecord(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
eval_id: str = Field(min_length=1)
status: Literal["queued", "passed", "failed", "unknown"]
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_valid_wrong_shape = load_record('{"foo": "bar"}')
schema_valid = load_record('{"eval_id": "eval-17", "status": "failed"}')
try:
TriageRecord.model_validate(syntax_valid_wrong_shape)
except ValidationError:
print("JSON-only result: rejected by schema")
print("structured record:", TriageRecord.model_validate(schema_valid).model_dump())
for raw in ['{"eval_id":"eval-17","eval_id":"eval-19"}', '{"status":NaN}']:
try:
load_record(raw)
except ValueError as error:
print("parser rejected:", error)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: NaNload_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.
What can you assume after JSON mode, and what changes with structured outputs?
Answer
JSON mode targets syntactically valid JSON without guaranteeing your keys or enum values. Structured outputs enforce supported schema rules during decoding. Check completion and refusal states alongside backend limits, then validate locally; neither feature verifies truthfulness or grants execution permission.
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:

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 , the sampler transforms the raw logit vector before softmax:
- Parser state: Track in a Deterministic Finite Automaton (DFA) for regular expressions and fixed-depth schemas, or a stack-based parser for arbitrarily recursive JSON.
- Legal token subset: Identify , keeping only tokens that leave a completable prefix (and allowing
<eos>only when is accepting). - Logit mask and renormalization: Set if and otherwise, then apply softmax to (at temperature 1):
If 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.](https://assets.leetllm.com/v1/2324ab996d98/agents/structured-output-constrained-generation/illustrations/_generated/contract_gates_dark.png)
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:
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)
chosen = tokens[int(np.argmax(after_probs))]
print("before softmax (%):", {t: round(float(p) * 100, 1) for t, p in zip(tokens, before_probs)})
print("masked logits:", {t: float(x) for t, x in zip(tokens, masked_logits)})
print("after softmax (%):", {t: round(float(p) * 100, 1) for t, p in zip(tokens, after_probs)})
print("chosen token:", chosen)
assert chosen == "{"
assert np.isclose(after_probs[1], 1.0)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 subword tokens 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 and reject the whole token if any byte overshoots.[1]
After {"status":", expecting "failed":
fais legal (advances two characters inside"failed").iled"}is legal afterfa(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:
- Indexed finite-state decoding (Willard and Louf, 2023) precomputes the allowed token IDs per reachable DFA state into a lookup table.[1]
- llguidance pairs an Earley context-free parser, a regex lexer, and a tokenizer trie to compute masks incrementally.[7]
- XGrammar splits the vocabulary into context-independent tokens (precomputed bitmasks per active rule) and context-dependent tokens (checked dynamically against the parser stack).[8]
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.

{"status":". From fa, the token iled"} reaches the final brace cleanly, whereas iled"}! overshoots at ! and is masked out as a whole token.LANGUAGE = ('{"status":"passed"}', '{"status":"failed"}')
VOCAB = ('The', '{"status":"', 'fa', 'passed', 'iled"}', 'iled"}!', '"}', '<eos>')
SCORES = {
'The': 9.0, '{"status":"': 1.0, 'fa': 3.0, 'passed': 2.0,
'iled"}': 1.0, 'iled"}!': 8.0, '"}': 1.0, '<eos>': 7.0,
}
def build_prefix_dfa(strings: tuple[str, ...]) -> tuple[dict[int, dict[str, int]], set[int]]:
prefixes = {''}
for s in strings:
for i in range(1, len(s) + 1):
prefixes.add(s[:i])
state_id = {p: idx for idx, p in enumerate(sorted(prefixes, key=lambda x: (len(x), x)))}
transitions: dict[int, dict[str, int]] = {idx: {} for idx in state_id.values()}
for p, sid in state_id.items():
for ch in {s[len(p)] for s in strings if s.startswith(p) and len(p) < len(s)}:
transitions[sid][ch] = state_id[p + ch]
return transitions, {state_id[s] for s in strings}
DFA, ACCEPTING = build_prefix_dfa(LANGUAGE)
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')
record, trace = decode()
print('tokens:', trace)
print('record:', record)
fa_state = advance_token(advance_token(0, '{"status":"'), 'fa')
print('overshooting token next state:', advance_token(fa_state, 'iled"}!'))
assert record in LANGUAGE
assert advance_token(fa_state, '<eos>') is Nonetokens: ['{"status":"', 'fa', 'iled"}', '<eos>']
record: {"status":"failed"}
overshooting token next state: NoneEven 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]
VOCAB = ['"', ':', '{', '":"', '":"passed', 'passed', '{"status', '"}']
def greedy_tokenize(text: str, vocab: list[str]) -> list[str]:
tokens, pos = [], 0
while pos < len(text):
match = max((tok for tok in vocab if text.startswith(tok, pos)), key=len)
tokens.append(match)
pos += len(match)
return tokens
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)]
print("naive prompt tokens:", naive_tokens)
print("healed prefix:", trimmed_prefix, "required continuation start:", repr(required_start))
print("healed candidates:", healed_candidates)
assert '":"passed' in healed_candidatesnaive 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]
from typing import Literal
import outlines
from outlines import Generator
from pydantic import BaseModel, ConfigDict
from transformers import AutoModelForCausalLM, AutoTokenizer
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 KV cache across shared system prompts and schema prefixes (cutting Time To First Token) 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 ; with overlap, sampling waits only for .
Deep dive: Serving backend APIs and schema-compiler quirks
- Outlines backends: Supports
outlines_core,llguidance, and XGrammar with different coverage; benchmark cold compilation and warm per-token latency separately.[13] - llama.cpp (GBNF): Converts JSON Schema into GBNF grammars.[14][3] Unsupported keywords can be dropped quietly, and
llama.cppdoes not inject the schema into your prompt automatically, so describe required fields in the prompt and keep local Pydantic validation.[3] - SGLang and vLLM: SGLang defaults to XGrammar alongside Outlines and
llguidance.[11] vLLM configures constrained decoding throughstructured_outputsbacked by XGrammar orllguidance, replacing legacy per-format flags (guided_json,guided_regex).[12]
What latency work belongs to prefix caching versus grammar state?
Answer
Prefix caching reuses prefill computation for a matching token prefix, reducing Time To First Token when cache entries hit. Grammar-state optimizations cut the per-step cost of finding legal next tokens. They optimize different stages of serving latency.
Function calling vs. structured outputs
Both tool definitions and structured extraction APIs use JSON Schema, yet they serve different host roles:
| Dimension | Function calling (tool use) | Structured outputs |
|---|---|---|
| Core purpose | Agent action selection and execution | Structured data extraction and transformation |
| Control flow | Model proposes a tool; host runs it and feeds back the observation | Terminal JSON record consumed directly by application code |
| Return format | Tool name plus JSON argument object | JSON document matching the response schema |
| Side effects | Host validates permissions before executing the tool | Host 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:
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(),
}
valid_call = GetEvalStatusArgs.model_validate_json('{"eval_id": "eval-17"}')
print("tool:", tool_definition["name"], "strict:", tool_definition["strict"])
print("validated args:", valid_call.model_dump())
try:
GetEvalStatusArgs.model_validate_json('{"eval_id": "eval-17", "force_rerun": true}')
except ValidationError as error:
print("extra arg rejected:", error.errors()[0]["type"])tool: get_eval_status strict: True
validated args: {'eval_id': 'eval-17'}
extra arg rejected: extra_forbiddenStructured 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:
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})
print("required:", schema["required"])
print("closed object:", schema["additionalProperties"] is False)
print("nullable task:", update.failing_task)
try:
EvalStatusUpdate.model_validate({"eval_id": "eval-17", "status": "failed"})
except ValidationError:
print("omitted task: rejected")required: ['eval_id', 'status', 'failing_task']
closed object: True
nullable task: None
omitted task: rejectedAlways 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:
from copy import deepcopy
from pydantic import TypeAdapter
class RetrySuggestion(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
retry_count: int = Field(ge=0)
original_schema = RetrySuggestion.model_json_schema()
wire_schema = deepcopy(original_schema)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)print("local minimum:", original_schema["properties"]["retry_count"]["minimum"])
print("wire minimum present:", "minimum" in wire_schema["properties"]["retry_count"])
print("candidate fits wire integer shape:", wire_int == -1)
try:
RetrySuggestion.model_validate(candidate)
except ValidationError as error:
print("local rejection:", error.errors()[0]["type"])local minimum: 0
wire minimum present: False
candidate fits wire integer shape: True
local rejection: greater_than_equalWhen 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:
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"
parsed = TriageRecord.model_validate({"eval_id": "eval-17", "status": "failed"})
print("format check:", parsed.model_dump())
print("authorized and true:", decide_update({"nlp-eval"}, parsed))
print("other suite:", decide_update({"vision-eval"}, parsed))
false_claim = TriageRecord.model_validate({"eval_id": "eval-17", "status": "passed"})
print("authorized but false:", decide_update({"nlp-eval"}, false_claim))format check: {'eval_id': 'eval-17', 'status': 'failed'}
authorized and true: show
other suite: deny
authorized but false: review: contradicts eval logfalse_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
| Bottleneck | Underlying cause | Serving impact | Mitigation |
|---|---|---|---|
| Schema compilation | Building a grammar and tokenizer index | Higher cold-start TTFT | Reuse compiled artifacts; measure cold and warm distributions separately |
| Per-token grammar work | Advancing parser state and applying the mask | Adds to TPOT unless overlapped with GPU | Benchmark on your backend at realistic batch sizes |
| Schema prompt overhead | Field descriptions and injected schema text | Extra prefill tokens | Measure prompt token counts and prefix-cache hit rates |
| Grammar complexity | Deep nesting, wide unions, optional branches | Larger state tables or dropped keywords | Profile 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.
import re
SOURCE_LOG = "Evaluation eval-17 failed on math-500 after symbolic-verifier timed out."
class EvalDecision(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
evidence_quote: str = Field(min_length=1)
eval_id: str = Field(min_length=1)
decision: Literal["rerun_suite", "halt_release", "needs_review", "unknown"]
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
decision = verify_evidence_span(
{"evidence_quote": SOURCE_LOG, "eval_id": "eval-17", "decision": "rerun_suite"},
SOURCE_LOG,
)
print("decision:", decision.decision, "| quote in source:", decision.evidence_quote in SOURCE_LOG)
try:
verify_evidence_span({**decision.model_dump(), "evidence_quote": "eval-17 needs a release halt."}, SOURCE_LOG)
except ValueError as error:
print("invented quote:", error)
# A verbatim quote still does not verify that halt_release is justified by rules.
unsupported = verify_evidence_span({**decision.model_dump(), "decision": "halt_release"}, SOURCE_LOG)
print("true quote with wrong action accepted by quote check:", unsupported.decision)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_releaseFlattening 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:
from dataclasses import dataclass
@dataclass(frozen=True)
class FlatNode:
node_id: str
parent_id: str | None
label: str
nodes = [
FlatNode("root", None, "eval_run"),
FlatNode("n1", "root", "failing_task"),
FlatNode("n2", "root", "trace_uri"),
]
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
root_id, children = validate_tree(nodes)
print("root ID:", root_id, "| child IDs:", children[root_id])
cyclic = [nodes[0], FlatNode("a", "b", "task"), FlatNode("b", "a", "trace")]
try:
validate_tree(cyclic)
except ValueError as error:
print("invalid tree:", error)root ID: root | child IDs: ['n1', 'n2']
invalid tree: disconnected nodes or cycles presentEvery 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.
Legal prefixes that never finish
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:

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.- Completed candidate: Decode strictly, validate with local Pydantic, and verify source facts and caller permissions.
- 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 signalsstatus: "incomplete"withincomplete_details.reason: "max_output_tokens".)[15] - Refusal or content-filter stop: Halt automatic retries immediately and return a safe refusal.
- Unsupported or invalid schema: Fix the schema or SDK adapter in code; retrying identical input fails identically.
- 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.
FORMAT = {"type": "json_schema", "name": "eval_status", "strict": True, "schema": schema}
class StubResponseClient:
def __init__(self, responses):
self.responses = iter(responses)
self.calls = []
def create(self, **kwargs):
self.calls.append(kwargs)
return next(self.responses)
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")
generated_payload = {"eval_id": "eval-17", "status": "failed", "failing_task": "math-500"}
incomplete = {"status": "incomplete", "output": [], "incomplete_details": {"reason": "max_output_tokens"}}
completed = {"status": "completed", "output": [{"type": "message", "status": "completed",
"content": [{"type": "output_text", "text": json.dumps(generated_payload)}]}]}
client = StubResponseClient([incomplete, completed])
update = extract_with_single_retry(client, SOURCE_LOG)
print("retry preserved schema:", update.model_dump())
print("budgets:", [call["max_output_tokens"] for call in client.calls])
assert client.calls[0]["text"] == client.calls[1]["text"]
refused = {"status": "completed", "output": [{"type": "reasoning", "summary": []},
{"type": "message", "status": "completed", "content": [{"type": "refusal", "refusal": "blocked"}]}]}
filtered = {"status": "incomplete", "output": [], "incomplete_details": {"reason": "content_filter"}}
for label, responses in (("refusal routed", [refused]), ("content filter", [filtered]),
("second length stop", [incomplete, incomplete])):
stopped = StubResponseClient(responses)
try:
extract_with_single_retry(stopped, SOURCE_LOG)
except RuntimeError as error:
print(f"{label}: {error}; calls={len(stopped.calls)}")
assert len(stopped.calls) == len(responses)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=2Never 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:
from dataclasses import dataclass
@dataclass(frozen=True)
class ModelEvalProposal:
eval_id: str
action: str
approved: bool # Untrusted model output; never read for authorization
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"
proposal = ModelEvalProposal("eval-17", "rerun_suite", approved=True)
print(check_approval(proposal, stored_request=None))
print(check_approval(proposal, stored_request=("eval-19", "rerun_suite")))
print(check_approval(proposal, stored_request=("eval-17", "rerun_suite")))deny: missing approval for this request
deny: missing approval for this request
approval matched; continue host checksPractice: 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:
- Return
{"mentions": [{"suite": "...", "status": "passed|degraded|failed|unknown"}, ...]}under strict structured outputs. - Represent zero suite mentions as
{"mentions": []}, nevernullor a missing key. - 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.
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
KNOWN_SUITES = {"math-500", "humaneval-plus", "mmlu-pro"}
class SuiteMention(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
suite: str = Field(min_length=1)
status: Literal["passed", "degraded", "failed", "unknown"]
class BenchmarkDigest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
mentions: list[SuiteMention]
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)
digest = BenchmarkDigest.model_validate({
"mentions": [
{"suite": "math-500", "status": "passed"},
{"suite": "humaneval-plus", "status": "degraded"},
{"suite": "gpqa-diamond", "status": "unknown"},
]
})
empty = BenchmarkDigest.model_validate({"mentions": []})
check_unique_suites(digest)
print("mentions:", len(digest.mentions), "| unknown suites:", unknown_suites(digest))
print("empty mentions:", empty.mentions)
conflicting = BenchmarkDigest.model_validate({
"mentions": [
{"suite": "math-500", "status": "passed"},
{"suite": "math-500", "status": "failed"},
]
})
print("tempting dict conversion:", {m.suite: m.status for m in conflicting.mentions})
try:
check_unique_suites(conflicting)
except ValueError as error:
print("identity check:", error)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
- Grammar-guided decoding masks illegal tokens before softmax to enforce syntax and supported schema rules at token generation time.
- Strict JSON parsing and local Pydantic models catch duplicate keys, nonfinite numbers, and numeric bounds stripped by wire adapters.
- Host verification compares extracted claims against trusted stores and derives access decisions exclusively from authenticated application state.
- Stop-reason recovery retries a single token-limit cutoff when budgets allow while halting on refusals and fixing bad schemas in code.