WORKINGCHAPTER 09

Structured output and schema enforcement

Free text is a format your code cannot read. Constrain the shape, validate the meaning, repair what fails, and measure both

50 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

An extractor that asks for JSON in the prompt produces valid, schema-conforming output 94% of the time, and 88% of outputs have every field correct. You switch on schema-constrained decoding. Validity goes to 100%. What happens to the share with every field correct?

A model emits tokens. Your code wants a typed object. The distance between the two is where most production failures in LLM applications live: not wrong answers, but right answers in a shape the next function cannot read. This chapter closes that distance in three layers. First, constrain the output so it is always parseable and always has your fields. Second, validate the meaning with code you control. Third, when validation fails, feed the error back and let the model repair it. Then you measure validity and accuracy separately, because a pipeline that never throws can still be wrong.

Why free text breaks downstream code

A prompt that says “reply with JSON only” works most of the time with a capable model. Most of the time is the problem. At 10,000 calls a day, 99% compliance is 100 failures a day, and the failures are not random. They cluster on the inputs that were already unusual: the angry customer who pasted three orders, the message in Portuguese, the one with no order number at all. Those are the tickets you most need to handle.

The failures come in a small number of families, and it pays to know them by name:

  • Wrapper text. “Here is the extracted data:” before the brace, or a Markdown code fence around it. The JSON inside is fine; json.loads still throws.
  • Shape drift. A key renamed (orderId instead of order_id), a list where you expected a single object, a number serialised as a string with a thousands separator.
  • Vocabulary drift. An enum value that is not in your list: “billing_issue”, “Damaged”, “wrong item”.
  • Truncation. The response hits max_tokens halfway through an array. The stop reason says so, but code that only looks at the text sees a syntax error.
  • Honest absence rendered as invention. No order id in the message, so the model writes 0, or "unknown", or a plausible-looking number.

The first four are formatting failures, and you can remove them almost completely. The fifth is a meaning failure, and no format constraint touches it. Keep those two categories apart; the rest of the chapter treats them differently.

Four ways to get JSON out of a model

Approach What it guarantees What it does not Where you meet it
Prompt only: “reply with JSON” Nothing. Compliance is statistical. Syntax, keys, types, enums Every model, including the smallest local ones
JSON mode Syntactically valid JSON Your keys, your types, your enum values Ollama format="json", several hosted APIs
Schema-constrained decoding Output parses and matches your JSON Schema That the values are true Anthropic output_config.format, Ollama format=<schema>, Outlines, llama.cpp grammars
Tool call as schema The tool’s input matches its input_schema (with strict: true) That the model calls the tool at all, unless forced Anthropic strict: true tools; the older trick before native structured outputs

Prompt-only is what you start with and what a surprising number of production systems still run. JSON mode is a half-measure: it ends the parse errors and leaves every other failure in place, which makes them harder to see because nothing throws until a KeyError three functions later.

Schema-constrained decoding is the real fix for formatting failures, so it is worth knowing how it works.

How constrained decoding works

At each step the model produces a probability for every token in its vocabulary, typically 100,000 to 200,000 entries. Normal sampling picks from that distribution. Constrained decoding inserts one step before the pick: it asks a parser which tokens are legal next, given everything generated so far and the grammar, and sets the probability of every illegal token to zero.

Your JSON Schema is compiled into that grammar. After {"issue": " the only legal continuations are the first characters of late, damaged, wrong_item, refund or other. After "qty": only digits are legal. When the object’s required keys have all been written, the only legal token is }. The model cannot produce a preamble because the grammar’s first legal character is {.

Willard and Louf’s 2023 paper made this fast by compiling the grammar into a finite-state machine and precomputing, for each state, which vocabulary tokens are allowed, so the per-token cost is a table lookup rather than a parse. That precomputation is why the first request with a new schema is slower. Anthropic’s documentation says the first use of a schema pays a grammar compilation cost, and compiled grammars are cached for 24 hours from last use; changing the schema’s structure invalidates the cache, while changing only name or description fields does not. Budget for a slow first call after every schema deploy, and do not generate schemas dynamically per request.

The grammar can express structure. It cannot express arithmetic. Anthropic’s structured outputs do not support numeric bounds (minimum, maximum, multipleOf), string length limits (minLength, maxLength), recursive schemas, external $ref, or array minItems above 1. Simple regex pattern values work; backreferences, lookaround and \b do not. Every object needs additionalProperties: false, and a schema that uses an unsupported feature gets a 400 with details. One more surprise from the docs: the grammar does not guarantee the capitalisation of string enum and const values, so compare enum values case-insensitively or normalise them in your validator.

Constraining the output distribution has a cost. Tam et al. (2024) found that forcing JSON or XML output measurably degrades performance on reasoning tasks, with stricter formats hurting more. For extraction, where the answer is in the input, the effect is small. For a task where the model has to work something out, let it reason first (Claude’s thinking happens before the constrained text block) or split the job: reason in free text, then extract the conclusion into a schema in a second call.

Structured outputs on the Anthropic API

On the Claude API the feature is output_config.format, it needs no beta header, and current models support it. The older output_format request parameter is deprecated. The Python SDK’s messages.parse takes a Pydantic model, builds the schema, sends it, and validates the response into an instance:

import anthropic
from typing import Literal
from pydantic import BaseModel

class Ticket(BaseModel):
    order_id: int | None
    issue: Literal["late", "damaged", "wrong_item", "refund", "other"]

client = anthropic.Anthropic()
r = client.messages.parse(
    model="claude-opus-5-5",
    max_tokens=4000,
    output_config={"effort": "low"},          # merged with the format the SDK builds
    output_format=Ticket,
    messages=[{"role": "user", "content": "Extract the ticket: my order 1182733 came smashed"}],
)
if r.stop_reason != "end_turn":
    raise RuntimeError(f"incomplete: {r.stop_reason}")   # max_tokens or refusal
print(r.parsed_output)   # Ticket(order_id=1182733, issue='damaged')

Two stop reasons break the guarantee. With max_tokens, the output was cut off and may not parse; raise the limit and retry. With refusal, the model declined and the refusal takes precedence over the schema. Check stop_reason before you trust the text. On Claude Opus 5.5, thinking is always on and the response starts with a thinking block, so code that reads content[0].text breaks; find the block whose type is text. For extraction, effort: "low" keeps the thinking short and the bill small.

If you want the raw text and your own validation, which the lab does so it can count failures, send the schema yourself:

schema = anthropic.transform_schema(Ticket.model_json_schema())
r = client.messages.create(model="claude-opus-5-5", max_tokens=4000, messages=msgs,
    output_config={"effort": "low", "format": {"type": "json_schema", "schema": schema}})
text = next(b.text for b in r.content if b.type == "text")

The second route is strict tool use. Set strict: true on a tool definition and the tool’s input is guaranteed to match its input_schema; it uses the same grammar pipeline. Before native structured outputs, teams defined a fake tool called record_ticket and forced the model to call it with tool_choice, then read the arguments. That still works on models that accept forced tool use, but Claude Opus 5.5, Claude Sonnet 5.5 and Claude Fable 5.1 return a 400 for tool_choice of type any or tool. On those models, use output_config.format when you want a structured answer, and strict: true tools when you want structured actions. The next chapter is about the second.

Pydantic as the single source of truth

You need the schema in three places: in the request, in the validator, and in the type your downstream code uses. Write it once as a Pydantic model and derive the other two. Model.model_json_schema() produces the JSON Schema; Model.model_validate_json(text) parses and validates in one step and raises ValidationError with a list of every failing field; the instance is the typed object the rest of your code consumes.

Two details matter. First, a field typed int | None with no default is required and nullable. That is what you want for extraction: the model must decide, for every field, whether the value is present, and say null when it is not. A field with a default becomes optional, and the model learns it can leave it out.

Second, constraints the grammar cannot enforce do not disappear. When you write qty: int = Field(ge=1), the Anthropic SDK’s transform_schema strips minimum: 1 from the schema it sends (the API would reject it) and moves it into the field’s description as {minimum: 1}, so the model still reads the rule. Your Pydantic validator still enforces it. That means a schema-constrained response can still fail validation, and you need the repair loop below even with constraints on. Run print(anthropic.transform_schema(Order.model_json_schema())) once on any model you ship, and read what is actually sent.

Field descriptions are prompt. Field(description="Digits only; null if the message has none") reaches the model inside the schema and changes its behaviour as much as the same sentence in the system prompt would. Put the rule next to the field it governs.

Validation and the retry-with-error loop

When validation fails, the cheapest fix is often the model itself, given the error. The loop is short:

def extract(text, ask, repairs=2):
    messages = [{"role": "user", "content": PROMPT + text}]
    for attempt in range(repairs + 1):
        out, raw = ask(messages)
        try:
            return Order.model_validate_json(out)
        except ValidationError as e:
            messages += [{"role": "assistant", "content": raw},
                         {"role": "user", "content": f"That failed validation:\n{e}\nReply with corrected JSON only."}]
    return None

Three rules make it work. Append the model’s previous output verbatim, so it can see what it wrote; on Claude, append the whole content list including thinking blocks, and never edit earlier turns, because current models invalidate thinking from an edited history. Send Pydantic’s error text unchanged: it names the field, the value and the rule (issue: Input should be 'late', 'damaged', ...), which is exactly what the model needs. And cap the retries. One repair fixes most failures, a second fixes a few more, and a third almost never helps: an input that fails three times usually fails for a reason the model cannot fix, such as a message that contains no order at all. Send those to a dead-letter queue with the error and the raw text, and count them.

A repair costs a full extra call including the original input. If 5% of your inputs need one repair, your bill rises by about 5% plus the size of the error message. That is cheaper than losing the 5%, and much cheaper than retrying the same prompt from scratch, which tends to make the same mistake again because nothing about the input changed. Libraries such as Instructor package this loop (they call it reasking) around Pydantic for many providers; it is worth knowing what they do before you adopt one.

Partial and streaming JSON

A long structured response, such as fifty extracted line items, takes seconds to generate. If a user is watching, you want to show items as they arrive. Streaming gives you the text in chunks, and the chunks are not valid JSON until the last one. A partial parser solves it: pydantic_core.from_json(buffer, allow_partial=True) returns the longest valid prefix as Python objects, closing open arrays and dropping the incomplete trailing value.

from pydantic_core import from_json
buf = ""
with client.messages.stream(model="claude-opus-5-5", max_tokens=8000, messages=msgs,
                            output_config={"format": {"type": "json_schema", "schema": schema}}) as s:
    for chunk in s.text_stream:
        buf += chunk
        items = from_json(buf, allow_partial=True).get("items", [])
        render(items[:-1])        # the last item may still be growing
order = Order.model_validate_json(buf)   # validate the whole thing once, at the end

Render the complete items and hold back the last one, whose strings may still be growing. Validate only the final buffer. A partial object is a display aid, not data; never write it to a database.

Enums and the ‘other’ trap

Enums are where structured output looks most successful and fails most quietly. Without an escape value, a model facing a message that fits none of your categories has to pick a wrong one, and your router sends a shipping question to the refunds team. So you add other. Now every output is valid, and a new problem appears: other absorbs uncertainty. A model that is 55% sure a message is wrong_item may pick other instead. A new kind of complaint that you never anticipated, such as a product recall, lands there in volume and nothing alerts.

The fixes are measurement and design, not prompting:

  • Track the share of other as a metric. In a stable system it is a stable number. When it doubles, either your inputs changed or your model did, and both deserve a look.
  • Pair other with a free-text field such as issue_detail: str | None, so the records that land there carry the reason. Read a sample weekly; that is where your next enum value comes from.
  • Describe every value. A Literal type gives the model the names; a description per value (in the field description or the system prompt) gives it the boundaries. “damaged: arrived broken or defective. wrong_item: arrived intact but not what was ordered.”
  • Never remove a value without checking where its traffic goes. The lab’s break step does exactly this and shows the result.

Measuring validity rate

Measure two numbers on a labelled set, and keep them apart.

Validity rate: the share of inputs that produce an object your validator accepts, within your retry budget. Report it with and without repairs, so you know how much the loop is carrying. A drop in first-pass validity after a model or prompt change is an early warning even if repairs hide it from users.

Accuracy: the share of valid outputs whose fields match the labels. Report it per field as well as for the whole object, because the fields fail differently: enums fail on ambiguous inputs, ids fail on messages with several numbers in them, totals fail on European decimal commas.

Fifty labelled examples is enough to compare two configurations and catch a regression; it is not enough to quote a production error rate to two decimal places. Module three builds this into a proper evaluation set. For now, log every failure with its input, raw output and validation error. The failures are the dataset you will learn the most from.

LAB Fifty messy messages, three ways ~45 MIN
YOU NEEDPython 3.12 and uvan Anthropic API key in ANTHROPIC_API_KEYOllama with llama3.2:3b pulled (about 2 GB)about $0.50 to $1.00 of API credit

You will extract orders from 50 generated support messages, with known correct answers, using Claude without and with schema enforcement, then add a repair loop, then run the same job on a local 3B model through Ollama. Work in labs/ai/extract/, inside the labs/ai uv project from the first chapter’s lab.

Cost: the default model is claude-opus-5-5 at $4 per million input tokens and $20 per million output tokens. One extraction at effort: "low" is roughly 500 input and 200 output tokens, about half a cent, so each 50-message pass costs $0.20 to $0.30 and the whole lab under a dollar. MODEL=claude-haiku-5-5 ($0.10 in, $0.50 out) runs the same lab for a few cents if you want to compare.

1. Set up.

From the root of your checkout:

cd labs/ai && uv add anthropic pydantic ollama
mkdir -p extract && cd extract
ollama pull llama3.2:3b
uv adds whichever of the three packages labs/ai/pyproject.toml does not already have and installs them into labs/ai/.venv; Ollama prints success after the pull. If uv add says it cannot find Python 3.12, run uv python install 3.12 first.

2. Generate the messages. Create gen_messages.py. It writes 50 support messages with deliberately messy formatting, each with the correct extraction alongside it:

import json, random
random.seed(7)
SKUS = ["SKU-10042", "SKU-20417", "SKU-31008", "SKU-40991", "SKU-55120"]
ISSUES = {
    "late": ["where is my order??", "still not here after 2 weeks", "tracking hasnt moved since monday"],
    "damaged": ["arrived smashed", "box was crushed and the lid is cracked", "broken on arrival!!"],
    "wrong_item": ["you sent me the wrong thing", "this is not what i ordered", "got a blue one, ordered red"],
    "refund": ["i want my money back", "please refund me", "cancel it and refund pls"],
    "other": ["do you ship to norway", "can i change my delivery address", "is there a student discount"],
}
rows = []
for i in range(50):
    issue = random.choice(list(ISSUES))
    oid = random.randint(100000, 1999999) if random.random() > 0.15 else None
    email = f"user{random.randint(1, 500000)}@example.com" if random.random() > 0.3 else None
    items = [] if issue == "other" else [
        {"sku": random.choice(SKUS), "qty": random.randint(1, 3)} for _ in range(random.choice([1, 1, 2]))]
    total = round(random.uniform(9, 400), 2) if items and random.random() > 0.4 else None
    parts = [random.choice(ISSUES[issue])]
    if oid: parts.append(random.choice([f"order #{oid}", f"ord {oid}", f"order number {oid:,}"]))
    for it in items:
        parts.append(random.choice([f"{it['qty']}x {it['sku']}", f"{it['sku']} (qty {it['qty']})",
                                    f"{it['qty']} of {it['sku'].lower()}"]))
    if total: parts.append(random.choice([f"paid €{total}", f"{total} EUR", f"total was {str(total).replace('.', ',')}€"]))
    if email: parts.append(random.choice([f"reach me at {email}", f"- {email}", f"email: {email.upper()}"]))
    random.shuffle(parts)
    text = (" " if random.random() > 0.5 else "\n").join(parts)
    rows.append({"id": i, "text": text, "truth": {"order_id": oid, "customer_email": email,
                 "issue": issue, "items": items, "total_eur": total}})
with open("messages.jsonl", "w") as f:
    f.writelines(json.dumps(r) + "\n" for r in rows)
print(rows[3]["text"])
uv run gen_messages.py && wc -l messages.jsonl
One message printed over several lines (216.9 EUR, an email address, box was crushed and the lid is cracked, ord 1248703, 1 of sku-55120), then 50 messages.jsonl. The seed is fixed, so you get the same 50 messages as everyone else: 13 wrong_item, 12 late, 11 damaged, 7 refund and 7 other. Thousands separators, lower-case SKUs, decimal commas, upper-case emails and missing fields are all deliberate: they are the inputs that break naive parsing.

3. The extractor. Create extract.py. One file runs every configuration: backend (claude or ollama), mode (free for prompt-only or JSON mode, schema for constrained decoding), and a repair budget.

import json, os, sys
from typing import Literal
import anthropic, ollama
from pydantic import BaseModel, Field, ValidationError

MODEL = os.environ.get("MODEL", "claude-opus-5-5")
PRICE = {"claude-opus-5-5": (4.00, 20.00), "claude-haiku-5-5": (0.10, 0.50)}  # USD per 1M tokens: in, out
client = anthropic.Anthropic()
spent = 0.0
# Opus and Sonnet retry a classifier decline on a fallback model (the API chapter's rule);
# Haiku 5.5 has no server-side fallback
FALLBACK = {} if MODEL.startswith("claude-haiku") else {
    "betas": ["server-side-fallback-2026-07-01"], "fallbacks": "default"}

class Item(BaseModel):
    sku: str = Field(description="Product SKU in upper case, e.g. SKU-10042")
    qty: int = Field(ge=1)

class Order(BaseModel):
    order_id: int | None = Field(description="Digits only; null if the message has none")
    customer_email: str | None
    issue: Literal["late", "damaged", "wrong_item", "refund", "other"]
    items: list[Item]
    total_eur: float | None

SCHEMA = Order.model_json_schema()
PROMPT = """Extract the order from the support message below. Reply with JSON only, with keys
order_id, customer_email, issue (one of: late, damaged, wrong_item, refund, other),
items (a list of objects with sku and qty) and total_eur. Use null when a value is missing.

<message>
MSG
</message>"""

def ask_claude(messages, constrained):
    global spent
    config = {"effort": "low"}
    if constrained:
        config["format"] = {"type": "json_schema", "schema": anthropic.transform_schema(SCHEMA)}
    r = client.beta.messages.create(model=MODEL, max_tokens=4000, messages=messages, output_config=config,
                                    **FALLBACK)
    p_in, p_out = PRICE[MODEL]
    spent += (r.usage.input_tokens * p_in + r.usage.output_tokens * p_out) / 1e6
    # a refusal has no text: it fails validation and is counted, not crashed on
    return next((b.text for b in r.content if b.type == "text"), ""), r.content or "(declined)"

def ask_ollama(messages, constrained):
    r = ollama.chat(model="llama3.2:3b", messages=messages, options={"temperature": 0},
                    format=SCHEMA if constrained else "json")
    return r.message.content, r.message.content

def extract(text, ask, constrained, repairs):
    messages = [{"role": "user", "content": PROMPT.replace("MSG", text)}]
    err = None
    for attempt in range(repairs + 1):
        out, raw = ask(messages, constrained)
        try:
            return Order.model_validate_json(out), attempt, None
        except ValidationError as e:
            err = e
            messages += [{"role": "assistant", "content": raw},
                         {"role": "user", "content": f"That failed validation:\n{e}\nReply with corrected JSON only."}]
    return None, repairs, err

def correct(o, t):
    return (o.issue == t["issue"] and o.order_id == t["order_id"]
            and (o.customer_email or "").lower() == (t["customer_email"] or "")
            and sorted((i.sku.upper(), i.qty) for i in o.items) == sorted((i["sku"], i["qty"]) for i in t["items"])
            and abs((o.total_eur or 0) - (t["total_eur"] or 0)) < 0.01)

if __name__ == "__main__":
    backend, mode = sys.argv[1], sys.argv[2]
    repairs = int(sys.argv[3]) if len(sys.argv) > 3 else 0
    ask = ask_claude if backend == "claude" else ask_ollama
    rows = [json.loads(line) for line in open("messages.jsonl")]
    valid = right = repaired = other = 0
    for row in rows:
        o, attempts, err = extract(row["text"], ask, mode == "schema", repairs)
        if o is None:
            print(f"  #{row['id']:02d} invalid:", " ".join(str(err).splitlines()[1:3])[:100])
            continue
        valid += 1; repaired += attempts > 0; other += o.issue == "other"
        right += correct(o, row["truth"])
    print(f"{backend}/{mode} repairs={repairs}: valid {valid}/50  correct {right}/50  "
          f"repaired {repaired}  issue=other {other}  cost ${spent:.2f}")

Run the prompt-only baseline on Claude:

uv run extract.py claude free
A line like claude/free repairs=0: valid 48/50 correct 45/50 repaired 0 issue=other 9 cost $0.24, possibly preceded by one or two invalid: lines. With a frontier model, prompt-only validity is usually in the mid to high 40s; the failures, when they appear, are Invalid JSON from a Markdown fence or a sentence before the brace. Your numbers will differ run to run. That instability is the point: nothing in this configuration guarantees anything.

4. Turn on schema enforcement.

uv run extract.py claude schema
valid 50/50. The correct count moves by a few at most compared with step 3, in either direction. Look at which messages are still wrong: typically the ones with two numbers that could be the order id, or a total written with a decimal comma. Constraints removed the formatting failures and left the meaning failures exactly where they were, which is what the Predict question was about. The first call in this run is noticeably slower than the rest: that is the grammar compiling, and it is cached for the next 24 hours.

5. The local model, and the repair loop. Run the 3B model in JSON mode, then with repairs, then with its schema-constrained mode:

uv run extract.py ollama free
uv run extract.py ollama free 2
uv run extract.py ollama schema
JSON mode on llama3.2:3b produces parseable JSON every time and still fails validation often: typically 25 to 40 valid out of 50, with errors like issue: Input should be 'late', 'damaged', ... (it wrote Damaged or shipping) and items.0.qty: Input should be a valid integer (it wrote "2x"). With two repairs, validity climbs by 5 to 15, which shows how much an error message is worth. With schema, validity reaches 50/50 and correctness stays well below Claude’s, often 20 to 35. All three Ollama runs cost nothing and take one to three minutes on a laptop. A small local model plus a schema is a reasonable choice for high-volume, low-stakes extraction, as long as you measure the accuracy you are getting.

6. Repair on top of the frontier model.

uv run extract.py claude free 2
valid 50/50 with repaired at 0 to 3. With a strong model, the repair loop mops up the rare wrapper failure for the price of one extra call each. In production you run constraints and repairs together: constraints for shape, Pydantic for the rules the grammar cannot carry, repairs for what fails validation, and a dead-letter queue for what fails three times.
Delete "refund" from the issue Literal in extract.py and re-run uv run extract.py claude schema. Validity stays at 50/50. The issue=other count jumps by the number of refund messages (seven in this dataset), and correct drops by the same amount. Nothing throws, no error is logged, and a dashboard that tracks only validity shows a perfect run. That is the ‘other’ trap in one edit, and the reason the share of other belongs on the same dashboard as the validity rate. Put "refund" back afterwards.
ARTEFACT Write the extraction data contract ~45 MIN
YOU PRODUCEA data contract between a model's output and the downstream system

Template

# Data contract: <extraction name>, version <n>
Decision needed: <what, from whom, by when>. Scope: <which inputs and which consumers>. Out of scope: <what this does not cover>.
Written by <role, producer side>. Approved by <role, consumer side>. Date <date>.

## 1. Schema
| Field | Type | Nullable? | Allowed values | Owner of its meaning |
Where the schema lives (one source of truth): <file or model>.

## 2. Validation
Rules the grammar cannot carry (bounds, sums, formats): <list>. Checked by <validator>.

## 3. When it fails
- Parse or validity failure: <retries, limit, then where it goes>
- Valid but wrong value (checked how, found how): <action>
- Truncation or refusal: <action>
- Share of 'other' and dead-letter count: <alert threshold, who is paged>

## 4. Evidence
Labelled set of <n> messages. Validity <x>/<n>, correct <y>/<n>, cost <$>. Assumptions: <list>.

## 5. Owners
Model side: <role>. Consuming side: <role>. Who is paged for each failure type: <list>.

## 6. Versioning
Version field in every record. Additive change: <process>. Breaking change: <notice, overlap period>. Rollback: <how, how fast>.

## 7. How this could be wrong
<one way, and what would show it>
WORKED EXAMPLE

The support team’s ticket router reads each customer message and posts an order id and an issue to the order service. At a real company the engineer who owns the extractor writes this contract and the owner of the order service approves it.

Data contract: ticket extraction, version 1. Decision needed: the order service lead approves go-live for the router by 30 November 2026. Scope: order id, email, issue, items and total from English support messages. Out of scope: other languages and attachments.

Schema. Order has order_id (integer, nullable), customer_email (nullable), issue (one of late, damaged, wrong_item, refund, other), items and total_eur (nullable). The Pydantic model is the single source; the request schema and the validator derive from it. The order service owns what issue means.

Validation. qty is at least 1, which the grammar cannot enforce, so the validator does.

Failures. Constrained output gave valid 50/50 on the 50-message lab set. The prompt-only baseline gave valid 48/50 and correct 45/50 at $0.24 a pass, so the wrapper failures were real. A failed validation is repaired at most twice, then dead-lettered with the raw text and the error. A valid but wrong value is the harder case: the lab’s schema run still got messages wrong, usually two candidate order numbers. We sample 50 a week against labels. Removing refund moves seven messages into other with nothing thrown, so the share of other is alerted: the labelled share in the lab set is 7 of 50.

Owners and versioning. The engineer owns the model side; the order service lead owns the consuming side and reads the dead-letter queue daily. Every record carries schema_version. Adding an optional field is announced a week ahead. Removing or renaming one runs both versions side by side for two weeks.

How this could be wrong. The 50 messages are generated, not real. Assumed: 2,000 tickets a day. Real tickets could show lower correct counts.

Now you

Wrenpost has about 2,400 business customers and 12 people in support. The support team wants a model to read each incoming ticket and fill four fields for the support queue: the customer account, the product (SMS or email), the severity (low, medium or high) and the country. Engineering would build the extractor; the head of support operations consumes the fields and routes tickets by them.

You write the data contract before anything ships. Reuse what the lab gave you: its validity and correct counts, and what the break step did to the other count. Label any figure about Wrenpost’s own tickets as an assumption. Decide what happens when severity comes back valid but wrong, since a wrong high routes a page at night. Name the owner on each side and say how you would add a fifth field without breaking the queue.

The head of support operations approves it, and decides whether the router goes live.

Self-check

DECIDE

Your team runs an invoice-ingestion job: 200,000 PDFs a day, text already extracted, a model pulls supplier, invoice number, line items and totals into a finance database. It uses a prompt asking for JSON, and about 3% of outputs fail to parse; the job logs a warning and skips them. Finance has noticed missing invoices. You have a week. What do you change?

READING
  1. DOC
    Structured outputs

    The authoritative list of what the grammar supports and what it does not, the stop reasons that break the guarantee, grammar caching, and the strict tool use variant. Read the JSON Schema limitations section twice; skip the per-language tabs you do not use.

  2. DOC
    Pydantic: Models

    How model_validate_json, model_json_schema, required-but-nullable fields and validators behave. Everything this chapter does with schemas rests on it. Skip the sections on generic models and RootModel for now.

  3. PAPER
    Efficient Guided Generation for Large Language Models Brandon T. Willard and Rémi Louf, 2023

    The paper behind Outlines, and the clearest explanation of how a regex or grammar becomes a per-token mask at negligible cost. After it, constrained decoding is a mechanism, not magic. Read: sections 1 to 3; skip the proofs.

  4. PAPER
    Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models Tam et al., 2024

    Evidence that forcing a format can lower reasoning accuracy, and that the effect depends on the task. The reason to reason first and extract second when the model has to work something out. Read: the abstract, the experimental setup, and the results tables for reasoning versus classification tasks.

  5. DOC
    Instructor

    A widely used library that wraps the validate-and-reask loop around Pydantic for many providers, including Anthropic. Read the concepts pages on validation and retries to compare with the loop you wrote; skip the provider catalogue.

  6. DOC
    Ollama: Structured outputs

    How the format parameter takes either 'json' or a JSON Schema for local models, with the advice to repeat the schema in the prompt and lower the temperature. Short; read all of it.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Tool use and function calling →