AS·167
Structured Outputs
Getting machine-readable, type-safe results from a model that produces text: why free text breaks integrations, JSON and its pitfalls, JSON Schema (types, required, enums, formats, nesting, descriptions, additionalProperties, unions) as the contract, typed outputs generated from Pydantic, Zod, Java records, Go structs and Rust serde types, the three levels of enforcement (prompting, provider JSON modes and strict schema modes, local constrained decoding), how constrained decoding works with token masks over a grammar (implemented on a toy vocabulary), semantic validation beyond the schema, repair and retry loops with error feedback, streaming partial objects, schema design that helps models (field order, reasoning fields, nullable vs optional, enums, avoiding over-constraint), testing and monitoring, with runnable Python and equivalents in Java (Spring AI), TypeScript, Go and Rust.
Start here: answers a program can read
A person can read "Sure! The refund is ₹450, approved, I think." A program can't. When a model's output feeds code (to store a record, call an API, show a form), you need structured output: text in a fixed, machine-readable shape, usually JSON that matches a schema.
{"answer": "a set of reusable database connections", "confidence": 8}
Three levels of enforcement
| Level | How | Guarantee |
|---|---|---|
| ask | describe the format in the prompt, give examples | none: the model may still drift |
| validate | parse and check the output against the schema; on failure, retry with the error message | correct when it passes, but costs retries |
| constrain | at each generation step, allow only tokens that keep the output valid | always matches the grammar |
Constrained decoding in one picture
At every step a model scores all possible next tokens. Constrained decoding masks out every token that would break the format, then picks among the rest. After {"answer": "a set, a } is impossible (the string isn't closed), so it is removed from the candidates.
The lab tried this on the tiny GPT from Volume 14, which has never seen JSON in this format:
| Method | Valid output |
|---|---|
| instructions only | 0% |
| instructions plus two examples | 0% |
| examples plus up to 5 validate-and-retry attempts | 0% |
| constrained decoding | 100% |
But look at what it produced: {"answer": "file", "confidence": 2}. Perfectly shaped, and meaningless. Structure guarantees the shape, not the truth; you still validate values (ranges, allowed options) and evaluate correctness.
How deep to go in structured outputs
Volume 17 defines six mastery levels; for structured outputs they look like this:
| Level | You can… |
|---|---|
| L1 | explain why structure matters and what a schema is |
| L2 | get validated, typed objects from a model API with retries |
| L3 | explain constrained decoding, grammars and tokenizer interactions |
| L4 | debug truncation, escaping, schema-induced quality loss and streaming parse errors |
| L5 | design schemas and contracts that models fill well and systems can evolve |
| L6 | operate structured-output pipelines with monitoring of validity, repairs and drift |
Why structure
An LLM application rarely ends at text for a human. It feeds databases, APIs, UIs and other programs: extracting invoice fields, classifying tickets, producing a plan of tool calls, returning UI components. Free text invites failure:
- "Sure! Here's the JSON you asked for:" followed by the object wrapped in a Markdown code fence (extra prose and fences).
- Missing or renamed keys, wrong types ("total": "48,000.00"), invalid enum values ("Urgent!!" instead of "high").
- Truncated output at max tokens: unterminated JSON (chapter 157).
- Plausible but wrong values (a hallucinated date), which no parser catches.
Structured outputs turn the model's response into a typed object you can trust to have the right shape, then you validate its meaning.
JSON and JSON Schema
JSON is the lingua franca: objects, arrays, strings, numbers, booleans, null. Pitfalls: no comments, no trailing commas, numbers have no precision guarantees across languages (keep money as integer minor units or strings), no date type (use ISO 8601 strings).
JSON Schema (draft 2020-12 is current) describes the allowed shape:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Invoice",
"type": "object",
"properties": {
"invoice_number": {"type": "string", "description": "As printed, e.g. INV-2291"},
"vendor": {"type": "string"},
"issue_date": {"type": "string", "format": "date", "description": "ISO 8601 YYYY-MM-DD"},
"currency": {"type": "string", "enum": ["INR", "USD", "EUR", "GBP"]},
"total_minor": {"type": "integer", "minimum": 0, "description": "Total in minor units (paise, cents)"},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"quantity": {"type": "number", "exclusiveMinimum": 0},
"unit_price_minor": {"type": "integer", "minimum": 0}
},
"required": ["description", "quantity", "unit_price_minor"],
"additionalProperties": false
}
},
"due_date": {"type": ["string", "null"], "format": "date"}
},
"required": ["invoice_number", "vendor", "issue_date", "currency", "total_minor", "line_items", "due_date"],
"additionalProperties": false
}
Key features: type, properties, required, enum/const, items, minimum/maximum, minLength/maxLength, pattern, format, anyOf/oneOf (unions), $ref/$defs (reuse, recursion), additionalProperties: false (reject unknown keys), and description, which models read as instructions. Provider strict modes support a subset of JSON Schema (for example, often requiring every property to be listed in required with nullability expressed as a null type, and additionalProperties: false); check the provider's documented limitations.
Typed outputs: define once in your language
Write the type in your language and generate the schema from it, so the schema, the parser and the code that uses the object never drift apart.
from datetime import date
from enum import Enum
from typing import Literal
from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator
class Priority(str, Enum):
low = "low"; medium = "medium"; high = "high"
class LineItem(BaseModel):
description: str
quantity: float = Field(gt=0)
unit_price_minor: int = Field(ge=0)
class Invoice(BaseModel):
invoice_number: str = Field(pattern=r"^[A-Z]{2,5}-\d+$", description="As printed, e.g. INV-2291")
vendor: str
issue_date: date
currency: Literal["INR", "USD", "EUR", "GBP"]
total_minor: int = Field(ge=0, description="Total in minor units")
line_items: list[LineItem]
due_date: date | None = Field(description="null if not printed")
@model_validator(mode="after")
def totals_match(self): # semantic check beyond the schema
s = round(sum(li.quantity * li.unit_price_minor for li in self.line_items))
if self.line_items and s != self.total_minor:
raise ValueError(f"line items sum to {s} but total_minor is {self.total_minor}")
if self.due_date and self.due_date < self.issue_date:
raise ValueError("due_date is before issue_date")
return self
schema = Invoice.model_json_schema() # JSON Schema to send to the model / provider
sorted(schema["properties"]), schema["required"][:3]
// TypeScript: Zod schemas → JSON Schema and runtime validation
import { z } from "zod";
const LineItem = z.object({ description: z.string(), quantity: z.number().positive(), unit_price_minor: z.number().int().min(0) });
const Invoice = z.object({
invoice_number: z.string().regex(/^[A-Z]{2,5}-\d+$/),
vendor: z.string(),
issue_date: z.iso.date(),
currency: z.enum(["INR", "USD", "EUR", "GBP"]),
total_minor: z.number().int().min(0),
line_items: z.array(LineItem),
due_date: z.iso.date().nullable(),
});
type Invoice = z.infer<typeof Invoice>;
const jsonSchema = z.toJSONSchema(Invoice);
const parsed = Invoice.safeParse(JSON.parse(modelText)); // { success, data | error }
// Java: records + Spring AI — schema generated from the type, response mapped back to it
record LineItem(String description, double quantity, long unitPriceMinor) {}
record Invoice(String invoiceNumber, String vendor, LocalDate issueDate, String currency,
long totalMinor, List<LineItem> lineItems, LocalDate dueDate) {}
Invoice invoice = chatClient.prompt()
.system("Extract the invoice. Use null for fields not printed.")
.user(documentText)
.call()
.entity(Invoice.class); // BeanOutputConverter: JSON Schema in the prompt/request, Jackson to parse
// Go: struct tags + a JSON Schema generator (e.g. invopop/jsonschema); encoding/json to decode
type LineItem struct {
Description string `json:"description"`
Quantity float64 `json:"quantity" jsonschema:"exclusiveMinimum=0"`
UnitPriceMinor int64 `json:"unit_price_minor" jsonschema:"minimum=0"`
}
type Invoice struct {
InvoiceNumber string `json:"invoice_number" jsonschema:"pattern=^[A-Z]{2,5}-\\d+$"`
Currency string `json:"currency" jsonschema:"enum=INR,enum=USD,enum=EUR,enum=GBP"`
TotalMinor int64 `json:"total_minor"`
LineItems []LineItem `json:"line_items"`
DueDate *string `json:"due_date"` // nullable
}
schema := jsonschema.Reflect(&Invoice{})
dec := json.NewDecoder(strings.NewReader(modelText)); dec.DisallowUnknownFields()
var inv Invoice
err := dec.Decode(&inv)
// Rust: serde for (de)serialisation, schemars for JSON Schema
#[derive(Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct Invoice {
invoice_number: String,
currency: Currency, // enum → JSON Schema enum
total_minor: u64,
line_items: Vec<LineItem>,
due_date: Option<String>, // nullable
}
let schema = schemars::schema_for!(Invoice);
let inv: Invoice = serde_json::from_str(&model_text)?; // type errors surface as Result::Err
Three levels of enforcement
| Level | How | Guarantee |
|---|---|---|
| 1. Prompting | Describe the format, show an example, ask for JSON only | None: usually works with strong models; fails occasionally |
| 2. Provider structured-output modes | "JSON mode" (valid JSON, any shape) or strict schema mode (output conforms to your JSON Schema), and strict tool/function schemas | Syntactic validity and schema conformance (within supported features); not semantic correctness |
| 3. Local constrained decoding | Your inference engine masks invalid tokens using a grammar compiled from the schema, regex or CFG (Outlines, XGrammar, llguidance, llama.cpp GBNF; built into vLLM and SGLang) | Every generated token keeps the output valid; any grammar you can express |
Even with levels 2–3, always validate (truncation, refusals, semantic errors, provider feature gaps) and handle failures.
How constrained decoding works
At each step the engine knows which tokens can legally come next given the text so far and the grammar. It sets the logits of all other tokens to −∞ before sampling (chapter 157), so the model can only choose valid continuations. The grammar is compiled into an automaton over characters, and then mapped onto the tokenizer's vocabulary: a token is allowed if its characters keep the automaton in a live state. Efficient engines precompute per-state token masks and handle the many tokens that span grammar boundaries.
import numpy as np
def allowed_tokens(prefix, options, vocab):
"""Tokens t such that prefix + t is a prefix of some option (or completes one then closes)."""
ok = []
for i, t in enumerate(vocab):
s = prefix + t
if any(opt.startswith(s) for opt in options) or any(s == opt + '"' for opt in options):
ok.append(i)
return ok
def constrained_enum(logit_fn, options, vocab, max_steps=10):
out = ""
for _ in range(max_steps):
logits = logit_fn(out).copy()
mask = np.full(len(vocab), -np.inf); mask[allowed_tokens(out, options, vocab)] = 0
tok = vocab[int(np.argmax(logits + mask))]
out += tok
if out.endswith('"'): return out[:-1]
raise RuntimeError("no valid completion")
vocab = ["urgent", "high", "med", "ium", "lo", "w", '"', "banana", "h", "igh"]
def fake_model(prefix): # a model that would love to say "urgent"
prefs = {"": {"urgent": 5, "high": 4, "med": 3, "lo": 2}, "med": {"ium": 5}, "lo": {"w": 5}}
base = np.full(len(vocab), -5.0)
for t, v in prefs.get(prefix, {}).items(): base[vocab.index(t)] = v
base[vocab.index('"')] = 1.0
return base
constrained_enum(fake_model, ["low", "medium", "high"], vocab) # 'high' — 'urgent' was never possible
Caveats: constraining can push a model into unnatural token sequences (lower quality) if the grammar fights its preferences; keep schemas natural, describe fields, and give the model room (e.g. a reasoning field before the answer).
Validation, repair and retries
The schema guarantees shape; your code must check meaning:
- Cross-field rules (totals add up, end ≥ start), referential checks (customer id exists), business rules, ranges, plausibility (a date in 1899?).
- Grounding checks: extracted values actually appear in the source document (cheap string search catches many hallucinations).
- Refusals and truncation: the model may refuse or stop at max tokens; check the finish reason (chapter 157).
When validation fails:
- Deterministic repair first: strip code fences, extract the first
{…}block, fix trailing commas, coerce "48,000" → 48000 when unambiguous (libraries such as json-repair). Log every repair. - Retry with feedback: send the validation errors back ("
total_minor: line items sum to 46000 but total is 48000; re-check the document") and ask for a corrected object. Usually one retry suffices. - Escalate: a stronger model, a human review queue, or a safe default; never silently accept invalid data.
- Bound it: max attempts, total timeout, and metrics on failure rates.
import json, re
def extract_json(text):
"""Deterministic repair: strip fences and surrounding prose."""
text = re.sub(r"^`{3}(?:json)?\s*|\s*`{3}$", "", text.strip(), flags=re.M) # code fences
m = re.search(r"\{.*\}", text, flags=re.S)
if not m: raise ValueError("no JSON object found")
return json.loads(m.group(0))
def structured_call(llm, prompt, model_cls, max_attempts=3):
messages = [{"role": "user", "content": prompt}]
errors = []
for attempt in range(1, max_attempts + 1):
text = llm(messages)
try:
return model_cls.model_validate(extract_json(text)), attempt
except (ValueError, ValidationError) as e:
err = str(e)[:800]; errors.append(err)
messages += [{"role": "assistant", "content": text},
{"role": "user", "content": f"That output was invalid:\n{err}\nReturn only the corrected JSON object."}]
raise RuntimeError(f"structured output failed after {max_attempts} attempts: {errors[-1]}")
FENCE = "`" * 3
def reply(unit_price): # a fake model: first wraps JSON in prose + fences, with a wrong price
obj = {"invoice_number": "INV-2291", "vendor": "Acme", "issue_date": "2026-10-03", "currency": "INR",
"total_minor": 4800000, "line_items": [{"description": "Licences", "quantity": 4,
"unit_price_minor": unit_price}], "due_date": None}
return json.dumps(obj)
replies = iter([f"Here you go:\n{FENCE}json\n{reply(1150000)}\n{FENCE}", reply(1200000)])
invoice, attempts = structured_call(lambda msgs: next(replies), "Extract the invoice...", Invoice)
attempts, invoice.total_minor # (2, 4800000): first reply failed the totals check, second passed
Streaming structured output
Users don't want to wait for a whole object. Options: stream partial JSON and parse incrementally (partial-JSON parsers, or provider/SDK support for partial objects) to render fields as they arrive; stream arrays of items as newline-delimited JSON; or stream text for humans and produce the structured object in a separate call. Validate the final object before acting on it.
Designing schemas that models fill well
- Name and describe fields clearly; descriptions are instructions ("ISO 8601 date; null if not printed").
- Field order matters: models generate left to right. Put a short
reasoningorevidencefield before the decision field when the decision needs thought (and drop it before storage), or use a reasoning model and keep the schema lean. - Prefer enums for categorical values; include an explicit
"other"or"unknown"option rather than forcing a wrong choice. - Nullable, not missing: require every key and allow
nullfor "not present", so absence is explicit. - Flat over deeply nested; split very large extractions into several calls (per section, per entity type).
- Units and formats in the schema: minor units for money, ISO dates, normalised country codes.
- Don't over-constrain: overly tight regexes or tiny
maxLengthvalues push the model into bad outputs; validate semantics in code instead. - Version schemas like APIs; consumers depend on them.
Testing and monitoring
- Unit-test validators with valid and invalid fixtures.
- Evaluation sets with expected objects: field-level accuracy (exact match, normalised match, numeric tolerance), schema-validity rate, retry rate, end-to-end latency and cost (chapter 175).
- Production metrics: validation failure rate by field and model version, repair and retry counts, escalations; alert on spikes after model or prompt changes (chapter 177).
Lab: constrained decoding with a tiny GPT
Setup. Chapter 156's 2 M-parameter GPT (trained on prose, never on this JSON format), its 2,048-token byte-level BPE tokenizer, PyTorch on 2 CPU threads, and Pydantic 2.13 for validation. Schema: {"answer": <string, 1–60 characters, no quotes, backslashes or newlines>, "confidence": <integer 0–9>}. Sampling at temperature 0.8, 40 answers per method across five questions, up to 100 tokens each. Scope: a tiny model makes the effect of each enforcement level stark; capable models usually follow formats from instructions alone most of the time, which is exactly why the residual failures are easy to miss.
Experiment 1: four ways to get JSON
| Method | Parses as JSON | Passes the schema | ms / answer |
|---|---|---|---|
| zero-shot instructions, unconstrained | 0.03 | 0.00 | 481 |
| two examples (few-shot), unconstrained | 0.03 | 0.00 | 433 |
| few-shot + validate-and-retry, up to 1 / 3 / 5 attempts | — | 0.00 / 0.00 / 0.00 | — |
| few-shot, constrained | 1.00 | 1.00 | 267 |
| zero-shot, constrained | 1.00 | 1.00 | 186 |
unconstrained: " byte level than a view is warder have just the page's JIT termin; the hopalk..."
constrained: {"answer": "file", "confidence": 2} {"answer": "-11", "confidence": 0}
- Without constraints the model never produced the format; with a mask it always did, even with no examples. The constrained runs were faster per answer only because they stopped as soon as the object closed, while unconstrained text ran to the token limit.
- Retries multiply the chance of success only if each attempt has a reasonable chance; at 0% per attempt, five attempts still give 0%. With a model that's valid 95% of the time, three attempts give 99.99%, at the cost of extra latency on the failures.
- The constrained answers are well-formed nonsense. Structure is a contract about shape.
Experiment 2: how the mask is built
At each step the lab tested every one of the 2,048 tokens: "if I append this token's text, is the output still a prefix of some valid object?" Disallowed tokens get a score of −∞ before sampling. Two bugs appeared while building it, both instructive:
- The first version let
}follow"confidence":with no digit, after which nothing else was valid either, and the model wandered on for 200 tokens. A grammar must never allow a state it can't complete. - Byte-level BPE has tokens that are parts of multi-byte characters (alone, they decode to the replacement character U+FFFD). A text-level check can't judge them; the fix here was to exclude them, which forbids non-ASCII answers. Production libraries (llguidance, XGrammar, Outlines) work at the byte level and precompile the grammar against the vocabulary, so the mask costs microseconds rather than this lab's Python loop over every token.
Experiment 3: what the validator adds
Grammars handle syntax; validators handle meaning:
{"answer": "x", "confidence": 12} -> Input should be less than or equal to 9
{"answer": "", "confidence": 3} -> String should have at least 1 character
{"answer": "a queue", "confidence": "high"} -> Input should be a valid integer, unable to parse string as an integer
{"answer": "a queue", "confidence": 7} -> ok
Range and length rules could be compiled into the grammar (this lab's grammar did so, so these errors couldn't occur under constraint), but cross-field rules, lookups and business logic belong in validation code. Use both: constrain to the schema, validate the result, and send precise error messages back on retry.
Try it yourself
- Extend the grammar to an array of 1–3 answers and keep it always completable.
- Measure how often the unconstrained few-shot model produces a prefix of valid JSON and where it first goes wrong.
- With any capable model you can access, measure validity over 500 calls with and without the provider's structured-output mode.
- Force the
answerfield to come after areasoningfield and compare answer quality on a task you can score.
Revision sheet: structured outputs
Key ideas
- Structured output turns model text into data your code can trust: JSON matching a JSON Schema, generated from typed definitions (Pydantic, Zod).
- Three levels: prompt (no guarantee), validate + repair/retry (guarantee on success), constrained decoding (guaranteed syntax).
- Constrained decoding masks invalid tokens using a grammar compiled against the tokenizer; must handle partial-token and byte-level issues.
- Validation still needed for semantics: ranges, cross-field rules, references, business logic.
- Schema design: clear names and descriptions, enums over free text, explicit nulls/"unknown", flat over deeply nested, order fields so reasoning precedes conclusions if needed.
- Streaming structured output needs incremental parsers.
- Monitor validity rate, repair rate, retry latency, refusals and field-level accuracy.
Numbers to remember
- Lab: tiny GPT valid JSON 0% unconstrained (even with 5 retries) → 100% constrained.
- Retries: with per-attempt success p, k attempts succeed with 1 − (1 − p)^k.
Pitfalls
- Treating "valid JSON" as "correct answer".
- Grammars that can reach dead states, or that cut answers off at length limits silently.
- Overly complex schemas that degrade answer quality.
- Not giving the model a way to say "unknown".
- Silent coercion (e.g. "7" → 7) hiding real errors.
Glossary
- JSON Schema: a vocabulary for describing JSON structure and constraints.
- Constrained (guided) decoding: masking tokens to satisfy a grammar.
- Logit mask: setting disallowed tokens' scores to −∞.
- Repair: fixing malformed output, by code or by re-prompting with errors.
- Typed output: parsing model output directly into a language type.