03.4 Structured Output
Most LLM features end with your code reading what the model wrote: a category to route a ticket, an invoice to post to the ledger, a list of action items to put in a tracker. Code can't read "Sure! Here's the JSON you asked for", so the reply has to come back as structured output: data with a known shape that a parser accepts and a schema checks. Every provider now offers ways to make that happen, from asking nicely, through a "JSON mode", to decoding that is constrained by your schema and can't produce anything else. They differ in the schema features they accept, what their SDK helpers do to your schema before sending it, how they report refusals and truncated replies, and what they quietly ignore. This lesson is the complete engineering reference for structured output on OpenAI, Anthropic, Gemini and OpenRouter: Pydantic models as schemas, what actually goes over the wire, each provider's supported subset and limits, validation in layers, validate-and-retry with escalation, streaming partial objects, the common extraction and classification patterns, and the libraries built on top.
What you'll learn
- The four ways to get machine-readable output (prompt plus parse, JSON mode, schema-constrained output, strict tools), and when each is still the right choice
- Every provider's structured-output API, completely: OpenAI Responses (
text.format,responses.parse) and Chat Completions (response_format,chat.completions.parse), Anthropic (output_config.format,messages.parse, strict tools), Geminigenerate_content(response_schema,response_json_schema, enum mode) and Interactions (response_format), and OpenRouter (per-endpoint support,require_parameters, response healing) - Pydantic as the schema language: descriptions,
LiteralandEnum, nullable-but-required fields, nested models, bounded lists, unions, dates, defaults, and what each SDK transforms your schema into before it is sent - Each provider's supported JSON Schema subset and limits, in one verified table, with a pre-flight linter and the errors you get when a schema is rejected
- Schema design for reliability: names and descriptions, a reasoning or evidence field before the answer, an explicit "unknown" path, flat and bounded structures, enums, and splitting big schemas
- Validation in layers (parse, schema, semantic validators, business rules), and refusals, truncation and safety blocks as distinct outcomes on every provider
- A production validate-and-retry extractor: errors fed back, bounded retries, model escalation, human review and a typed result
- Streaming partial objects safely, and the patterns: classification, nested line items, multi-entity extraction, normalization, and "fill what you can"
- Why an extracted value is untrusted input, even when it is schema-valid
- What
instructorand Pydantic AI add on top of the native SDK helpers, and what they cost - The cost and latency of structured output: schemas as input tokens, first-request compilation, and prompt-cache interactions
What you don't need
- API keys. Every part has something you can run for free: real calls to a small local model, mock servers returning the providers' documented responses, or pure Python with no network at all. Samples that need a hosted provider are labelled, and their output is marked as illustrative.
- How constrained decoding works inside the model. Lesson 02.5, Part 9 explains the token masking; this lesson uses it.
- Tool calling in depth. Strict tools appear here as an output channel; the full round trip is lesson 03.5.
- Prompt wording. This lesson gives schema-design advice; what to write in instructions is Module 04.
Setup
The samples need Python 3.11+, the three official SDKs, and Pydantic. Lessons 03.1 to 03.9 share one project folder, llm-apis. If you haven't created it yet, run uv init llm-apis --bare --python 3.13 && cd llm-apis first (see lesson 03.1, Part 4 for the full setup and the .env file), then add this lesson's packages:
uv add openai anthropic google-genai pydantic python-dotenv tiktoken httpx
# or: pip install openai anthropic google-genai pydantic python-dotenv tiktoken httpxThe samples were written and checked against openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0 and Pydantic 2.14 as of November 2026; a newer major version may change names or defaults, so check the SDK's changelog if something does not match (03.1, 4.5 covers the google-genai 3.x changes). The mock-server samples build Gemini clients on httpx and OpenAI and Anthropic clients on httpx2. google-genai 2.34.0 installed httpx itself; 3.x does not, which is why httpx is in the command above.
The .env file holds the keys:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...Part 7's extractor also imports two small modules from lesson 03.8: llm_errors.py (4.4) and the retry_after.py it uses (7.3). Copy them into the same folder as the samples.
Part 10 uses two optional libraries. pydantic-ai-slim[openai] (2.66.0 as of November 2026) installs alongside the SDKs. instructor (1.17.0) does not, as of November 2026, so run it in its own environment (10.1 explains why).
The free local option. Samples marked "Try it free" run against qwen2.5:0.5b: Ollama serves the OpenAI and Anthropic formats on http://localhost:11434. Lesson 03.1, Part 12 shows how to install it. Two things have no local stand-in. Gemini: Ollama does not speak Gemini's API (lesson 03.1, 12.4), so every google-genai sample here is marked hosted-only (it needs GEMINI_API_KEY) and was not run. Anthropic output_config.format: Ollama's Anthropic endpoint ignores it, so those samples are hosted-only too; Anthropic Messages calls without output_config do run on Ollama. In your own tests, a hand-written mock server or recorded responses can stand in for Gemini. Several samples use small modules that live next to them (order_model.py, invoice_model.py, outcomes.py, extractor.py, schema_lint.py); each one is printed in full where it is introduced.
What you must be able to do after this lesson#
- Choose an approach from the ladder of structured output options
- Define a schema with Pydantic
- Design a schema that is reliable for the model
- Validate output in layers
- Retry when validation fails
- Call structured output on a provider
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Just tell it to reply in JSON." | 1.2 Rung 1: prompt plus parse |
| "We turned on JSON mode, so the output is safe." | 1.3 Rung 2: JSON mode |
| "Use structured outputs, not JSON mode." | 1.4 Rung 3: schema-constrained output |
"Should we extract with a tool call or with response_format?" |
1.5 Rung 4: strict tools |
| "The SDK rewrote my schema." | 2.9 Try it: what each SDK sends |
| "OpenAI says every field must be required. How do I make one optional?" | 2.4 Optional means nullable, not omittable |
"response.parsed is None and there's no error." |
3.9 When the helpers fail |
| "Claude rejected our schema as too complex." | 4.3 Anthropic's rules and limits |
"Gemini ignored our maxLength." |
4.4 Gemini's rules and limits |
| "Structured output works on that model on OpenRouter, but not on every endpoint." | 3.6 OpenRouter |
| "The JSON was valid, the total was wrong." | Part 6: Validation in layers |
| "Retry it with the error message." | Part 7: Validate-and-retry, provider-native |
"What are $ref, anyOf and additionalProperties?" |
Part 2, JSON Schema in 60 seconds |
"The model put HTML in the name field. The schema said string." |
6.3 Semantic validators (extracted values are untrusted) |
| "Show the extracted fields while it's still generating." | Part 8: Streaming partial objects |
| "Add a confidence score to the classifier." | 9.1 Classification |
| "Why not just use instructor?" | Part 10: Libraries |
| "Our schema costs more tokens than the prompt." | Part 11: Cost and latency |
Part 1: The ladder of approaches#
1.1 Four rungs#
There are four ways to get output your code can parse. Think of them as a ladder: each rung up gives you a stronger guarantee, and asks more of the provider and the model.
| Rung | What you do | What is guaranteed | Reliability | Cost | Portability |
|---|---|---|---|---|---|
| 1. Prompt plus parse | Ask for JSON in the prompt, then find and parse it in the reply | Nothing | Depends on the model and the input: usually fine, occasionally not | Prompt tokens for the instructions; retries when it fails | Works everywhere, including models with no JSON features |
| 2. JSON mode | Tell the API you want JSON, with no schema | The reply parses as JSON (when the provider enforces it) | Valid syntax, but keys, types and values are still up to the model | As rung 1, plus nothing extra | OpenAI, Gemini, OpenRouter (per endpoint); not Anthropic |
| 3. Schema-constrained structured output | Send a JSON Schema; the provider constrains decoding to it | The reply matches the schema (within the provider's supported subset) | Very high for format; content can still be wrong | The schema is input tokens on every request; first use may add compile latency | All four, with different schema subsets (Part 4) |
| 4. Strict tools | Define a tool whose parameters are your schema, with strict: true; read the arguments of the "call" |
The arguments match the schema (same machinery as rung 3) | As rung 3 | Tool definitions are input tokens, plus the tool-use system prompt some providers add | All four, but every provider's tool format differs (03.5) |
The mechanism behind rungs 3 and 4, constrained decoding (masking every token the schema doesn't allow before sampling), is explained in lesson 02.5, Part 9. Two consequences from that lesson drive everything here: the guarantee covers the format, not the truth (02.5, 9.3), and it only covers the schema features the provider's grammar engine supports.
flowchart TD
Q1{"Does code parse<br/>the output?"} -- "no, a person reads it" --> T["Plain text"]
Q1 -- yes --> Q2{"Does the model support<br/>schema-constrained output?"}
Q2 -- yes --> Q3{"Must the model choose<br/>between several actions<br/>or shapes?"}
Q3 -- "no: one shape" --> R3["Rung 3: schema-constrained<br/>structured output"]
Q3 -- "yes" --> R4["Rung 4: strict tools<br/>(one tool per shape)"]
Q2 -- "no" --> Q4{"Does it offer<br/>JSON mode?"}
Q4 -- yes --> R2["Rung 2: JSON mode<br/>+ Pydantic validation"]
Q4 -- no --> R1["Rung 1: prompt + parse<br/>+ validation + retry"]Whichever rung you stand on, you still validate with your own Pydantic model (Part 6). The rungs change how often validation fails, not whether you need it.
1.2 Rung 1: prompt plus parse#
Asking for JSON in the prompt is still the right choice in a few places: a model or endpoint with no JSON features (some open-weight models on some hosts), a quick prototype, or output that mixes prose and data on purpose (an answer for a person with a JSON block for your code). Lesson 02.10, 8.3 showed why it fails intermittently, and 21.3 built a small validate-and-retry wrapper around it with text.find("{") and text.rfind("}").
That one-liner breaks on two common replies: prose after the JSON that contains a brace, and a reply with two objects (a "first try" and a "corrected" version). A sturdier extractor uses json.JSONDecoder.raw_decode, which parses one JSON value starting at a given position and reports where it ended. Collect every top-level object, then let your schema choose:
# s1_2_extract_json.py
"""Rung 1, prompt plus parse: find the JSON object in a chatty reply, and let the schema pick.
json.JSONDecoder.raw_decode parses ONE JSON value starting at a given position and says
where it ended, so it copes with prose before and after, code fences, and braces inside
strings. We collect every top-level object, then return the first one that validates.
"""
import json
from collections.abc import Iterator
from typing import TypeVar
from pydantic import BaseModel, ValidationError
_decoder = json.JSONDecoder()
M = TypeVar("M", bound=BaseModel)
class Person(BaseModel):
name: str
age: int
def iter_json_objects(text: str) -> Iterator[dict]:
"""Yield each top-level JSON object found in `text`, left to right."""
pos = text.find("{")
while pos != -1:
try:
value, end = _decoder.raw_decode(text, pos)
except json.JSONDecodeError:
pos = text.find("{", pos + 1) # not valid JSON from here: try the next "{"
continue
if isinstance(value, dict):
yield value
pos = text.find("{", end) # skip past this object (and anything nested in it)
def parse_reply(text: str, model: type[M]) -> M:
"""Return the first object in `text` that validates against `model`."""
errors = []
for candidate in iter_json_objects(text):
try:
return model.model_validate(candidate)
except ValidationError as err:
errors.append(err)
raise ValueError(f"no valid {model.__name__} in reply ({len(errors)} JSON object(s) failed validation)")
REPLIES = {
"clean": '{"name": "Priya", "age": 29}',
"fenced": 'Sure! Here it is:\n```json\n{"name": "Tom", "age": 41}\n```',
"prose after": '{"name": "Ana", "age": 35}\nLet me know if you need anything else {happy to help}.',
"brace in a string": 'Result: {"name": "Kenji {KJ}", "age": 52} (done)',
"two objects": 'First try: {"name": "Fatima"} Corrected: {"name": "Fatima", "age": 23}',
"single quotes": "{'name': 'Lukas', 'age': 38}",
"truncated": '{"name": "Lukas", "age": 3',
}
def naive(text: str) -> dict: # the common one-liner, for comparison
return json.loads(text[text.find("{"): text.rfind("}") + 1])
for label, reply in REPLIES.items():
try:
ours = repr(parse_reply(reply, Person))
except ValueError as err:
ours = f"ValueError: {err}"
try:
theirs = str(naive(reply))
except json.JSONDecodeError as err:
theirs = f"JSONDecodeError: {err.msg}"
print(f"{label:17} | ours: {ours}\n{'':17} | naive: {theirs}")clean | ours: Person(name='Priya', age=29)
| naive: {'name': 'Priya', 'age': 29}
fenced | ours: Person(name='Tom', age=41)
| naive: {'name': 'Tom', 'age': 41}
prose after | ours: Person(name='Ana', age=35)
| naive: JSONDecodeError: Extra data
brace in a string | ours: Person(name='Kenji {KJ}', age=52)
| naive: {'name': 'Kenji {KJ}', 'age': 52}
two objects | ours: Person(name='Fatima', age=23)
| naive: JSONDecodeError: Extra data
single quotes | ours: ValueError: no valid Person in reply (0 JSON object(s) failed validation)
| naive: JSONDecodeError: Expecting property name enclosed in double quotes
truncated | ours: ValueError: no valid Person in reply (0 JSON object(s) failed validation)
| naive: JSONDecodeError: Expecting valueRead the rows that differ. With prose after the JSON, the naive slice runs from the first { to the last } and swallows {happy to help}. With two objects it does the same and parses neither. parse_reply gets both right, because it tries each object in turn and keeps the first one that passes Person. Single quotes and a truncated object fail in both, correctly: neither is JSON, and you should never repair them by guessing (02.5, 4.6). Ask again instead.
What this means for you as an engineer: if you must parse free text, parse candidates and let the schema decide, rather than slicing strings. Then move up a rung as soon as the provider allows it.
1.3 Rung 2: JSON mode#
JSON mode tells the API to produce valid JSON, without saying which JSON. Per provider, as of November 2026:
| Provider | How to turn it on | Notes |
|---|---|---|
| OpenAI | Responses: text={"format": {"type": "json_object"}}. Chat Completions: response_format={"type": "json_object"} |
The word "JSON" must appear somewhere in the context, or the API returns an error. OpenAI's guide: "If you don't include an explicit instruction to generate JSON, the model may generate an unending stream of whitespace and the request may run continually until it reaches the token limit." The API reference marks JSON mode "Not recommended for gpt-4o and newer models"; the guide says "We recommend always using Structured Outputs instead of JSON mode when possible" |
| Anthropic | Not offered. output_config.format accepts only type: "json_schema" |
Use a schema (3.3) |
| Provider | How to turn it on | Notes |
|---|---|---|
| Gemini | generate_content: response_mime_type="application/json" with no schema. Interactions: response_format={"type": "text", "mime_type": "application/json"} with no schema |
Google's Vertex docs describe JSON without a schema as "only a strong hint to the model" (02.5, 9.2) |
| OpenRouter | response_format={"type": "json_object"} (Chat Completions) or text.format (Responses) |
OpenRouter's parameter docs: it "guarantees the message the model generates is valid JSON", and "you should also instruct the model to produce JSON yourself". Support varies by endpoint (3.6) |
Try it free. The same "extract name and age as JSON" request, three times on each local path (the two OpenAI endpoints; Gemini's response_mime_type form has no local stand-in, so it is not in this script):
# s1_3_json_mode.py
"""Rung 2, JSON mode: valid JSON, but no schema. Try it free against the local stand-in.
OpenAI Responses and Chat Completions go to Ollama (localhost:11434). The prompt names the
keys we want; JSON mode itself only promises that whatever comes back parses.
"""
import json
from openai import OpenAI
PROMPT = ('Extract the customer as JSON with keys "name" and "age" (an integer).\n\n'
"Message: Hello! Fatima Noor, 23, from Lahore. Can I change my address?")
oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
def responses_json_mode() -> str:
r = oai.responses.create(model="gpt-6-luna", input=PROMPT, max_output_tokens=80,
text={"format": {"type": "json_object"}})
return r.output_text
def chat_json_mode() -> str:
c = oai.chat.completions.create(model="gpt-6-luna", max_completion_tokens=80,
messages=[{"role": "user", "content": PROMPT}],
response_format={"type": "json_object"})
return c.choices[0].message.content or ""
for name, call in [("Responses", responses_json_mode), ("Chat", chat_json_mode)]:
for attempt in range(1, 4):
text = call()
try:
data = json.loads(text) # with JSON mode enforced, this never fails
except json.JSONDecodeError:
print(f"{name:9} #{attempt} NOT JSON {text[:60]!r}")
continue
ok = isinstance(data, dict) and set(data) == {"name", "age"} and isinstance(data["age"], int)
print(f"{name:9} #{attempt} {'matches ' if ok else 'WRONG '} {json.dumps(data)}")Responses #1 matches {"name": "Fatima Noor", "age": 23}
Responses #2 matches {"name": "Fatima Noor", "age": 23}
Responses #3 NOT JSON '```json\n{\n "name": "Fatima Noor",\n "age": 23,\n "add'
Chat #1 WRONG {"name": "Fatima Noor", "age": 23, "gender": "female"}
Chat #2 WRONG {"name": "Fatima", "age": 23, "address": {"city": "Lahore", "country": "Pakistan"}}
Chat #3 WRONG {"name": "Fatima Noor", "age": 23, "email": ""}Two lessons in one printout:
- JSON mode is not a schema. Where the stand-in enforced it (Chat Completions on Ollama), every reply parsed, and none had exactly the keys we asked for: the model added
gender, a nestedaddressand an emptyemail. That's all JSON mode promises. A hosted model follows instructions far better than a 0.5B model, but the guarantee is the same: valid syntax, nothing more. - The stand-in doesn't enforce everything. Ollama's Responses endpoint accepted the JSON-mode setting and ignored it, so in one reply the model wrapped its JSON in a Markdown fence, which
json.loadsrejects. The hosted APIs enforce JSON mode; a local run only proves that your code builds the request correctly (lesson 03.1, 12.6).
When is JSON mode still the right choice? When the model or endpoint supports JSON mode but not schemas, or when the shape is genuinely open (arbitrary key-value metadata the model decides). In both cases validate with Pydantic, and expect retries.
1.4 Rung 3: schema-constrained structured output#
You send a JSON Schema with the request; the provider compiles it into a grammar and constrains decoding to it, so the reply parses and matches the schema (except for refusals and truncation, Part 6). This is what the providers call Structured Outputs, and it is the default choice for any output your code consumes:
- OpenAI:
text.formatwith"type": "json_schema"and"strict": true(Responses), orresponse_formatwith ajson_schema(Chat Completions). OpenAI: "Structured Outputs is the evolution of JSON mode. While both ensure valid JSON is produced, only Structured Outputs ensure schema adherence." - Anthropic:
output_config.formatwith"type": "json_schema", generally available on every model, no beta header. - Gemini:
response_mime_type="application/json"withresponse_json_schema(standard JSON Schema, Google's current recommendation) orresponse_schema(the SDK's Pydantic convenience) ongenerate_content, orresponse_formatwith aschemaon Interactions (3.4). - OpenRouter: the OpenAI shapes, passed through to endpoints that support them.
Part 3 covers each in full. Use rung 3 when the model's whole reply is the data: extraction, classification, transformation, any "answer in this shape".
1.5 Rung 4: strict tools as an output channel#
A tool (function) definition has a name, a description and a JSON Schema for its parameters. If you mark it strict, the provider constrains the arguments with the same grammar machinery as rung 3. So a tool you never actually run is another way to get schema-valid output: the model "calls" record_order, and you read the arguments.
When is rung 4 the right choice rather than rung 3?
- The model must choose between shapes. One tool per possible action (
create_ticket,escalate,ask_clarifying_question), and the model picks one. With rung 3 you'd need a union of all the shapes in one schema. - You're already in a tool-calling flow, and the final answer is just one more tool.
- The provider or model supports strict tools but not schema-constrained responses, which is now rare on the first-party APIs but still happens on some OpenRouter endpoints.
The traps are tool-specific. Forcing a tool call is how extraction-by-tool was usually done, and as of November 2026 Anthropic rejects it on its biggest models: tool_choice of any or tool "return a 400 error" on Claude Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1, with the message tool_choice: type "tool" and "any" are not supported for this model. Haiku 5.5 still accepts it. Anthropic's recommendation is "auto with strict tool use to guarantee schema-valid tool inputs, or structured outputs when you need a response in a fixed JSON shape". Gemini has no per-tool strict flag; instead, function-calling mode VALIDATED ("Model ensures function schema adherence") applies to the declarations. Here are all four (a hosted-provider sample: keys needed):
# s1_5_strict_tool_extraction.py
"""Rung 4: a strict tool definition as the structured-output channel, on all four providers.
The model "calls" record_order; we never run anything, we just read the arguments.
Needs OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY and OPENROUTER_API_KEY in .env.
The full tool-calling round trip is lesson 03.5.
"""
import json
import os
import anthropic
from anthropic import transform_schema
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI
from openai.lib._pydantic import to_strict_json_schema # private helper: may change in any openai release
from pydantic import ValidationError
from order_model import Order
load_dotenv()
EMAIL = "From: Ana Lima, 2 Nov 2026. Please send 2 x ABC-1234, urgent. No gift message."
TOOL = "record_order"
DESCRIPTION = "Record the customer's order exactly as stated in the email."
def show(provider: str, make_order) -> None:
"""Strict mode constrains the arguments; still validate them, and report what went wrong."""
try:
print(f"{provider:10}", make_order())
except ValidationError as err:
print(f"{provider:10} ValidationError: {err.error_count()} error(s), first: {err.errors()[0]['msg']}")
# OpenAI Responses: strict function tool, forced with tool_choice
oai = OpenAI()
r = oai.responses.create(
model="gpt-6-luna", input=EMAIL, max_output_tokens=2000, reasoning={"effort": "none"},
tools=[{"type": "function", "name": TOOL, "description": DESCRIPTION, "strict": True,
"parameters": to_strict_json_schema(Order)}],
tool_choice={"type": "function", "name": TOOL})
call = next(item for item in r.output if item.type == "function_call")
show("OpenAI", lambda: Order.model_validate_json(call.arguments))
# Anthropic: strict tool. Forced tool_choice ("any"/"tool") is a 400 on Opus 5.5, Sonnet 5.5,
# Fable 5.2 and 5.1 and Mythos 5.2 and 5.1, so use "auto" (and check that the model did call the tool)
claude = anthropic.Anthropic()
m = claude.messages.create(
model="claude-sonnet-5-5", max_tokens=2000, messages=[{"role": "user", "content": EMAIL}],
tools=[{"name": TOOL, "description": DESCRIPTION, "strict": True, "input_schema": transform_schema(Order)}],
tool_choice={"type": "auto"})
use = next((b for b in m.content if b.type == "tool_use"), None)
show("Anthropic", lambda: Order.model_validate(use.input) if use else f"no tool call (stop_reason={m.stop_reason})")
# Gemini generate_content: function calling mode VALIDATED ("ensures function schema adherence")
gem = genai.Client()
g = gem.models.generate_content(
model="gemini-3.8-flash", contents=EMAIL,
config=types.GenerateContentConfig(
tools=[types.Tool(function_declarations=[types.FunctionDeclaration(
name=TOOL, description=DESCRIPTION, parameters_json_schema=Order.model_json_schema())])],
tool_config=types.ToolConfig(function_calling_config=types.FunctionCallingConfig(
mode=types.FunctionCallingConfigMode.VALIDATED)),
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)))
fc = g.function_calls[0] if g.function_calls else None
show("Gemini", lambda: Order.model_validate(fc.args) if fc else f"no function call ({g.candidates[0].finish_reason})")
# OpenRouter: Chat Completions tool with strict, forced. With a Claude model ID here, OpenRouter would
# strip `strict` unless you send the x-anthropic-beta header (lesson 03.5, 10.5), so this stays on an OpenAI model
router = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
default_headers={"HTTP-Referer": "https://example.com/orders-demo", "X-OpenRouter-Title": "Orders demo"},
)
c = router.chat.completions.create(
model="openai/gpt-6-luna", messages=[{"role": "user", "content": EMAIL}], max_completion_tokens=2000,
tools=[{"type": "function", "function": {"name": TOOL, "description": DESCRIPTION, "strict": True,
"parameters": to_strict_json_schema(Order)}}],
tool_choice={"type": "function", "function": {"name": TOOL}},
extra_body={"provider": {"require_parameters": True}}) # OpenRouter-only: endpoints that support it all
tool_calls = c.choices[0].message.tool_calls or []
args = json.loads(tool_calls[0].function.arguments) if tool_calls and tool_calls[0].type == "function" else None
show("OpenRouter", lambda: Order.model_validate(args) if args else f"no tool call ({c.choices[0].finish_reason})")OpenAI customer='Ana Lima' order_date=datetime.date(2026, 11, 2) priority=<Priority.URGENT: 'urgent'> channel='email' gift_message=None discount_code=None items=[LineItem(sku='ABC-1234', quantity=2)]
Anthropic customer='Ana Lima' order_date=datetime.date(2026, 11, 2) priority=<Priority.URGENT: 'urgent'> channel='email' gift_message=None discount_code=None items=[LineItem(sku='ABC-1234', quantity=2)]
Gemini customer='Ana Lima' order_date=datetime.date(2026, 11, 2) priority=<Priority.URGENT: 'urgent'> channel='email' gift_message=None discount_code=None items=[LineItem(sku='ABC-1234', quantity=2)]
OpenRouter customer='Ana Lima' order_date=datetime.date(2026, 11, 2) priority=<Priority.URGENT: 'urgent'> channel='email' gift_message=None discount_code=None items=[LineItem(sku='ABC-1234', quantity=2)]Run against the stand-in, the OpenAI, Anthropic and OpenRouter-shaped calls go end to end and each prints a ValidationError: Ollama ignores strict and tool_choice, so the tiny model's tool arguments are unconstrained. The Gemini call is hosted-only, because Ollama doesn't speak Gemini's API (03.1, 12.4). That's why the sample validates the arguments even with strict mode on, and catches the error instead of crashing. Order and to_strict_json_schema are explained in Part 2. Note also automatic_function_calling=...(disable=True): the Gemini SDK can call Python functions for you, which you don't want here.
What this means for you as an engineer: prefer rung 3 for "give me this data". Reach for rung 4 when the model has to pick which shape, and then follow lesson 03.5 for the round trip, tool_choice and parallel calls. The strict-schema rules in Part 4 apply to both rungs.
1.6 When each rung is still right#
| Situation | Rung |
|---|---|
| A person reads the output | None: plain text |
| Your code reads one known shape, on a model with structured outputs | 3 |
| The model must choose between several actions or shapes | 4 |
| A model or endpoint with JSON mode but no schema support | 2, plus validation and retries |
| A model with neither (some open-weight hosts), or prose with embedded data | 1, plus the extractor in 1.2, validation and retries |
| Arbitrary keys you can't list in advance (free-form metadata) | 2, or rung 3 with a list of {"key", "value"} pairs (2.8 shows why dict[str, X] fails on strict modes) |
| A schema the provider can't express (recursion on Anthropic, a 2,000-value enum) | Redesign it first (Part 5); otherwise rung 2 on that provider, or another provider |
Part 2: Pydantic as the schema language#
JSON Schema in 60 seconds. Every schema in this lesson is built from the same dozen keywords. You will read them in printouts from here on, so here they are in plain language first:
| Keyword | Plain meaning |
|---|---|
type |
What kind of value: string, number, integer, boolean, object (a set of named fields), array (a list) or null |
properties |
For an object: the fields it may have, each with its own schema |
required |
The names of the fields that must be present (a field not listed here may be left out) |
enum |
A closed set of allowed values: ["cat", "dog"] |
anyOf |
"One of these shapes". [{"type": "integer"}, {"type": "null"}] means an integer or null. (oneOf is the stricter cousin, "exactly one of these"; most providers want anyOf) |
$defs and $ref |
A named definition and a reference to it. Instead of repeating the Owner shape wherever it is used, the schema defines it once under $defs and writes {"$ref": "#/$defs/Owner"} where it is needed. # means "this document" |
additionalProperties: false |
"No extra keys": the object may contain only the fields listed in properties. Strict modes require it on every object |
format and pattern |
Refinements of a string: format names a well-known shape (date, date-time, email, uuid), and pattern is a regular expression it must match |
description and title |
Free text. The model reads descriptions (2.2), so they are part of your prompt |
Here is one small Pydantic class that uses most of them, and the schema Pydantic writes for it (layer 1, no network; titles are dropped for brevity):
# s2_0_schema_primer.py
"""JSON Schema in 60 seconds: one tiny Pydantic class, and the schema it produces (layer 1, no network)."""
import json
from typing import Literal
from pydantic import BaseModel, ConfigDict
class Owner(BaseModel):
model_config = ConfigDict(extra="forbid") # "no extra keys": this becomes additionalProperties: false
name: str
class Pet(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
kind: Literal["cat", "dog"] # a closed set of values: enum
age: int | None # "an integer or null": anyOf
owner: Owner # a nested class: a named definition reached by $ref
schema = Pet.model_json_schema()
for key in ("type", "required", "additionalProperties"): # the top level of the schema
print(f"{key:21} {json.dumps(schema[key])}")
for name, prop in schema["properties"].items(): # one line per field
print(f"properties.{name:10} {json.dumps({k: v for k, v in prop.items() if k != 'title'})}")
print(f"{'$defs.Owner':21} {json.dumps({k: v for k, v in schema['$defs']['Owner'].items() if k != 'title'})}")type "object"
required ["name", "kind", "age", "owner"]
additionalProperties false
properties.name {"type": "string"}
properties.kind {"enum": ["cat", "dog"], "type": "string"}
properties.age {"anyOf": [{"type": "integer"}, {"type": "null"}]}
properties.owner {"$ref": "#/$defs/Owner"}
$defs.Owner {"additionalProperties": false, "properties": {"name": {"title": "Name", "type": "string"}}, "required": ["name"], "type": "object"}Read it line by line: required lists all four fields; kind became an enum; age: int | None became an anyOf of an integer and null; owner is a $ref to the Owner definition under $defs; and extra="forbid" is what produced additionalProperties: false (Pydantic's default allows extra keys and writes nothing). The providers' SDKs add that last one for you (2.9).
2.1 One class, three jobs#
Hand-writing JSON Schema is verbose and easy to get subtly wrong. A Pydantic model does three jobs from one definition:
- Generates the schema you send (
Model.model_json_schema(), or the SDK does it for you). - Validates the reply, with rules the provider can't enforce (
Model.model_validate_json(text)). - Gives your code typed objects (
order.items[0].quantityis anint,order.order_dateadatetime.date).
All three SDKs accept a Pydantic class directly in their parse helpers. Here is the example model used in Parts 2 and 3. It lives in order_model.py, which later samples import:
# order_model.py: the example schema used in Parts 2 and 3
import re
from datetime import date
from enum import Enum
from typing import Literal
from pydantic import BaseModel, Field, field_validator
SKU = re.compile(r"[A-Z]{3}-\d{4}")
class Priority(str, Enum):
LOW = "low"
NORMAL = "normal"
URGENT = "urgent"
class LineItem(BaseModel):
sku: str = Field(description="Stock code, e.g. ABC-1234")
quantity: int = Field(ge=1, le=999)
@field_validator("sku") # checked by Pydantic, never sent to the provider
@classmethod
def sku_format(cls, value: str) -> str:
if not SKU.fullmatch(value):
raise ValueError("sku must look like ABC-1234")
return value
class Order(BaseModel):
"""A customer order extracted from an email."""
customer: str = Field(description="Customer's full name (at most 100 characters)")
order_date: date
priority: Priority
channel: Literal["email", "phone", "web"]
gift_message: str | None = Field(description="The gift message, or null if there is none")
discount_code: str | None = None
items: list[LineItem] = Field(min_length=1, max_length=20)
@field_validator("customer") # a length limit is Pydantic's job: OpenAI's documented
@classmethod # strict subset has no maxLength (see 2.9 and 4.2)
def customer_length(cls, value: str) -> str:
if len(value) > 100:
raise ValueError("customer must be at most 100 characters")
return valueWhy Order has a validator instead of max_length=100 on customer. A string length limit (Field(max_length=100)) is written into the schema as maxLength, and OpenAI's documented strict subset does not list maxLength or minLength: its string keywords are pattern and format only (4.2). Because this model feeds the hosted OpenAI samples in 1.5 and 3.8, the length rule lives in a @field_validator instead, where it works on every provider and never reaches the schema. The description still says "at most 100 characters" so the model knows. 2.8 shows what each SDK does when a length limit does reach the schema.
2.2 Descriptions are part of the prompt#
The schema is sent to the model with your request, and the model reads it: field names, descriptions, enum values, even the class docstring (which becomes the schema's description). So a description is prompt text in a structured place. Field(description="Customer's full name") tells the model what you mean by customer far more reliably than a sentence in the system prompt.
Write descriptions for the model, not for your colleagues: what the field is, what format it takes, and what to do when the information is missing ("or null if there is none"). Part 5 covers schema design; prompt wording in general is Module 04's subject.
2.3 Literal and Enum: closed sets of values#
For a field that takes one of a few values, use Literal[...] or an Enum. Both become a JSON Schema enum, which constrained decoding enforces: on a hosted model with strict structured output, channel can only be "email", "phone" or "web".
Literalis lighter: the values appear inline in the property.- An
Enum(herePriority(str, Enum)) becomes a separate definition under$defswith a$refto it, and gives your code named constants (Priority.URGENT).
Two cautions. Casing isn't guaranteed on Anthropic: its docs say "Structured outputs don't guarantee the capitalization of string enum and const values… The response completes normally, with no error and no special stop_reason." Normalize case before you compare (6.3 shows a mode="before" validator that does it). And giant enums cost tokens and can break schema limits (5.4).
2.4 Optional means nullable, not omittable#
This is the rule that trips everyone up on OpenAI. In strict mode "all fields or function parameters must be specified as required", and you make a field optional by allowing null. So in strict modes "optional" means nullable but required: the key is always present, and its value may be null.
In Pydantic, the difference is whether the field has a default:
| Pydantic | JSON Schema from Pydantic | Meaning |
|---|---|---|
gift_message: str | None = Field(description=...) (no default) |
anyOf: [string, null], in required |
Nullable and required: always present, may be null. What strict modes want |
discount_code: str | None = None |
anyOf: [string, null], default: null, not in required |
May be left out entirely |
2.9 shows that the OpenAI SDK quietly makes discount_code required anyway (and drops its None default), while Anthropic and Gemini keep it optional. Write str | None with no default and a description that says when to use null, and the schema means the same thing on every provider.
2.5 Nested models and bounded lists#
Models nest: items: list[LineItem] puts a $ref to a LineItem definition inside an array. Bound every list: Field(min_length=1, max_length=20) becomes minItems/maxItems. A bound protects you twice: it stops a model from emitting an endless list (which ends in truncation), and it documents your expectation. Support differs: OpenAI enforces minItems and maxItems; Anthropic supports only minItems of 0 or 1, so its SDK moves maxItems into the description and Pydantic enforces it afterwards; Gemini enforces both but warns that large maxItems values, especially on nested arrays, are a common cause of "too many states" errors (4.4).
2.6 Unions and discriminated unions#
A field that can be one of several shapes is a union: payment: Card | Bank. Pydantic turns a plain union into anyOf, which all three providers support. A discriminated union, Annotated[Card | Bank, Field(discriminator="kind")], validates faster and gives better errors in Pydantic, but its JSON Schema uses oneOf plus a discriminator object, and 2.8 shows what that does: the OpenAI SDK sends oneOf through unchanged (it isn't in OpenAI's documented subset, which lists anyOf), the Anthropic SDK converts it to anyOf and moves the discriminator into the description, and google-genai's response_schema=Model conversion refuses it before sending (with response_json_schema it goes through: the SDK's own docs say oneOf is "interpreted the same as anyOf").
The portable recipe is a plain union of models that each carry a Literal tag (kind: Literal["card"]). The model must still write the tag, Pydantic still picks the right class, and the schema is a plain anyOf. Keep unions small: Anthropic counts each union-typed parameter against a limit of 16 per request (4.3), and a root-level anyOf is not allowed on OpenAI.
2.7 Dates: date, datetime or a string with a format#
order_date: date becomes {"type": "string", "format": "date"}; datetime becomes "format": "date-time". All three providers list date and date-time among their supported string formats (OpenAI and Anthropic also accept time and duration; Gemini lists date-time, date and time). The schema still says string: the model writes "2026-11-02", and Pydantic turns it into a datetime.date on your side, rejecting "2 Nov 2026" with a clear error.
Three practical rules:
- Say the format in the description too ("ISO date, YYYY-MM-DD"), because
formatis a hint to some grammar engines rather than a hard constraint, and Gemini's reference says offormatthat "Any value is allowed, but most do not trigger any special functionality". - Give the model today's date when the text may contain relative dates ("yesterday", "next Friday"), and validate the result's range (9.5).
- Time zones:
datetimewithformat: date-timeaccepts offsets; if you need UTC, convert in a validator rather than trusting the model to have done it.
2.8 Try it: tricky constructs on every SDK#
Before anything is sent, each SDK rewrites your schema. This pure-Python script (layer 1, plus a mock transport so google-genai's conversion can be captured without any network) shows what happens to eight constructs that cause real bugs. For Gemini it captures both routes: response_schema=Model (the SDK converts your class) and response_json_schema=Model.model_json_schema() (sent as written), which is the gemini-json line:
# s2_8_construct_matrix.py
"""Tricky Pydantic constructs: what each SDK does with them before anything is sent.
OpenAI: the strict transform used by responses.parse / chat.completions.parse
(openai.lib._pydantic.to_strict_json_schema: private, an implementation detail).
Anthropic: anthropic.transform_schema (public; what messages.parse uses).
Gemini: google-genai's conversion of response_schema=Model, and the response_json_schema=...
route (Google's recommended field), both captured from the request body with a mock
transport (layer 5; nothing leaves the machine).
"""
import json
from datetime import datetime
from typing import Annotated, Literal
import httpx
from anthropic import transform_schema
from google import genai
from google.genai import types
from openai.lib._pydantic import to_strict_json_schema # private: may change between versions
from pydantic import BaseModel, Field
class Card(BaseModel):
kind: Literal["card"]
last4: str
class Bank(BaseModel):
kind: Literal["bank"]
iban: str
class TaggedUnion(BaseModel): # a discriminated union: Pydantic emits oneOf + discriminator
payment: Annotated[Card | Bank, Field(discriminator="kind")]
class PlainUnion(BaseModel): # the same union without discriminator=: Pydantic emits anyOf
payment: Card | Bank
class FreeDict(BaseModel): # arbitrary keys: additionalProperties is a schema, not false
count_by_city: dict[str, int]
class Node(BaseModel): # recursion through $ref
name: str
children: list["Node"]
class Timestamp(BaseModel):
at: datetime # format: date-time
class Bounds(BaseModel):
score: float = Field(gt=0, le=10) # exclusiveMinimum + maximum
class LengthLimit(BaseModel):
name: str = Field(max_length=100) # maxLength: not in OpenAI's documented list
class WithDefault(BaseModel):
language: str = "en" # a default: optional in Pydantic's schema
captured: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
captured.append(json.loads(request.content))
return httpx.Response(200, json={"candidates": [{"content": {"role": "model", "parts": [{"text": "{}"}]},
"finishReason": "STOP"}]})
gem = genai.Client(api_key="test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))
def gemini_schema(model: type[BaseModel]) -> dict:
gem.models.generate_content(model="gemini-3.8-flash", contents="...", config=types.GenerateContentConfig(
response_mime_type="application/json", response_schema=model))
return captured[-1]["generationConfig"]["responseSchema"]
def gemini_json_schema(model: type[BaseModel]) -> dict:
"""The recommended route: standard JSON Schema, passed through as written."""
gem.models.generate_content(model="gemini-3.8-flash", contents="...", config=types.GenerateContentConfig(
response_mime_type="application/json", response_json_schema=model.model_json_schema()))
return captured[-1]["generationConfig"]["responseJsonSchema"]
def field_of(schema: dict) -> dict:
"""The interesting part: the single property (resolving a root $ref), minus titles."""
if "$ref" in schema and "properties" not in schema:
schema = schema["$defs"][schema["$ref"].split("/")[-1]]
name, prop = next(iter(schema["properties"].items())) if len(schema["properties"]) == 1 else \
list(schema["properties"].items())[-1]
prop = {k: v for k, v in prop.items() if k != "title"}
req = "required" if name in schema.get("required", []) else "NOT required"
return {"field": name, "schema": prop, "req": req}
def describe(get) -> str:
try:
f = field_of(get())
return f"{f['req']:12} {json.dumps(f['schema'], ensure_ascii=False)}"
except Exception as err: # some conversions fail before sending
return f"{type(err).__name__}: {str(err).splitlines()[0][:90]}"
for model in [TaggedUnion, PlainUnion, FreeDict, Node, Timestamp, Bounds, LengthLimit, WithDefault]:
print(f"\n===== {model.__name__} =====")
for label, get in [("pydantic", model.model_json_schema),
("openai", lambda m=model: to_strict_json_schema(m)),
("anthropic", lambda m=model: transform_schema(m)),
("gemini", lambda m=model: gemini_schema(m)),
("gemini-json", lambda m=model: gemini_json_schema(m))]:
line = describe(get)
print(f" {label:12}{line[:150]}{'...' if len(line) > 150 else ''}")===== TaggedUnion =====
pydantic required {"discriminator": {"mapping": {"bank": "#/$defs/Bank", "card": "#/$defs/Card"}, "propertyName": "kind"}, "oneOf": [{"$ref": "#/$defs/Card...
openai required {"discriminator": {"mapping": {"bank": "#/$defs/Bank", "card": "#/$defs/Card"}, "propertyName": "kind"}, "oneOf": [{"$ref": "#/$defs/Card...
anthropic required {"anyOf": [{"$ref": "#/$defs/Card"}, {"$ref": "#/$defs/Bank"}], "description": "{discriminator: {'mapping': {'bank': '#/$defs/Bank', 'car...
gemini ValidationError: 2 validation errors for Schema
gemini-json required {"discriminator": {"mapping": {"bank": "#/$defs/Bank", "card": "#/$defs/Card"}, "propertyName": "kind"}, "oneOf": [{"$ref": "#/$defs/Card...
===== PlainUnion =====
pydantic required {"anyOf": [{"$ref": "#/$defs/Card"}, {"$ref": "#/$defs/Bank"}]}
openai required {"anyOf": [{"$ref": "#/$defs/Card"}, {"$ref": "#/$defs/Bank"}]}
anthropic required {"anyOf": [{"$ref": "#/$defs/Card"}, {"$ref": "#/$defs/Bank"}]}
gemini required {"any_of": [{"properties": {"kind": {"enum": ["card"], "title": "Kind", "type": "STRING"}, "last4": {"title": "Last4", "type": "STRING"}}...
gemini-json required {"anyOf": [{"$ref": "#/$defs/Card"}, {"$ref": "#/$defs/Bank"}]}
===== FreeDict =====
pydantic required {"additionalProperties": {"type": "integer"}, "type": "object"}
openai required {"additionalProperties": {"type": "integer"}, "type": "object"}
anthropic required {"type": "object", "properties": {}, "additionalProperties": false}
gemini ValueError: additionalProperties is only supported in Gemini Enterprise Agent Platform mode, , not in
gemini-json required {"additionalProperties": {"type": "integer"}, "type": "object"}
===== Node =====
pydantic required {"items": {"$ref": "#/$defs/Node"}, "type": "array"}
openai required {"items": {"$ref": "#/$defs/Node"}, "type": "array"}
anthropic required {"type": "array", "items": {"$ref": "#/$defs/Node"}}
gemini required {"items": {}, "type": "ARRAY"}
gemini-json required {"items": {"$ref": "#/$defs/Node"}, "type": "array"}
===== Timestamp =====
pydantic required {"format": "date-time", "type": "string"}
openai required {"format": "date-time", "type": "string"}
anthropic required {"type": "string", "format": "date-time"}
gemini required {"format": "date-time", "type": "STRING"}
gemini-json required {"format": "date-time", "type": "string"}
===== Bounds =====
pydantic required {"exclusiveMinimum": 0, "maximum": 10, "type": "number"}
openai required {"exclusiveMinimum": 0, "maximum": 10, "type": "number"}
anthropic required {"type": "number", "description": "{exclusiveMinimum: 0, maximum: 10}"}
gemini ValidationError: 1 validation error for Schema
gemini-json required {"exclusiveMinimum": 0, "maximum": 10, "type": "number"}
===== LengthLimit =====
pydantic required {"maxLength": 100, "type": "string"}
openai required {"maxLength": 100, "type": "string"}
anthropic required {"type": "string", "description": "{maxLength: 100}"}
gemini required {"max_length": 100, "type": "STRING"}
gemini-json required {"maxLength": 100, "type": "string"}
===== WithDefault =====
pydantic NOT required {"default": "en", "type": "string"}
openai required {"default": "en", "type": "string"}
anthropic NOT required {"type": "string", "description": "{default: en}"}
gemini NOT required {"default": "en", "type": "STRING"}
gemini-json NOT required {"default": "en", "type": "string"}What each row means for you:
| Construct | OpenAI SDK | Anthropic SDK | Do this |
|---|---|---|---|
| Discriminated union | Sends oneOf + discriminator unchanged (not in the documented subset) |
Converts to anyOf; the discriminator goes into the description |
Plain union of tagged models |
| Plain union | anyOf |
anyOf |
Fine everywhere; keep it small |
dict[str, int] |
Keeps additionalProperties: {"type": "integer"}: the API requires false, so expect a 400 |
Silently replaces it with an empty object that forbids every key: the model can only return {} |
A list of {"key", "value"} objects |
Recursion (Node with children: list[Node]) |
Keeps the $ref (OpenAI supports recursion) |
Keeps it; the API rejects it (no recursive schemas) | Fixed depth, or a flat list with parent_id (5.4) |
datetime |
format: date-time |
format: date-time |
Fine; validate the range |
gt=0, le=10 |
Keeps exclusiveMinimum/maximum (supported) |
Moves both into the description; Pydantic enforces them afterwards | Use ge= (inclusive) for Gemini, or validate in Pydantic |
A length limit (max_length=100) |
Keeps maxLength, which is not in OpenAI's documented subset: the API may reject it, so keep it out of the schema |
Moves it into the description; Pydantic enforces it afterwards | A @field_validator, as Order does |
A default (language: str = "en") |
Makes it required and keeps default |
Keeps it optional; moves default into the description |
No defaults on model-filled fields (2.10) |
| Construct | google-genai response_schema=Model |
Gemini response_json_schema |
|---|---|---|
| Discriminated union | Raises ValidationError (discriminator is an extra field for its Schema) |
Sent as written (oneOf is read as anyOf) |
| Plain union | any_of, with the definitions inlined |
anyOf as written |
dict[str, int] |
Raises ValueError: "additionalProperties is only supported in Gemini Enterprise Agent Platform mode" |
Sent as written (Google documents additionalProperties as a boolean or a schema) |
Recursion (Node with children: list[Node]) |
Silently drops the recursion: items: {} |
Keeps the $ref; Google unrolls cycles to a limited depth, only inside non-required properties |
datetime |
format: date-time |
format: date-time |
gt=0, le=10 |
Raises: its Schema has minimum/maximum but no exclusiveMinimum |
Sent as written; exclusiveMinimum is not in Google's list, so test it |
A length limit (max_length=100) |
Sends max_length; Gemini silently does not enforce it |
Sent as maxLength; silently not enforced |
A default (language: str = "en") |
Keeps it optional, with default |
Sent as written; default is not in Google's list |
The silent ones are the dangerous ones. Anthropic's dict becomes an object that can never hold a key, Gemini's response_schema conversion turns a recursive list into a list of anything, and Gemini accepts a maxLength and then ignores it; none of them raises anything. The gemini-json route avoids the first two (it sends what Pydantic wrote), which is one reason Google steers you towards it (3.4). A schema linter (4.6) or a test that inspects the transformed schema catches them before production does.
2.9 Try it: what each SDK sends#
Now the whole Order model, through each SDK's parse helper, captured on the wire. Each SDK gets an in-memory mock transport that records the request body and returns a minimal valid reply, so nothing leaves the machine (layer 5). Gemini is captured twice, once per schema field, because the two routes send different things:
# s2_9_schema_transforms.py
"""One Pydantic model, and the schema each SDK actually puts on the wire (layer 5: nothing is sent).
Each SDK gets an in-memory mock transport. The handler records the request body and
returns a minimal valid reply, so the call completes. We then print the schema part of
each body, one line per property, next to Pydantic's own model_json_schema().
"""
import json
import anthropic
import httpx # google-genai uses httpx
import httpx2 # openai 3.x and anthropic 2.x use httpx2
from google import genai
from google.genai import types
from openai import OpenAI
from order_model import Order
ORDER_JSON = ('{"customer": "Ana Lima", "order_date": "2026-11-02", "priority": "normal", '
'"channel": "email", "gift_message": null, "discount_code": null, '
'"items": [{"sku": "ABC-1234", "quantity": 2}]}')
bodies: dict[str, dict] = {}
def recorder(name: str, reply: dict, lib):
def handler(request):
bodies[name] = json.loads(request.content)
return lib.Response(200, json=reply)
return handler
# Minimal replies, shaped like each API's documented response (only what the SDKs read)
OPENAI_REPLY = {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "output": [{"type": "message", "id": "msg_1", "role": "assistant",
"status": "completed", "content": [{"type": "output_text", "text": ORDER_JSON, "annotations": []}]}]}
ANTHROPIC_REPLY = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": ORDER_JSON}], "stop_reason": "end_turn",
"usage": {"input_tokens": 1, "output_tokens": 1}}
GEMINI_REPLY = {"candidates": [{"content": {"role": "model", "parts": [{"text": ORDER_JSON}]},
"finishReason": "STOP"}]}
oai = OpenAI(api_key="sk-test", http_client=httpx2.Client(
transport=httpx2.MockTransport(recorder("openai", OPENAI_REPLY, httpx2))))
oai.responses.parse(model="gpt-6-luna", input="...", text_format=Order)
claude = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(
transport=httpx2.MockTransport(recorder("anthropic", ANTHROPIC_REPLY, httpx2))))
claude.messages.parse(model="claude-haiku-5-5", max_tokens=1000,
messages=[{"role": "user", "content": "..."}], output_format=Order)
gem = genai.Client(api_key="test", http_options=types.HttpOptions(httpx_client=httpx.Client(
transport=httpx.MockTransport(recorder("gemini", GEMINI_REPLY, httpx)))))
gem.models.generate_content(model="gemini-3.8-flash", contents="...", config=types.GenerateContentConfig(
response_mime_type="application/json", response_schema=Order))
via_response_schema = bodies["gemini"] # the handler overwrites this key on the next call
gem.models.generate_content(model="gemini-3.8-flash", contents="...", config=types.GenerateContentConfig(
response_mime_type="application/json", response_json_schema=Order.model_json_schema()))
via_json_schema = bodies["gemini"]
schemas = {
"pydantic": Order.model_json_schema(),
"openai": bodies["openai"]["text"]["format"]["schema"],
"anthropic": bodies["anthropic"]["output_config"]["format"]["schema"],
"gemini": via_response_schema["generationConfig"]["responseSchema"],
}
print("OpenAI text.format envelope:",
{k: v for k, v in bodies["openai"]["text"]["format"].items() if k != "schema"})
print("Anthropic output_config.format envelope:",
{k: v for k, v in bodies["anthropic"]["output_config"]["format"].items() if k != "schema"})
print("Gemini (response_schema=Order) generationConfig keys:", list(via_response_schema["generationConfig"]))
print("Gemini (response_json_schema=...) generationConfig keys:", list(via_json_schema["generationConfig"]))
def compact(schema: dict) -> str:
drop = {"title"} # titles are noise here; every SDK keeps them
return json.dumps({k: v for k, v in schema.items() if k not in drop}, ensure_ascii=False)
def show(name: str, schema: dict) -> None:
print(f"\n===== {name} =====")
extras = {k: v for k, v in schema.items() if k not in ("properties", "$defs", "title")}
print("root:", json.dumps(extras, ensure_ascii=False))
for key, prop in schema["properties"].items():
print(f" {key:14} {compact(prop)}")
for def_name, d in schema.get("$defs", {}).items():
print(f" $defs.{def_name}: " + (compact(d) if "properties" not in d else ""))
for key, prop in d.get("properties", {}).items():
print(f" {key:10} {compact(prop)}")
if "properties" in d:
rest = {k: v for k, v in d.items() if k not in ("properties", "title")}
print(f" (object) {json.dumps(rest)}")
for name, schema in schemas.items():
show(name, schema)
sent = via_json_schema["generationConfig"]["responseJsonSchema"]
print("\nresponse_json_schema: sent exactly as Pydantic wrote it?", sent == Order.model_json_schema())OpenAI text.format envelope: {'type': 'json_schema', 'strict': True, 'name': 'Order'}
Anthropic output_config.format envelope: {'type': 'json_schema'}
Gemini (response_schema=Order) generationConfig keys: ['responseMimeType', 'responseSchema']
Gemini (response_json_schema=...) generationConfig keys: ['responseMimeType', 'responseJsonSchema']
===== pydantic =====
root: {"description": "A customer order extracted from an email.", "required": ["customer", "order_date", "priority", "channel", "gift_message", "items"], "type": "object"}
customer {"description": "Customer's full name (at most 100 characters)", "type": "string"}
order_date {"format": "date", "type": "string"}
priority {"$ref": "#/$defs/Priority"}
channel {"enum": ["email", "phone", "web"], "type": "string"}
gift_message {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "The gift message, or null if there is none"}
discount_code {"anyOf": [{"type": "string"}, {"type": "null"}], "default": null}
items {"items": {"$ref": "#/$defs/LineItem"}, "maxItems": 20, "minItems": 1, "type": "array"}
$defs.LineItem:
sku {"description": "Stock code, e.g. ABC-1234", "type": "string"}
quantity {"maximum": 999, "minimum": 1, "type": "integer"}
(object) {"required": ["sku", "quantity"], "type": "object"}
$defs.Priority: {"enum": ["low", "normal", "urgent"], "type": "string"}
===== openai =====
root: {"description": "A customer order extracted from an email.", "required": ["customer", "order_date", "priority", "channel", "gift_message", "discount_code", "items"], "type": "object", "additionalProperties": false}
customer {"description": "Customer's full name (at most 100 characters)", "type": "string"}
order_date {"format": "date", "type": "string"}
priority {"$ref": "#/$defs/Priority"}
channel {"enum": ["email", "phone", "web"], "type": "string"}
gift_message {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "The gift message, or null if there is none"}
discount_code {"anyOf": [{"type": "string"}, {"type": "null"}]}
items {"items": {"$ref": "#/$defs/LineItem"}, "maxItems": 20, "minItems": 1, "type": "array"}
$defs.LineItem:
sku {"description": "Stock code, e.g. ABC-1234", "type": "string"}
quantity {"maximum": 999, "minimum": 1, "type": "integer"}
(object) {"required": ["sku", "quantity"], "type": "object", "additionalProperties": false}
$defs.Priority: {"enum": ["low", "normal", "urgent"], "type": "string"}
===== anthropic =====
root: {"type": "object", "description": "A customer order extracted from an email.", "additionalProperties": false, "required": ["customer", "order_date", "priority", "channel", "gift_message", "items"]}
customer {"type": "string", "description": "Customer's full name (at most 100 characters)"}
order_date {"type": "string", "format": "date"}
priority {"$ref": "#/$defs/Priority"}
channel {"type": "string", "enum": ["email", "phone", "web"]}
gift_message {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "The gift message, or null if there is none"}
discount_code {"anyOf": [{"type": "string"}, {"type": "null"}], "description": "{default: None}"}
items {"type": "array", "items": {"$ref": "#/$defs/LineItem"}, "minItems": 1, "description": "{maxItems: 20}"}
$defs.LineItem:
sku {"type": "string", "description": "Stock code, e.g. ABC-1234"}
quantity {"type": "integer", "description": "{maximum: 999, minimum: 1}"}
(object) {"type": "object", "additionalProperties": false, "required": ["sku", "quantity"]}
$defs.Priority: {"type": "string", "enum": ["low", "normal", "urgent"]}
===== gemini =====
root: {"description": "A customer order extracted from an email.", "property_ordering": ["customer", "order_date", "priority", "channel", "gift_message", "discount_code", "items"], "required": ["customer", "order_date", "priority", "channel", "gift_message", "items"], "type": "OBJECT"}
customer {"description": "Customer's full name (at most 100 characters)", "type": "STRING"}
order_date {"format": "date", "type": "STRING"}
priority {"enum": ["low", "normal", "urgent"], "type": "STRING"}
channel {"enum": ["email", "phone", "web"], "type": "STRING"}
gift_message {"description": "The gift message, or null if there is none", "nullable": true, "type": "STRING"}
discount_code {"nullable": true, "type": "STRING"}
items {"items": {"properties": {"sku": {"description": "Stock code, e.g. ABC-1234", "title": "Sku", "type": "STRING"}, "quantity": {"maximum": 999.0, "minimum": 1.0, "title": "Quantity", "type": "INTEGER"}}, "property_ordering": ["sku", "quantity"], "required": ["sku", "quantity"], "title": "LineItem", "type": "OBJECT"}, "max_items": 20, "min_items": 1, "type": "ARRAY"}
response_json_schema: sent exactly as Pydantic wrote it? Trueflowchart LR
M["Pydantic model"] --> J["model_json_schema()"]
J --> O["OpenAI SDK<br/>strict transform"]
J --> A["Anthropic SDK<br/>transform_schema()"]
M --> G["google-genai<br/>converts to its Schema type"]
J --> GJ["response_json_schema<br/>sent as is"]
O --> W1["text.format / response_format<br/>strict: true"]
A --> W2["output_config.format"]
G --> W3["responseSchema"]
GJ --> W4["responseJsonSchema"]
W1 --> V["Reply text"]
W2 --> V
W3 --> V
W4 --> V
V --> PV["Validated against the ORIGINAL<br/>Pydantic model, with all its rules"]Reading the four versions side by side:
- OpenAI (
responses.parse, the same transform aschat.completions.parse): addsadditionalProperties: falseto every object, lists every property inrequired(includingdiscount_code), drops theNonedefault, and wraps it all in{"type": "json_schema", "strict": true, "name": "Order"}; the name is the class name. Everything else, includingminimum/maximumandminItems/maxItems(all three are in OpenAI's documented list), passes through.Ordercarries nomaxLengthfor exactly this reason: that keyword is not in OpenAI's documented subset (2.1, 4.2). - Anthropic (
messages.parse, via the publictransform_schema): addsadditionalProperties: false, keeps Pydantic'srequiredlist (sodiscount_codestays optional), and moves every constraint it doesn't support into the field's description as text, such as"{maxItems: 20}"and"{maximum: 999, minimum: 1}"(amax_lengthon a string would appear the same way, as in theLengthLimitrow of 2.8), so the model "might" follow them (the SDK source's own word). Anthropic's docs describe the same five steps: remove unsupported constraints, add them to descriptions, addadditionalProperties: false, filter string formats to the supported list, and "Validate responses against your original schema and all its constraints". The envelope is just{"type": "json_schema", "schema": ...}, sent asoutput_config.format. - Gemini (
response_schema=Order): converts to Gemini's own OpenAPI-styleSchema: upper-case types ("STRING","OBJECT"),$defsinlined (thePriorityenum appears in place),nullable: trueinstead of anullunion, and aproperty_orderinglist on every object fixing the output key order (4.4). A stringmax_lengthwould be sent, and silently not enforced. Note the snake_case keys insideresponseSchema(property_ordering,max_items): that is how the SDK serializes itsSchematype. Google's structured-output page itself refers to "snake_case variants" of keywords such asminLength, and the protobuf JSON specification (which Google's APIs generally follow) requires parsers to accept both the lowerCamelCase name and the original proto field name, but the Gemini reference says nothing explicit about it and this lesson has not sent a snake_caseresponseSchemato the hosted API: if a request is rejected, switch to camelCase. - Gemini with
response_json_schema=Order.model_json_schema()(the last line of the output confirms it): the standard JSON Schema goes asresponseJsonSchema, byte for byte what Pydantic wrote,default: nullandtitles included. This is the route Google's reference steers towards (3.4), and it is the one to use when the SDK's conversion rejects or mangles a construct, as in 2.8. Because nothing is rewritten, you must keep the schema inside Google's documented keywords yourself (4.4).
One more detail from the source: Anthropic's transform writes leftover keywords with Python's repr, so a None default appears in the description as {default: None} rather than JSON's null. It's harmless, and another reason not to put defaults on model-filled fields.
What this means for you as an engineer: the schema the provider enforces is not your Pydantic model; it's a looser version of it. Every rule that didn't survive the transform (Anthropic's numeric bounds, Gemini's string lengths, your @field_validators) is enforced only when you validate the reply against the original model. The helpers do that for you; with create() you do it yourself (Part 6).
2.10 Default values, and why strict modes forbid them#
A Pydantic default means "if the key is missing, use this". Strict modes take that choice away:
- On OpenAI, every key is required, so the model must write a value for it and the default never applies. Worse, the model may copy the default from the schema (
"default": "en"is right there) whether or not it fits the document.defaultis not in OpenAI's documented list of supported keywords; the SDK passes non-Nonedefaults through anyway. - On Anthropic,
defaultis documented as supported, but the SDK's transform moves it into the description, and the field stays optional, so it counts against the 24-optional-parameter limit (4.3). - On Gemini, a default is sent and the field stays optional.
So a default on a field the model fills is either ignored or ambiguous. The rule: no defaults on model-filled fields. If a value can be missing, make it X | None with a description saying when to use null, and apply your default in code after validation (lang = result.language or "en"). Fields your code fills (an ID, a timestamp) don't belong in the model's schema at all: build them into a separate class, or exclude them.
Part 3: Every provider, completely#
Reference
This part is the reference for each API's structured-output surface: the raw request shape, the SDK helper, where the parsed object appears, and how the non-answers (refusals, truncation) show up. Everything was checked against the official docs and the SDK versions named in Setup, as of November 2026.
3.1 OpenAI Responses#
Raw request. Put the schema in text.format:
| Field | Value |
|---|---|
type |
"json_schema" (or "json_object" for JSON mode, "text" for plain text) |
name |
Required. "Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64" |
schema |
The JSON Schema (strict rules in 4.2) |
strict |
true to enforce the schema. It defaults to false, so always set it |
description |
Optional: "used by the model to determine how to respond in the format" |
SDK helper. client.responses.parse(..., text_format=Order) builds that text.format from your Pydantic class (with the strict transform from 2.9), sends the request, and parses the reply. The result is a ParsedResponse:
response.output_parsedis yourOrder, parsed from the final-answer message'soutput_text(a message with nophase, orphase: "final_answer").response.statusis"completed", or"incomplete"withresponse.incomplete_details.reasonset to one of the SDK's literals:"max_output_tokens","content_filter","max_messages"or"steered".- A refusal is not an error and not text. It arrives as a content item
{"type": "refusal", "refusal": "I'm sorry, I cannot assist with that request."}inside the message, withstatus: "completed". OpenAI: "Since a refusal does not necessarily follow the schema you have supplied... the API response will include a new field calledrefusal." With a refusal,output_parsedisNone.
responses.stream(..., text_format=Order) is the streaming form (Part 8).
3.2 OpenAI Chat Completions#
Raw request. response_format={"type": "json_schema", "json_schema": {"name": ..., "schema": ..., "strict": true, "description": ...}}, with the same name rule and strict defaulting to false. Note the extra json_schema level, which text.format in Responses doesn't have: it's the most common copy-paste bug between the two APIs. Here are the two request fragments for the same class, captured on the wire (layer 5: mock transports, nothing is sent; the schema is elided so the envelopes are easy to compare):
# s3_2_request_shapes.py
"""The Responses and Chat Completions request shapes side by side, captured on the wire (layer 5).
Mock transports record what the openai SDK would send for the same Pydantic class; nothing leaves the machine.
The schema itself is elided ("{...}") so the two envelopes are easy to compare.
"""
import json
import httpx2
from openai import OpenAI
from order_model import Order
bodies: dict[str, dict] = {}
def mock(name: str, reply: dict) -> OpenAI:
def handler(request: httpx2.Request) -> httpx2.Response:
bodies[name] = json.loads(request.content)
return httpx2.Response(200, json=reply)
return OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
ORDER = ('{"customer": "Ana Lima", "order_date": "2026-11-02", "priority": "normal", "channel": "email", '
'"gift_message": null, "discount_code": null, "items": [{"sku": "ABC-1234", "quantity": 2}]}')
responses_reply = {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-6-luna", "status": "completed",
"output": [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": ORDER, "annotations": []}]}]}
chat_reply = {"id": "c1", "object": "chat.completion", "created": 0, "model": "gpt-6-luna",
"choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": ORDER, "refusal": None}}]}
mock("responses", responses_reply).responses.parse(model="gpt-6-luna", input="...", text_format=Order)
mock("chat", chat_reply).chat.completions.parse(
model="gpt-6-luna", messages=[{"role": "user", "content": "..."}], response_format=Order)
def elide(node):
"""Replace every 'schema' value with {...} so only the envelope is left."""
if isinstance(node, dict):
return {k: ("{...}" if k == "schema" else elide(v)) for k, v in node.items()}
return node
print("Responses API: ", json.dumps(elide({"text": bodies["responses"]["text"]})))
print("Chat Completions: ", json.dumps(elide({"response_format": bodies["chat"]["response_format"]})))Responses API: {"text": {"format": {"type": "json_schema", "strict": true, "name": "Order", "schema": "{...}"}}}
Chat Completions: {"response_format": {"type": "json_schema", "json_schema": {"schema": "{...}", "name": "Order", "strict": true}}}In Responses, format sits directly under text, with name, strict and schema beside type. In Chat Completions, response_format holds type and one more object, json_schema, which holds name, strict and schema. (OpenRouter's Responses-compatible API takes the first shape and its Chat Completions API the second.)
SDK helper. client.chat.completions.parse(..., response_format=Order) returns a ParsedChatCompletion; read completion.choices[0].message:
message.parsed: yourOrder, orNonewhen the model refused.message.refusal: the refusal text, orNone.- Two exceptions, raised by the helper (not by the API) when it can't parse:
openai.LengthFinishReasonErrorwhenfinish_reason == "length"(the message is "Could not parse response content as the length limit was reached", anderr.completioncarries the completion, includingusage, for your logs), andopenai.ContentFilterFinishReasonErrorwhenfinish_reason == "content_filter". Both subclassopenai.OpenAIError, notAPIStatusError: there was no HTTP error. - Invalid content (rare under strict mode, common on endpoints that ignore it) raises Pydantic's
ValidationError.
client.chat.completions.stream(..., response_format=Order) streams with partial parsing; OpenAI's guide still shows it under client.beta.chat.completions.stream, and both names exist in SDK 3.42.1. The Chat Completions shape matters beyond OpenAI: it's what OpenRouter, Gemini's OpenAI-compatibility endpoint (which documents client.beta.chat.completions.parse(... response_format=CalendarEvent)), Ollama and most other "OpenAI-compatible" servers speak.
3.3 Anthropic Messages#
Raw request. output_config={"format": {"type": "json_schema", "schema": {...}}}. Structured outputs are generally available, need no beta header, and "are available on every model" (Anthropic's availability note); they are not available on Managed Agents. type: "json_schema" is the only format: there is no JSON mode.
SDK helper. client.messages.parse(..., output_format=Order) transforms the schema with transform_schema (2.9), sends it as output_config.format (merging it with any other output_config keys you pass), and validates the reply against the original model:
message.parsed_outputis yourOrder, taken from the first text block.message.stop_reasonis"end_turn"for a complete answer;"max_tokens"or"model_context_window_exceeded"means truncated;"refusal"means the model declined.- A refusal is "a successful HTTP 200 response with
stop_reason: "refusal"", withstop_detailsof{"type": "refusal", "category": ..., "explanation": ...}. The categories arecyber,bio,frontier_llm,reasoning_extraction,general_harmsornull, and Anthropic warns thatexplanation"is not stable, so display it rather than parse it". "The output might not match your schema because the refusal message takes precedence."
Pass a type, not a dict: output_format={"type": "object"} raises TypeError: output_format must be a type; pass a schema dict as output_config={'format': ...} instead. Any type that works with pydantic.TypeAdapter is accepted, so output_format=list[LineItem] also works on the SDK side.
Strict tools. "Setting strict: true on a tool definition guarantees Claude's tool inputs match your JSON Schema by constraining the model's token sampling." It's a top-level property of the tool, "alongside name, description, and input_schema". The same schema rules and the same complexity limits apply (4.3), and remember the forced-tool_choice 400 on Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1 (1.5).
What it doesn't combine with. As of November 2026:
- Citations: "The API returns a 400 error if citations are enabled with
output_config.format." - Prefill: "Prefilling is incompatible with JSON outputs" (prefill is gone on current models anyway, lesson 03.2, 4.2).
- Thinking works: "Grammars apply only to Claude's direct output, not to tool use calls, tool results, or thinking tags." So a thinking block may precede the JSON text block: select the text block by
type. One warning: asking for step-by-step reasoning inside a schema property "might lead to areasoning_extractionrefusal" (5.2). - Batches, token counting and streaming all work with structured outputs (batches at the usual 50% discount; lesson 03.9).
3.7 Try it free: the OpenAI helpers on the local stand-in#
Three of the helpers can run against the free local stack, because Ollama serves the OpenAI formats: responses.parse, chat.completions.parse, and the OpenRouter-style Chat Completions call. The others cannot. Gemini has no local stand-in (Ollama does not speak Gemini's API), and Anthropic's output_config.format is accepted and ignored by Ollama's Anthropic endpoint, so messages.parse(output_format=...) has nothing to enforce the schema locally. Those four paths, Anthropic and the three Gemini routes, run only in the hosted sample of 3.8. Here are the three that run:
# s3_7_local_all_paths.py
"""Try it free: the OpenAI-shaped structured-output helpers, against the local stand-in.
All calls go to Ollama (localhost:11434). Gemini and Anthropic output_config have no local
stand-in: see the hosted sample in 3.8.
"""
from openai import OpenAI
from pydantic import ValidationError
from order_model import Order
EMAIL = ("From: Ana Lima\nSent: 2 November 2026\n\nHi, please send 2 x ABC-1234 and 1 x XYZ-0042 "
"as soon as possible, it's urgent. No gift message needed. Thanks!")
INSTRUCTIONS = "Extract the order from the customer's email."
oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
router = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # OpenRouter-shaped code
def openai_responses() -> Order | None:
r = oai.responses.parse(model="gpt-6-luna", instructions=INSTRUCTIONS, input=EMAIL,
text_format=Order, max_output_tokens=400)
print(f" status={r.status}")
return r.output_parsed
def openai_chat() -> Order | None:
c = oai.chat.completions.parse(model="gpt-6-luna", response_format=Order, max_completion_tokens=400,
messages=[{"role": "system", "content": INSTRUCTIONS},
{"role": "user", "content": EMAIL}])
print(f" finish_reason={c.choices[0].finish_reason} refusal={c.choices[0].message.refusal}")
return c.choices[0].message.parsed
def openrouter_chat() -> Order | None:
c = router.chat.completions.parse(model="openai/gpt-6-luna", response_format=Order, max_completion_tokens=400,
messages=[{"role": "system", "content": INSTRUCTIONS},
{"role": "user", "content": EMAIL}])
print(f" finish_reason={c.choices[0].finish_reason}")
return c.choices[0].message.parsed
for name, call in [("OpenAI Responses: responses.parse(text_format=Order)", openai_responses),
("OpenAI Chat: chat.completions.parse(response_format=Order)", openai_chat),
("OpenRouter-style: chat.completions.parse", openrouter_chat)]:
print(name)
try:
order = call()
print(f" -> {order!r}" if order else " -> no parsed object")
except ValidationError as err: # valid-looking JSON that broke a rule, or no JSON at all
first = err.errors()[0]
print(f" -> ValidationError ({err.error_count()} errors), first: {first['loc']}: {first['msg']}")OpenAI Responses: responses.parse(text_format=Order)
status=completed
-> Order(customer='Ana Lima', order_date=datetime.date(2026, 11, 2), priority=<Priority.URGENT: 'urgent'>, channel='email', gift_message=None, discount_code=None, items=[LineItem(sku='ABC-1234', quantity=2), LineItem(sku='XYZ-0042', quantity=1)])
OpenAI Chat: chat.completions.parse(response_format=Order)
finish_reason=stop refusal=None
-> Order(customer='Ana Lima', order_date=datetime.date(2195, 11, 24), priority=<Priority.URGENT: 'urgent'>, channel='web', gift_message=None, discount_code=None, items=[LineItem(sku='ABC-1234', quantity=2), LineItem(sku='XYZ-0042', quantity=1)])
OpenRouter-style: chat.completions.parse
finish_reason=stop
-> Order(customer='Ana Lima', order_date=datetime.date(2026, 11, 2), priority=<Priority.URGENT: 'urgent'>, channel='email', gift_message='', discount_code='ABC-1234', items=[LineItem(sku='XYZ-0042', quantity=1)])This is a tiny 0.5B model, and its semantic mistakes are useful. Under constrained decoding every enforced reply had the right shape, and the content still wobbles: a Chat reply dated 2195-11-24 on the web channel, and the OpenRouter-style call writing an SKU into discount_code and dropping a line item. A hosted model would extract this email correctly, but the lesson holds at any size: schema-valid is not the same as right. (Each run of a 0.5B model differs; yours will wobble in other places.)
What the stand-in actually enforces, from probes on Ollama 0.32.5 (ask for a poem, attach a schema, see whether JSON comes back):
| Path | Schema enforced locally? |
|---|---|
OpenAI Responses text.format json_schema / responses.parse (Ollama) |
Yes |
OpenAI Responses text.format json_object (Ollama) |
No (accepted, ignored: 1.3) |
OpenAI Chat response_format json_schema / json_object (Ollama) |
Yes |
Anthropic output_config.format on Ollama (:11434) |
No: accepted and ignored, so messages.parse only succeeds when the model happens to write valid JSON. Hosted-only |
Strict tools and tool_choice (Ollama) |
No (1.5) |
| Path | Schema enforced locally? |
|---|---|
Gemini (response_json_schema, response_schema, enum mode, Interactions response_format) |
Hosted-only: no local stand-in |
Ollama's grammar engine also has its own schema subset. A pattern such as ^[A-Z]{3}-\d{4}$ made it fail with 400 ... Failed to initialize samplers: failed to parse grammar, which is why order_model.py checks the SKU in a validator rather than with Field(pattern=...).
3.8 The same extraction on all four hosted providers#
The production-shaped version, against the real APIs (keys needed). Each function checks its provider's "did it finish?" signal before trusting the object, and the loop catches the ValidationError the parse helpers raise on truncated or invalid output:
# s3_8_hosted_extraction.py
"""The same extraction on all four hosted providers, with each one's native structured output.
Needs OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY and OPENROUTER_API_KEY in .env.
Each function checks the provider's "did it finish?" signal before trusting the parsed object.
"""
import os
import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI
from pydantic import ValidationError
from order_model import Order
load_dotenv()
EMAIL = ("From: Ana Lima\nSent: 2 November 2026\n\nHi, please send 2 x ABC-1234 and 1 x XYZ-0042 "
"as soon as possible, it's urgent. No gift message needed. Thanks!")
INSTRUCTIONS = "Extract the order from the customer's email."
def openai_order(client: OpenAI) -> Order | None:
response = client.responses.parse(
model="gpt-6-luna", instructions=INSTRUCTIONS, input=EMAIL,
text_format=Order, max_output_tokens=2000, reasoning={"effort": "none"})
for item in response.output: # a refusal is a content item, not an error
if item.type == "message":
for part in item.content:
if part.type == "refusal":
print(" OpenAI refused:", part.refusal)
return None
print(f" OpenAI: status={response.status} usage={response.usage.input_tokens}+{response.usage.output_tokens}")
return response.output_parsed
def anthropic_order(client: anthropic.Anthropic) -> Order | None:
message = client.messages.parse(
model="claude-haiku-5-5", max_tokens=2000, system=INSTRUCTIONS,
messages=[{"role": "user", "content": EMAIL}], output_format=Order)
print(f" Anthropic: stop_reason={message.stop_reason} "
f"usage={message.usage.input_tokens}+{message.usage.output_tokens}")
return message.parsed_output if message.stop_reason == "end_turn" else None
def gemini_order(client: genai.Client) -> Order | None:
# response_json_schema is Google's recommended field: standard JSON Schema in, JSON text out.
# (response_schema=Order would give you response.parsed, but through the SDK's own conversion: 3.4)
response = client.models.generate_content(
model="gemini-3.8-flash", contents=EMAIL,
config=types.GenerateContentConfig(
system_instruction=INSTRUCTIONS, max_output_tokens=2000,
response_mime_type="application/json", response_json_schema=Order.model_json_schema()))
candidate = response.candidates[0] if response.candidates else None
print(f" Gemini: finish_reason={candidate.finish_reason if candidate else None} "
f"block_reason={response.prompt_feedback.block_reason if response.prompt_feedback else None}")
if not candidate or candidate.finish_reason != types.FinishReason.STOP: # blocked, truncated, ...
return None
return Order.model_validate_json(response.text or "") # raises ValidationError if invalid
def gemini_interactions_order(client: genai.Client) -> Order | None:
interaction = client.interactions.create(
model="gemini-3.8-flash", system_instruction=INSTRUCTIONS, input=EMAIL, store=False,
generation_config={"max_output_tokens": 2000},
response_format={"type": "text", "mime_type": "application/json", "schema": Order.model_json_schema()})
print(f" Gemini Interactions: status={interaction.status}")
if interaction.status != "completed":
return None
return Order.model_validate_json(interaction.output_text or "") # no parse helper here
def openrouter_order(client: OpenAI) -> Order | None:
completion = client.chat.completions.parse(
model="google/gemini-3.8-flash", response_format=Order, max_completion_tokens=2000,
messages=[{"role": "system", "content": INSTRUCTIONS}, {"role": "user", "content": EMAIL}],
# OpenRouter-only field: only route to endpoints that support every parameter we send
extra_body={"provider": {"require_parameters": True}})
choice = completion.choices[0]
cost = (completion.usage.model_extra or {}).get("cost") if completion.usage else None
print(f" OpenRouter: finish_reason={choice.finish_reason} refusal={choice.message.refusal} cost={cost}")
return choice.message.parsed
def openrouter_responses_order(client: OpenAI) -> Order | None:
response = client.responses.parse(
model="openai/gpt-6-luna", instructions=INSTRUCTIONS, input=EMAIL,
text_format=Order, max_output_tokens=2000,
# OpenRouter-only fields: strict routing, and repair of malformed JSON (non-streaming only)
extra_body={"provider": {"require_parameters": True}, "plugins": [{"id": "response-healing"}]})
print(f" OpenRouter Responses: status={response.status}")
return response.output_parsed if response.status == "completed" else None
openai_client = OpenAI()
anthropic_client = anthropic.Anthropic()
gemini_client = genai.Client()
openrouter_client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
default_headers={"HTTP-Referer": "https://example.com/orders-demo", "X-OpenRouter-Title": "Orders demo"},
)
for name, run in [("OpenAI", lambda: openai_order(openai_client)),
("Anthropic", lambda: anthropic_order(anthropic_client)),
("Gemini", lambda: gemini_order(gemini_client)),
("Gemini Interactions", lambda: gemini_interactions_order(gemini_client)),
("OpenRouter", lambda: openrouter_order(openrouter_client)),
("OpenRouter Responses", lambda: openrouter_responses_order(openrouter_client))]:
try:
order = run()
except ValidationError as err: # parse helpers raise this on truncated or invalid JSON
print(f" {name}: ValidationError: {err.errors()[0]['msg']}")
continue
print(f" {name} ->", order.model_dump(mode="json") if order else None) OpenAI: status=completed usage=412+96
OpenAI -> {'customer': 'Ana Lima', 'order_date': '2026-11-02', 'priority': 'urgent', 'channel': 'email', 'gift_message': None, 'discount_code': None, 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
Anthropic: stop_reason=end_turn usage=598+102
Anthropic -> {'customer': 'Ana Lima', 'order_date': '2026-11-02', 'priority': 'urgent', 'channel': 'email', 'gift_message': None, 'discount_code': None, 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
Gemini: finish_reason=FinishReason.STOP block_reason=None
Gemini -> {'customer': 'Ana Lima', 'order_date': '2026-11-02', 'priority': 'urgent', 'channel': 'email', 'gift_message': None, 'discount_code': None, 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
Gemini Interactions: status=completed
Gemini Interactions -> {'customer': 'Ana Lima', 'order_date': '2026-11-02', 'priority': 'urgent', 'channel': 'email', 'gift_message': None, 'discount_code': None, 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
OpenRouter: finish_reason=stop refusal=None cost=0.000284
OpenRouter -> {'customer': 'Ana Lima', 'order_date': '2026-11-02', 'priority': 'urgent', 'channel': 'email', 'gift_message': None, 'discount_code': None, 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
OpenRouter Responses: status=completed
OpenRouter Responses -> {'customer': 'Ana Lima', 'order_date': '2026-11-02', 'priority': 'urgent', 'channel': 'email', 'gift_message': None, 'discount_code': None, 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}Notes on the sample:
reasoning={"effort": "none"}ongpt-6-lunakeeps extraction fast and cheap; current models think by default, so if you do want reasoning, leave room inmax_output_tokens(02.8, 8.2). The Claude call leaves 2,000 tokens of room for the same reason.- The input token counts include the schema. The
Orderschema is a few hundred tokens by itself, and Anthropic adds a system prompt for structured output (Part 11). Orderis inside OpenAI's documented strict subset. It has nomaxLength(the length rule is a validator, 2.1), no non-Nonedefaults and nooneOf, so the schemaresponses.parsebuilds uses only listed keywords:format,enum,anyOfwithnull,minimum/maximumandminItems/maxItems. Whether OpenAI accepts a keyword it doesn't document is untested here, which is why the model avoids them.- Gemini uses
response_json_schemaandmodel_validate_json, with an explicitfinish_reasoncheck first, as 3.4 recommends. The.parsedconvenience (response_schema=Order) is described in 3.4. - Each sample checks a different signal, because each provider reports completion differently:
status,stop_reason,finish_reasonplusprompt_feedback,statusagain,finish_reasonplusrefusal. Part 6 turns them into one outcome type. - The OpenRouter Responses call routes to an OpenAI model on purpose. OpenRouter hands your schema to whichever provider serves the request, and the strict transform keeps
minimum,maximumandmaxItems, which are inside OpenAI's and Gemini's subsets but outside Anthropic's (4.5). To reach Claude, send a schema that passeslint_anthropic(4.6). - The OpenRouter calls send
require_parameters(and, on the Responses call,response-healing) throughextra_body, because they are OpenRouter-only fields; the cost arrives inusage.model_extra["cost"](lesson 03.7).
Against the stand-in, only part of this sample can run, and the output above is illustrative. The OpenAI and OpenRouter-shaped calls ran end to end and returned orders that passed validation (one OpenRouter-style reply carried junk text in gift_message, which is a 0.5B model's doing). The Anthropic call raised ValidationError on Ollama, because Ollama ignores output_config.format (3.7), so it is hosted-only. The two Gemini calls are hosted-only too: Ollama doesn't speak Gemini's API (03.1, 12.4).
What later samples leave out: the .env loading and attribution headers shown here, the outcome checks of Part 6 (Part 8 and 9 samples use the parse helpers for brevity and treat any ValidationError as "invalid"; production code uses extract() from Part 7), and per-call usage logging (lesson 03.10). The timeouts and retries the SDKs apply by default are lesson 03.8's subject.
3.9 When the helpers fail#
The helpers behave well on a clean reply and differently from each other on everything else. Same four replies to every helper, from mock servers (layer 3: the fixtures follow each provider's documented response shape):
# s3_9_helper_failures.py
"""What each SDK parse helper does when the reply is NOT a clean object, on MOCK servers.
Same four replies everywhere: clean JSON, JSON cut off by the token limit, a refusal, and
valid JSON with a value outside the schema. Fixtures follow each provider's documented shape.
"""
from typing import Literal
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from pydantic import BaseModel
class Refund(BaseModel):
amount: float
currency: Literal["GBP", "EUR", "USD"]
CLEAN, CUT, WRONG = '{"amount": 42.5, "currency": "GBP"}', '{"amount": 42.5, "curr', '{"amount": 42.5, "currency": "gbp"}'
REFUSAL = "I'm sorry, I can't help with that."
def replies(fixtures: list[dict], lib):
it = iter(fixtures)
return lib.MockTransport(lambda request: lib.Response(200, json=next(it)))
def oai_resp(text: str, status: str = "completed", reason: str | None = None, refusal: bool = False) -> dict:
part = {"type": "refusal", "refusal": text} if refusal else {"type": "output_text", "text": text, "annotations": []}
return {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-6-luna", "status": status,
"incomplete_details": {"reason": reason} if reason else None,
"output": [{"type": "message", "id": "m", "role": "assistant", "status": "completed", "content": [part]}]}
def oai_chat(text: str | None, finish: str = "stop", refusal: str | None = None) -> dict:
return {"id": "c", "object": "chat.completion", "created": 0, "model": "gpt-6-luna",
"choices": [{"index": 0, "finish_reason": finish,
"message": {"role": "assistant", "content": text, "refusal": refusal}}],
"usage": {"prompt_tokens": 30, "completion_tokens": 12, "total_tokens": 42}}
def claude(text: str, stop: str = "end_turn") -> dict:
return {"id": "msg", "type": "message", "role": "assistant", "model": "claude-haiku-5-5", "stop_reason": stop,
"content": [{"type": "text", "text": text}], "usage": {"input_tokens": 30, "output_tokens": 12}}
def gemini(text: str, finish: str = "STOP") -> dict:
return {"candidates": [{"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": finish}]}
LABELS = ["clean", "truncated", "refusal", "wrong value"]
o = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=replies(
[oai_resp(CLEAN), oai_resp(CUT, "incomplete", "max_output_tokens"), oai_resp(REFUSAL, refusal=True),
oai_resp(WRONG), oai_chat(CLEAN), oai_chat(CUT, "length"), oai_chat(None, refusal=REFUSAL),
oai_chat(WRONG)], httpx2)))
a = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=replies(
[claude(CLEAN), claude(CUT, "max_tokens"), claude(REFUSAL, "refusal"), claude(WRONG)], httpx2)))
g = genai.Client(api_key="test", http_options=types.HttpOptions(httpx_client=httpx.Client(transport=replies(
[gemini(CLEAN), gemini(CUT, "MAX_TOKENS"), gemini(REFUSAL, "SAFETY"), gemini(WRONG)], httpx))))
gcfg = types.GenerateContentConfig(response_mime_type="application/json", response_schema=Refund)
msgs = [{"role": "user", "content": "..."}]
helpers = {
"responses.parse -> output_parsed":
lambda: o.responses.parse(model="gpt-6-luna", input="...", text_format=Refund).output_parsed,
"chat.completions.parse -> message.parsed":
lambda: o.chat.completions.parse(model="gpt-6-luna", messages=msgs, response_format=Refund) # type: ignore[arg-type]
.choices[0].message.parsed,
"messages.parse -> parsed_output":
lambda: a.messages.parse(model="claude-haiku-5-5", max_tokens=200, messages=msgs, # type: ignore[arg-type]
output_format=Refund).parsed_output,
"generate_content -> response.parsed":
lambda: g.models.generate_content(model="gemini-3.8-flash", contents="...", config=gcfg).parsed,
}
for name, call in helpers.items():
print(name)
for label in LABELS:
try:
result = f"returns {call()!r}"
except Exception as err:
result = f"RAISES {type(err).__name__}"
print(f" {label:12} {result}")responses.parse -> output_parsed
clean returns Refund(amount=42.5, currency='GBP')
truncated RAISES ValidationError
refusal returns None
wrong value RAISES ValidationError
chat.completions.parse -> message.parsed
clean returns Refund(amount=42.5, currency='GBP')
truncated RAISES LengthFinishReasonError
refusal returns None
wrong value RAISES ValidationError
messages.parse -> parsed_output
clean returns Refund(amount=42.5, currency='GBP')
truncated RAISES ValidationError
refusal RAISES ValidationError
wrong value RAISES ValidationError
generate_content -> response.parsed
clean returns Refund(amount=42.5, currency='GBP')
truncated returns None
refusal returns None
wrong value returns None| Reply | responses.parse |
chat.completions.parse |
messages.parse |
|---|---|---|---|
| Clean | the object | the object | the object |
| Truncated | raises ValidationError (status lost) |
raises LengthFinishReasonError (completion kept) |
raises ValidationError (stop reason lost) |
| Refusal | None; the refusal is a content item |
None; text in message.refusal |
raises ValidationError if the refusal has text |
| Wrong value | raises ValidationError |
raises ValidationError |
raises ValidationError |
| Reply | Gemini .parsed |
|---|---|
| Clean | the object |
| Truncated | None, silently |
| Refusal | None, silently |
| Wrong value | None, silently |
Three of the four helpers raise on a truncated reply, and only one of those (Chat Completions) tells you why; the Gemini helper never raises at all. Neither behaviour is a bug, but both make it easy to treat a truncated reply as "invalid output" and retry it with the same budget forever, or to treat a safety stop as an empty result. The fix is the same everywhere: check the outcome before you parse. Part 6 builds that check for every provider.
3.4 Gemini generate_content#
Which field to use. In GenerateContentConfig, set response_mime_type="application/json" and one of two schema fields. As of November 2026, Google's direction is clear, though the sources are thinner than for the other providers:
- Google's current API reference for
generateContentlistsresponseJsonSchemaas the schema field and carries noresponseSchemaentry of its own; the one entry that points elsewhere reads "An internal detail. UseresponseJsonSchemarather than this field." (The page's wording there is garbled, so read it as "prefer the JSON Schema field".) - Google's structured-output guide, the page 4.4 cites for the not-enforced list, now documents only the Interactions API (3.5). It has no
GenerateContentConfigtext at all. Thegenerate_contentdetails in this lesson therefore come from the API reference and from the SDK itself. - The SDK's own docstring for
response_json_schemalists the keywords it supports, and says "If set,response_schemamust be omitted".
So the recommended path is response_json_schema=Model.model_json_schema() with Model.model_validate_json(response.text). It sends standard JSON Schema as written, so Pydantic's recursion, anyOf, additionalProperties and exclusiveMinimum are not rewritten or rejected by the SDK (2.8):
config = types.GenerateContentConfig(
response_mime_type="application/json",
response_json_schema=Order.model_json_schema()) # Google's recommended field
response = client.models.generate_content(model="gemini-3.8-flash", contents=email, config=config)
order = Order.model_validate_json(response.text) # you validate; response.parsed is a plain dict hereThe other field, response_schema, takes a Pydantic class, list[Model], an Enum or a types.Schema, and the SDK converts it to Gemini's own OpenAPI-style Schema (2.9). It stays useful as a convenience: it fills response.parsed with your model, and it is the only way to use enum mode (9.2). Its costs are the ones 2.8 measured: the conversion rejects exclusiveMinimum, discriminator and additionalProperties, drops recursion without a word, and .parsed is None on any failure. Gemini has no local stand-in, so neither route can be run locally; the hosted sample in 3.8 uses the recommended one.
Use one field or the other. Google's current reference doesn't say whether the two fields are mutually exclusive (an earlier version of its docs did), the SDK docstring still says so, and SDK 2.34.0 sends both if you set both, so don't.
Reading the result. response.parsed "will parse the returned JSON, and return the result" when it can ("When possible", in Google's words):
- With
response_schema=Orderit's anOrder; withlist[Model], a list of models; with anEnumand enum mode, an enum member. - With
response_json_schemait's a plain dict, not your model, because the SDK only has a JSON Schema. Validate it yourself withOrder.model_validate_json(response.text); that also gives you a realValidationErrorto feed back on a retry. - On any failure (truncated JSON, a value outside the schema, a safety stop with no JSON) it is
None, with no exception (3.9). Always check it explicitly, and checkcandidates[0].finish_reasonfirst. - In a stream,
chunk.parsedis alwaysNone: joinchunk.textand validate once at the end (lesson 03.3, 6.3).
Enum mode. response_mime_type="text/x.enum" with an Enum as response_schema returns one bare value ("ENUM as a string response", in the API reference) instead of a JSON object. It exists only in generate_content; the Interactions mime_type doesn't offer it. 9.2 shows it on a mock server.
Property order. Schema.property_ordering is "Used to determine the order of the properties in the response". With response_schema the SDK fills it from your Pydantic field order, so keys come back in the order you declared them (4.4). The response_json_schema route has no such conversion; the SDK's docstring lists the non-standard propertyOrdering keyword for it, so add it yourself where the order matters.
With tools. Structured output combined with built-in tools (Google Search, URL context, code execution, file search) and function calling is "Preview: This feature is available only to Gemini 3 series models", as of November 2026.
3.5 Gemini Interactions#
The Interactions API (Google's recommended interface for new projects, lesson 03.1, 5.3) puts structured output in response_format:
response_format={"type": "text", "mime_type": "application/json", "schema": Order.model_json_schema()}- It is polymorphic: "an object (or an array containing an object) of type
text". A list is for asking for several modalities; for JSON output, pass one object. mime_typeaccepts"application/json"or"text/plain". There is no enum mode.schemais standard JSON Schema, so passmodel_json_schema(), not the class.- There is no parse helper: read
interaction.output_textand validate it, as Google's own sample does:Recipe.model_validate_json(interaction.output_text). Checkinteraction.status == "completed"first. The statuses the reference and SDK 2.34.0 list arein_progress,requires_action,completed,failed,cancelled,incomplete("completed, but contains incomplete results (e.g. hitting max_tokens)"),requires_continuation,budget_exceededandqueued. 6.4 says what each means for an extractor, andfrom_gemini_interactionin 6.5 handles them. - Since Google's structured-output guide now documents only this API, its Python examples are the best primary source for this shape:
response_format={"type": "text", "mime_type": "application/json", "schema": Model.model_json_schema()}, thenModel.model_validate_json(interaction.output_text). - The rest of the schema rules are the same as
generate_content's JSON Schema path (4.4), and streaming "chunks are valid partial JSON strings that can be concatenated to form the final JSON object".
3.6 OpenRouter#
OpenRouter passes the OpenAI shapes through: response_format with json_schema (Chat Completions, the primary API) or text.format (its Responses API). The openai SDK's parse helpers work unchanged with base_url="https://openrouter.ai/api/v1". What's different is that support is per endpoint. OpenRouter: "Support is determined per endpoint, not just per model: the same model may be served by multiple providers, and only some of those providers may support structured outputs."
Four settings and facts to know:
provider.require_parameters: true(an OpenRouter-only field, sent inextra_body) routes only to endpoints that support every parameter in your request. Without it, the default is softer: OpenRouter prefers endpoints that support your response format, but "If none of a model's providers support the parameter, the request is still routed to that model and the parameter is ignored". (Its structured-outputs page says such a request "will fail with an error"; the routing page describes the silent behaviour. Setrequire_parametersand you don't depend on which is right.)- Claude behind OpenRouter:
stricton tools can vanish. For a Claude model, OpenRouter stripsstrictfrom tool definitions unless you send thex-anthropic-beta: structured-outputs-2025-11-13header, and applies the header itself only forresponse_formatJSON schemas (lesson 03.5, 10.5). So for structured output through OpenRouter to Claude, preferresponse_formatover a strict tool, and keep validating either way. - Even
strictvaries by endpoint: "some guarantee schema-conforming output, while others translate your schema... or treat it as a strong hint, so exact compliance is not guaranteed on every endpoint." Validate everything. - The
response-healingplugin, enabled with"plugins": [{"id": "response-healing"}], "automatically validates and repairs malformed JSON responses": missing brackets, trailing commas, Markdown wrappers, mixed text, unquoted keys. It "only applies to non-streaming requests", works withjson_schemaandjson_object, and "if the response is truncated bymax_output_tokens, the plugin will not be able to repair it". OpenRouter's announcement says it is free and that it "fixes JSON syntax errors, not schema adherence". Useful on endpoints that only "hint", but never a substitute for your validation.
You can see per-endpoint support yourself, because OpenRouter's catalogue is public (no key needed). The models API lists structured_outputs ("JSON schema enforcement") and response_format ("Output format specification") in each model's and each endpoint's supported_parameters:
# s3_6_openrouter_endpoints.py
"""OpenRouter: structured-output support is per endpoint. The catalogue is public (no key).
GET /api/v1/models?supported_parameters=... filters models; GET /api/v1/models/{id}/endpoints
lists every provider serving a model, each with its own supported_parameters.
"""
import httpx
BASE = "https://openrouter.ai/api/v1"
with httpx.Client(base_url=BASE, timeout=30) as http:
every = http.get("/models").json()["data"]
strict = http.get("/models", params={"supported_parameters": "structured_outputs"}).json()["data"]
print(f"models: {len(every)}, of which list 'structured_outputs': {len(strict)}")
model_id = "meta-llama/llama-3.3-70b-instruct" # an open-weight model served by many providers
endpoints = http.get(f"/models/{model_id}/endpoints").json()["data"]["endpoints"]
print(f"\n{model_id}: {len(endpoints)} endpoints")
print(f" {'provider':10} {'tag':28} {'response_format':16} structured_outputs")
for ep in endpoints:
params = set(ep["supported_parameters"])
print(f" {ep['provider_name']:10} {ep['tag']:28} {str('response_format' in params):16} "
f"{'structured_outputs' in params}")models: 454, of which list 'structured_outputs': 356
meta-llama/llama-3.3-70b-instruct: 9 endpoints
provider tag response_format structured_outputs
DeepInfra deepinfra/turbo True True
AkashML akashml/fp8 True True
Parasail parasail/fp8 True True
Cloudflare cloudflare/fp8 True False
SambaNova sambanova-turbo True True
Groq groq True False
CoreWeave coreweave/fp16 True True
Google google-vertex/us-central1 True True
Google google-vertex True FalseThe same open-weight model is served by nine endpoints, and three of them support response_format (JSON mode) but not structured_outputs (schema enforcement). Send a schema without require_parameters and one of those three can serve it, and treat your schema as, at best, a suggestion. That's the strongest argument for setting require_parameters: true on every structured-output request to OpenRouter, and for validating the reply regardless.
Part 4: Supported JSON Schema subsets and limits#
Reference
Every provider compiles your schema into a grammar, and every grammar engine supports a different subset of JSON Schema. This part is the module's reference for those rules, for structured outputs and strict tools (the same rules apply to both; lesson 03.5 links here). The limits are volatile: they are quoted as of November 2026, with the page to re-check.
4.1 The comparison table#
| Feature | OpenAI (strict) | Anthropic |
|---|---|---|
| Root | Must be an object; not anyOf |
Not restricted in the docs |
| Required | Every property must be in required; optional = union with null |
Normal JSON Schema required; required properties are emitted first |
additionalProperties |
Must be false on every object |
Must be false on every object |
| Types | string, number, boolean, integer, object, array, enum, anyOf |
All basic types including null; enum of primitives only; const; anyOf; allOf (not with $ref) |
| Composition | Not supported: allOf, not, dependentRequired, dependentSchemas, if/then/else; oneOf is not listed either |
Not supported: allOf with $ref; external $ref |
$defs / $ref |
Yes | Yes ($ref, $def, definitions; local only) |
| Recursion | Yes (# or explicit $ref) |
No |
| String keywords | pattern; format: date-time, time, date, duration, email, hostname, ipv4, ipv6, uuid |
Simple-regex pattern; format: those nine plus uri |
minLength / maxLength |
Not in the documented list | Not supported (SDK moves to description) |
| Numbers | minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf |
Not supported (SDK moves to description) |
| Arrays | minItems, maxItems |
minItems of 0 or 1 only |
| Size limits | 5,000 properties; 10 nesting levels; 120,000 characters of names and values; 1,000 enum values; 15,000 characters for a string enum with more than 250 values | 20 strict tools; 24 optional parameters; 16 union-typed parameters (all per request); 180 s compile timeout |
| Key order in the output | Schema order | Required properties first, then optional |
| Unsupported feature → | An error ("If you turn on Structured Outputs by supplying strict: true and call the API with an unsupported JSON Schema, you will receive an error") |
"a 400 error with details" |
| Feature | Gemini |
|---|---|
| Root | Object, array or enum (enum mode) |
| Required | Normal required |
additionalProperties |
Boolean or a schema (but response_schema=Model on the Developer API rejects a schema, 2.8) |
| Types | string, number, integer, boolean, object, array, null (via a type array); enum (string and numeric); anyOf in examples |
| Composition | anyOf listed; the SDK's docstring says oneOf is "interpreted the same as anyOf". allOf, not and const are not listed: test before relying on them |
$defs / $ref |
$defs, $ref and $anchor are listed; response_schema=Model inlines $defs instead. If $ref is set on a sub-schema, no other keywords except those starting with $ may sit beside it (per the SDK docstring) |
| Recursion | Documented, but "unrolled to a limited degree" and only inside non-required properties (nullable is not enough). response_schema=Model drops it silently, 2.8 |
| String keywords | format: date-time, date, time. pattern: not listed in Google's docs; test before relying on it |
minLength / maxLength |
Silently not enforced |
| Numbers | minimum/maximum (inclusive) |
| Arrays | minItems, maxItems, items, prefixItems |
| Other not enforced | minProperties, maxProperties, uniqueItems, contains, minContains, maxContains: "strips and ignores them... rather than returning an error" |
| Size limits | No numbers published: "too many states" 400 |
| Key order in the output | propertyOrdering (the SDK sets it from your field order) |
| Unsupported feature → | Silently ignored (the not-enforced list), or 400 INVALID_ARGUMENT for complexity |
OpenRouter has no column because it has no subset of its own: your schema goes to whichever provider serves the request and is judged by that provider's rules, so read the column of the provider behind the model ID (4.5). Without provider.require_parameters: true, an endpoint that doesn't support a keyword (or structured output at all) may ignore it instead of failing.
Sources: OpenAI's Structured Outputs guide, Anthropic's structured outputs page, Google's structured output page and API reference, and OpenRouter's structured outputs guide. As of November 2026 Google's structured-output page documents only the Interactions API, so the generate_content cells above come from the API reference and from the response_json_schema docstring in google-genai 2.34.0, which lists the supported keywords: $id, $defs, $ref, $anchor, type, format, title, description, enum, items, prefixItems, minItems, maxItems, minimum, maximum, anyOf, oneOf, properties, additionalProperties, required and propertyOrdering. These pages change: check them when a schema is rejected or a limit matters.
4.2 OpenAI's rules and limits#
The strict-mode rules, from OpenAI's guide as of November 2026:
- "the root level object of a schema must be an object, and not use
anyOf". The guide names Zod discriminated unions as one way to produce a forbidden rootanyOf; in Python, a rootCard | Bankdoes the same. Wrap unions in an object field. - "all fields or function parameters must be specified as
required", with optional fields expressed as a union withnull(2.4). - "we require developers to set
additionalProperties: false" on every object. - Key order: "outputs will be produced in the same order as the ordering of keys in the schema." Put fields the model should think about first, first (5.2).
- Definitions and recursion are supported:
$defswith$ref, and "root recursion" with"$ref": "#". - Unsupported: "
allOf,not,dependentRequired,dependentSchemas,if,then,else".oneOfisn't in the supported list either: useanyOf. - Supported keywords per type: strings have
patternandformat; numbers havemultipleOf,maximum,exclusiveMaximum,minimumandexclusiveMinimum; arrays haveminItemsandmaxItems.minLengthandmaxLengthare not on the list (they appear only in the fine-tuned-model note below), and neither dodefaultoroneOf. That is why the flagshipOrdermodel enforces the customer-name length in a validator (2.1): the SDK would pass amaxLengthstraight through, and as of November 2026 the guide's supported list still has nominLengthormaxLength, and it says an unsupported schema understrict: trueproduces an error, but it does not say whether a keyword it merely omits is rejected or ignored. The lesson therefore can't promise the API accepts one. Nobody has tested it here; if you need a length limit in the schema, send a one-field schema withmaxLengthto your own account and see. - Fine-tuned models additionally lose
minLength,maxLength,pattern,format,minimum,maximum,multipleOf,patternProperties,minItemsandmaxItems.
Size limits, quoted:
- "up to 5000 object properties total, with up to 10 levels of nesting."
- "total string length of all property names, definition names, enum values, and const values cannot exceed 120,000 characters."
- "up to 1000 enum values across all enum properties."
- "For a single enum property with string values, the total string length of all enum values cannot exceed 15,000 characters when there are more than 250 enum values."
Function tools in Responses are strict by default when possible. From OpenAI's function-calling guide: "If you omit strict, the default depends on the API: Responses requests will attempt to normalize your schema into strict mode when possible, and will fall back to non-strict, best-effort function calling if the schema cannot be made compatible with strict mode. When fallback happens, the response tool will show strict: false. Chat Completions requests remain non-strict by default." To opt out in Responses, set strict: false explicitly. Two consequences: a Responses tool with an optional parameter may silently fall back to non-strict (check the tool's strict in the response if it matters), and the same tool definition behaves differently on Chat Completions. OpenAI's advice is "We recommend always enabling strict mode", which means writing schemas that pass the rules above.
4.3 Anthropic's rules and limits#
What Anthropic's grammar supports, quoted from its docs as of November 2026:
- "All basic types: object, array, string, integer, number, boolean, null"; "
enum(strings, numbers, booleans, or nulls only, no complex types)"; "const"; "anyOfandallOf(with limitations:allOfwith$refnot supported)"; "$ref,$def, anddefinitions(external$refnot supported)"; "defaultproperty for all supported types"; "requiredandadditionalProperties(must be set tofalsefor objects)"; string formatsdate-time,time,date,duration,email,hostname,uri,ipv4,ipv6,uuid; "ArrayminItems(only values 0 and 1 supported)". - Not supported: recursive schemas; complex types within enums; external
$ref; "Numerical constraints (such asminimum,maximum,multipleOf)"; "String constraints (minLength,maxLength)"; "Array constraints beyondminItemsof 0 or 1"; "additionalPropertiesset to anything other thanfalse". - Regex in
pattern: full and partial matching,*,+,?, "simple{n,m}cases", character classes,.,\d,\w,\sand groups. Not: backreferences, lookahead/lookbehind,\b/\B, and "Complex{n,m}quantifiers with large ranges". (SDK 2.4.0'stransform_schemamovespatterninto the description regardless, so withmessages.parseyour regex is enforced by Pydantic, not by the grammar. If you need the grammar to enforce a simple pattern, send the schema yourself withoutput_config.)
Complexity limits, all counted across every strict schema in one request (strict tools and the JSON output schema together):
| Limit | Value |
|---|---|
| Strict tools per request | 20 ("Non-strict tools don't count toward this limit") |
| Optional parameters | 24 |
Parameters with union types (anyOf, or type arrays such as ["string", "null"]) |
16 |
| Compile timeout | 180 seconds, "as a final stop-gap" |
| Error when exceeded | 400, "Schema is too complex for compilation." |
The union limit bites sooner than you'd expect: every str | None field is a union-typed parameter. Seventeen nullable fields across your tools and output schema in one request is over the limit.
Behaviour you must design for:
- Output order: "required properties appear first, followed by optional properties." So
discount_code(optional) comes afteritems, whatever order you declared. If the model should write a field before another, make both required. - Enum casing: not guaranteed (2.3). Normalize.
- Compile latency and caching: "additional latency while the grammar compiles" on first use; "Compiled grammars are cached for 24 hours from last use." Changing the schema's structure or the set of tools invalidates that cache; changing only
nameordescriptionfields doesn't (11.2). - Prompt caching: "Changing the
output_config.formatparameter will invalidate any prompt cache for that conversation thread" (11.3). - Incompatible: citations (400) and prefill (3.3).
- Data handling: structured outputs are eligible for zero data retention (ZDR), the arrangement where the provider stores nothing from your requests ("qualified; excludes Covered Models"), "Only the JSON schema is cached, for up to 24 hours since last use", and for HIPAA workloads (US health-privacy rules) "PHI must not be included in JSON schema definitions". In practice: the compiled grammar is cached with your schema's property names,
enumandconstvalues andpatterns, so none of them may contain personal data. Don't put customer data in schemas: an enum of customer names is both a privacy problem and a token bill. Module 12 covers privacy and compliance as topics of their own.
4.4 Gemini's rules and limits#
As of November 2026 Google's structured-output page documents only the Interactions API (3.5), so what follows for generate_content comes from the page's keyword and limit sections, the API reference, and the response_json_schema docstring in google-genai 2.34.0:
- Types: string, number, integer, boolean, object, array, and null: "To allow a property to be null, include
"null"in the type array (e.g.,{"type": ["string", "null"]})". Thegenerate_contentSchematype also hasnullable("Indicates if the value may be null"), which is what the SDK emits forstr | None. - Keywords:
title,description,properties,required,additionalProperties,enum,format(date-time,date,time),minimum/maximum("inclusive"),items,prefixItems,minItems,maxItems, plusanyOfand$ref: "#"recursion in the examples; and, per the SDK docstring forresponse_json_schema,$id,$defs,$ref,$anchor,oneOf(read asanyOf) andpropertyOrdering. Not listed anywhere:pattern,exclusiveMinimum,exclusiveMaximum,multipleOf,allOf,not,const. Google doesn't say they are rejected or ignored, so treat them as untested (4.6 flags them). - Silently not enforced: "
minLength,maxLength,minProperties,maxProperties,uniqueItems,contains,minContains, andmaxContains(and their snake_case variants) are not enforced by the constrained decoding grammar engine… the API automatically strips and ignores them during request normalization rather than returning an error.minItemsandmaxItemsare enforced." AmaxLength=100in your Pydantic model is therefore a validation rule, not a generation rule, on Gemini. Enforce it in Pydantic: validate the reply against your class yourself (model_validate_json), which the.parsedconvenience also does, silently. - "Too many states": "Very large or deeply nested schemas may be rejected with a
400 INVALID_ARGUMENTerror that says the schema produces a constraint with too many states or too much branching for serving. Common causes are largemaxItemslimits (especially on nested arrays), very long property or enum names, enums with many values, long runs of optional properties,anyOfwith many alternatives, and numericminimum/maximumbounds. To fix it, lower or remove nested array limits, shorten names, or intersperse required properties among optional ones." Google publishes no numeric limits. - Property ordering:
propertyOrdering"Used to determine the order of the properties in the response". Google's troubleshooting page adds a symptom: "When the model output has a different order for the fields than the defined structured schema, this can lead to repeating text", and the fix: "Don't specify the order of fields in your prompt. Make all output fields required." - Validate anyway: "While output is syntactically correct JSON, always validate values in your application."
- Recursion: documented with
$ref: "#", but "Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties" (the SDK docstring). Don't rely on deep recursion. - With tools: Gemini 3 only, in Preview (3.4).
4.5 OpenRouter: whatever the routed endpoint supports#
OpenRouter doesn't define its own subset. Your schema is passed to whichever provider serves the request, with that provider's rules, so a schema that works on openai/gpt-6-luna can be rejected on anthropic/claude-haiku-5.5 (recursion, or the minimum/maximum and maxItems that Order's strict schema carries) or silently loosened on an endpoint that only "hints". Two habits: write schemas to the intersection of the providers you might route to (the linter below checks all three), and set provider.require_parameters: true so an endpoint without structured-output support can't serve the request (3.6).
4.6 Try it: a pre-flight schema linter#
Rather than learn about a rule from a 400 in production, check schemas in a unit test. This linter encodes the table above (layer 1, no network). It lives in schema_lint.py:
# schema_lint.py: a pre-flight check of a JSON Schema against each provider's documented subset.
"""Rules as documented in November 2026 (see the table in 4.1). It catches the common mistakes
before you pay for a 400; the provider's own validation stays the final word."""
from collections.abc import Iterator
from typing import Any
OPENAI_FORMATS = {"date-time", "time", "date", "duration", "email", "hostname", "ipv4", "ipv6", "uuid"}
ANTHROPIC_FORMATS = OPENAI_FORMATS | {"uri"}
GEMINI_FORMATS = {"date-time", "date", "time"}
OPENAI_UNSUPPORTED = {"allOf", "not", "if", "then", "else", "dependentRequired", "dependentSchemas"}
OPENAI_UNDOCUMENTED = {"minLength", "maxLength", "uniqueItems", "minProperties", "maxProperties"}
ANTHROPIC_UNSUPPORTED = {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf",
"minLength", "maxLength", "maxItems", "uniqueItems"}
GEMINI_NOT_ENFORCED = {"minLength", "maxLength", "minProperties", "maxProperties", "uniqueItems",
"contains", "minContains", "maxContains"}
# Keywords that appear in neither Google's keyword list nor google-genai's list for response_json_schema
GEMINI_UNDOCUMENTED = {"exclusiveMinimum", "exclusiveMaximum", "multipleOf", "pattern", "allOf", "not", "const"}
# Things google-genai's own conversion of response_schema=Model rejects client-side (Developer API)
GEMINI_SDK_REJECTS = {"discriminator", "exclusiveMinimum", "exclusiveMaximum"}
def walk(node: Any, path: str = "#", depth: int = 0) -> Iterator[tuple[str, dict, int]]:
"""Yield (path, subschema, object-nesting depth) for every subschema."""
if not isinstance(node, dict):
return
yield path, node, depth
child_depth = depth + (1 if node.get("type") == "object" else 0)
for key, value in node.get("properties", {}).items():
yield from walk(value, f"{path}/properties/{key}", child_depth)
for key in ("items", "additionalProperties"):
if isinstance(node.get(key), dict):
yield from walk(node[key], f"{path}/{key}", child_depth)
for key in ("anyOf", "oneOf", "allOf", "prefixItems"):
for i, value in enumerate(node.get(key, [])):
yield from walk(value, f"{path}/{key}/{i}", child_depth)
for key in ("$defs", "definitions"):
for name, value in node.get(key, {}).items():
yield from walk(value, f"#/{key}/{name}", 1)
def refs_cycle(schema: dict) -> bool:
"""True if any $defs entry can reach itself through $ref (a recursive schema)."""
defs = schema.get("$defs", {}) | schema.get("definitions", {})
edges = {name: {n["$ref"].split("/")[-1] for _, n, _ in walk(d) if "$ref" in n} for name, d in defs.items()}
if any(n.get("$ref") == "#" for _, n, _ in walk(schema)):
return True
def reaches(start: str, target: str, seen: set[str]) -> bool:
return any(nxt == target or (nxt not in seen and reaches(nxt, target, seen | {nxt}))
for nxt in edges.get(start, ()))
return any(reaches(name, name, {name}) for name in edges)
def lint_openai(schema: dict) -> list[str]:
issues = []
if schema.get("type") != "object" or "anyOf" in schema:
issues.append("root must be an object and not anyOf")
props = enum_values = text = 0
for path, node, depth in walk(schema):
if depth > 10:
issues.append(f"{path}: more than 10 levels of nesting")
for kw in sorted(OPENAI_UNSUPPORTED & node.keys()):
issues.append(f"{path}: '{kw}' is not supported")
for kw in sorted(OPENAI_UNDOCUMENTED & node.keys()):
issues.append(f"{path}: '{kw}' is not in the documented subset (enforce it in Pydantic)")
if "oneOf" in node:
issues.append(f"{path}: 'oneOf' is not in the documented subset (use anyOf)")
if node.get("type") == "object" or "properties" in node:
if node.get("additionalProperties") is not False:
issues.append(f"{path}: additionalProperties must be false")
missing = set(node.get("properties", {})) - set(node.get("required", []))
if missing:
issues.append(f"{path}: every property must be required; missing {sorted(missing)}")
props += len(node.get("properties", {}))
text += sum(len(k) for k in node.get("properties", {}))
if node.get("format") and node["format"] not in OPENAI_FORMATS:
issues.append(f"{path}: format '{node['format']}' is not supported")
if "enum" in node:
enum_values += len(node["enum"])
chars = sum(len(str(v)) for v in node["enum"])
text += chars
if len(node["enum"]) > 250 and chars > 15_000:
issues.append(f"{path}: enum with >250 values exceeds 15,000 characters")
if props > 5000:
issues.append(f"{props} object properties in total (limit 5,000)")
if enum_values > 1000:
issues.append(f"{enum_values} enum values in total (limit 1,000)")
if text > 120_000:
issues.append(f"{text:,} characters of names and enum values (limit 120,000)")
return issues
def lint_anthropic(schema: dict) -> list[str]:
issues = ["recursive schemas are not supported"] if refs_cycle(schema) else []
optional = unions = 0
for path, node, _ in walk(schema):
for kw in sorted(ANTHROPIC_UNSUPPORTED & node.keys()):
issues.append(f"{path}: '{kw}' is not supported")
if node.get("minItems") not in (None, 0, 1):
issues.append(f"{path}: minItems must be 0 or 1")
if node.get("type") == "object" or "properties" in node:
if node.get("additionalProperties") is not False:
issues.append(f"{path}: additionalProperties must be false")
optional += len(set(node.get("properties", {})) - set(node.get("required", [])))
if "anyOf" in node or isinstance(node.get("type"), list):
unions += 1
if node.get("format") and node["format"] not in ANTHROPIC_FORMATS:
issues.append(f"{path}: format '{node['format']}' is not supported")
if str(node.get("$ref", "#")).startswith(("http", "file")):
issues.append(f"{path}: external $ref is not supported")
if optional > 24:
issues.append(f"{optional} optional parameters (limit 24 across the request)")
if unions > 16:
issues.append(f"{unions} union-typed parameters (limit 16 across the request)")
return issues
def lint_gemini(schema: dict, route: str = "response_json_schema") -> list[str]:
"""route="response_json_schema": the JSON Schema is sent as written (Google's recommended field).
route="response_schema": google-genai first converts your Pydantic model to its own Schema type,
which rejects or drops more (see 2.8). Lint the schema Pydantic produced, before the conversion."""
issues = []
if refs_cycle(schema):
if route == "response_schema":
issues.append("recursive schema: google-genai's response_schema conversion silently drops the "
"recursion (items: {}); use response_json_schema")
else:
issues.append("recursive schema: Google unrolls cycles only to a limited depth, and only "
"inside non-required properties")
for path, node, _ in walk(schema):
for kw in sorted(GEMINI_NOT_ENFORCED & node.keys()):
issues.append(f"{path}: '{kw}' is silently not enforced (validate it yourself)")
for kw in sorted(GEMINI_UNDOCUMENTED & node.keys()):
issues.append(f"{path}: '{kw}' is not in the documented list (test it before relying on it)")
if route == "response_schema":
for kw in sorted(GEMINI_SDK_REJECTS & node.keys()):
issues.append(f"{path}: google-genai raises a ValidationError for '{kw}' before sending")
if isinstance(node.get("additionalProperties"), dict):
issues.append(f"{path}: google-genai raises a ValueError for an additionalProperties schema")
if node.get("format") and node["format"] not in GEMINI_FORMATS:
issues.append(f"{path}: format '{node['format']}' is not in the documented list")
if isinstance(node.get("maxItems"), int) and node["maxItems"] > 100:
issues.append(f"{path}: large maxItems ({node['maxItems']}) is a common 'too many states' cause")
return issues
def lint_gemini_response_schema(schema: dict) -> list[str]:
return lint_gemini(schema, route="response_schema")
LINTERS = {"openai": lint_openai, "anthropic": lint_anthropic,
"gemini (json schema)": lint_gemini, "gemini (response_schema)": lint_gemini_response_schema}It has two Gemini linters, because the two routes fail differently (3.4): gemini (json schema) checks what response_json_schema would send, and gemini (response_schema) also reports what google-genai's own conversion raises on or silently drops. And here it is on five schemas, raw and as each SDK would send them. Contact is a small model that carries a string length limit and gt=0, the kinds of constraint Order no longer has:
# s4_6_schema_lint.py
"""Lint schemas before sending them: Pydantic's raw schema vs what each SDK would send."""
from anthropic import transform_schema
from openai.lib._pydantic import to_strict_json_schema # private: the strict transform .parse() uses
from pydantic import BaseModel, Field
from order_model import Order
from schema_lint import LINTERS
class Node(BaseModel): # recursive: a category tree
name: str
children: list["Node"]
class Contact(BaseModel): # the kinds of constraint that Order no longer carries
name: str = Field(max_length=100)
rating: float = Field(gt=0, le=10)
HAND_WRITTEN = { # a typical hand-written schema: one optional field, no additionalProperties
"type": "object",
"properties": {"name": {"type": "string"}, "email": {"type": "string", "format": "email"},
"website": {"type": "string", "format": "uri"}},
"required": ["name"],
}
def as_sent(model: type[BaseModel]) -> dict[str, dict]:
"""What each route would send. Both Gemini routes start from Pydantic's own schema."""
plain = model.model_json_schema()
return {"openai": to_strict_json_schema(model), "anthropic": transform_schema(model),
"gemini (json schema)": plain, "gemini (response_schema)": plain}
cases = {
"Order, Pydantic's raw schema": {p: Order.model_json_schema() for p in LINTERS},
"Order, as each SDK sends it": as_sent(Order),
"Contact (max_length, gt), as each SDK sends it": as_sent(Contact),
"Node (recursive), as each SDK sends it": as_sent(Node),
"hand-written dict, sent as is": {p: HAND_WRITTEN for p in LINTERS},
}
for title, per_provider in cases.items():
print(f"\n===== {title} =====")
for provider, schema in per_provider.items():
issues = LINTERS[provider](schema)
print(f" {provider:24} {'OK' if not issues else ''}")
for issue in issues:
print(f" - {issue}")===== Order, Pydantic's raw schema =====
openai
- #: additionalProperties must be false
- #: every property must be required; missing ['discount_code']
- #/$defs/LineItem: additionalProperties must be false
anthropic
- #: additionalProperties must be false
- #/properties/items: 'maxItems' is not supported
- #/$defs/LineItem: additionalProperties must be false
- #/$defs/LineItem/properties/quantity: 'maximum' is not supported
- #/$defs/LineItem/properties/quantity: 'minimum' is not supported
gemini (json schema) OK
gemini (response_schema) OK
===== Order, as each SDK sends it =====
openai OK
anthropic OK
gemini (json schema) OK
gemini (response_schema) OK
===== Contact (max_length, gt), as each SDK sends it =====
openai
- #/properties/name: 'maxLength' is not in the documented subset (enforce it in Pydantic)
anthropic OK
gemini (json schema)
- #/properties/name: 'maxLength' is silently not enforced (validate it yourself)
- #/properties/rating: 'exclusiveMinimum' is not in the documented list (test it before relying on it)
gemini (response_schema)
- #/properties/name: 'maxLength' is silently not enforced (validate it yourself)
- #/properties/rating: 'exclusiveMinimum' is not in the documented list (test it before relying on it)
- #/properties/rating: google-genai raises a ValidationError for 'exclusiveMinimum' before sending
===== Node (recursive), as each SDK sends it =====
openai OK
anthropic
- recursive schemas are not supported
gemini (json schema)
- recursive schema: Google unrolls cycles only to a limited depth, and only inside non-required properties
gemini (response_schema)
- recursive schema: google-genai's response_schema conversion silently drops the recursion (items: {}); use response_json_schema
===== hand-written dict, sent as is =====
openai
- #: additionalProperties must be false
- #: every property must be required; missing ['email', 'website']
- #/properties/website: format 'uri' is not supported
anthropic
- #: additionalProperties must be false
gemini (json schema)
- #/properties/email: format 'email' is not in the documented list
- #/properties/website: format 'uri' is not in the documented list
gemini (response_schema)
- #/properties/email: format 'email' is not in the documented list
- #/properties/website: format 'uri' is not in the documented listThree things to take from it:
- Raw Pydantic schemas fail strict rules (no
additionalProperties: false, an optional field), which is why you let the SDK helpers transform them, or call the transforms yourself. - After the transforms, the remaining warnings are real.
Ordernow passes all four linters, because the length rule moved into a validator: this is the check that found the problem, since an earlier version of the model carriedmax_length=100and the linter reported "maxLengthis not in the documented subset" for OpenAI while the hosted samples were about to send it.Contactstill shows the problem:maxLengthisn't documented for OpenAI and isn't enforced by Gemini, so it is Pydantic's job, andgt=0becomesexclusiveMinimum, which Google doesn't list and whichresponse_schema=Modelraises on. And the recursiveNodepasses OpenAI, is rejected by Anthropic, and gets a different warning on each Gemini route (silently dropped byresponse_schema, unrolled only to a limited depth byresponse_json_schema). - Hand-written schemas are where the classic mistakes live: a property missing from
required, noadditionalProperties, auriformat OpenAI doesn't list. A test that runslint_openai(schema)for every schema in your codebase costs nothing and catches these on the day they are written.
The linter is deliberately simple (it doesn't resolve every $ref for nesting depth, for example). Treat it as a first line, with the provider as the final word.
4.7 Try it: schemas the providers reject#
What a rejection looks like from each SDK, against mock servers returning each provider's documented error envelope (layer 3). Anthropic's message is the one its docs give; the OpenAI and Gemini messages are modelled on their docs' descriptions, and the real wording may differ:
# s4_7_schema_rejections.py
"""Schema rejections: what each SDK raises, against MOCK servers returning 400 fixtures.
The fixtures follow each provider's documented error envelope. Anthropic's message is the
documented one; the OpenAI and Gemini messages are modelled on the documented wording and
the real text may differ. The point is the exception class, the fields you can log, and the
fact that the SDKs don't retry a 400 (so count the attempts).
"""
from typing import Annotated, Literal
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import errors, types
from pydantic import BaseModel, Field
attempts: dict[str, int] = {}
def mock(name: str, status: int, body: dict, lib, headers: dict | None = None):
def handler(request):
attempts[name] = attempts.get(name, 0) + 1
return lib.Response(status, json=body, headers=headers or {})
return lib.MockTransport(handler)
OPENAI_400 = {"error": {"type": "invalid_request_error", "code": "invalid_json_schema", "param": "text.format.schema",
"message": "Invalid schema for response_format 'Contact': 'required' must include every "
"key in 'properties'. Missing 'email'."}}
ANTHROPIC_400 = {"type": "error", "request_id": "req_011CTest",
"error": {"type": "invalid_request_error", "message": "Schema is too complex for compilation."}}
GEMINI_400 = {"error": {"code": 400, "status": "INVALID_ARGUMENT",
"message": "The specified schema produces a constraint that has too many states for serving."}}
CONTACT = {"type": "object", "additionalProperties": False, "required": ["name"],
"properties": {"name": {"type": "string"}, "email": {"type": "string"}}}
# --- OpenAI: strict schema with a property missing from "required" --------------------------
oai = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=mock("openai", 400, OPENAI_400, httpx2)))
try:
oai.responses.create(model="gpt-6-luna", input="...", text={"format": {
"type": "json_schema", "name": "Contact", "schema": CONTACT, "strict": True}})
except openai.BadRequestError as err:
print(f"OpenAI {type(err).__name__} {err.status_code} code={err.code} param={err.param}"
f" attempts={attempts['openai']}")
print(" ", err.body.get("message") if isinstance(err.body, dict) else err.body)
# --- Anthropic: a schema over the compiler's complexity limits -------------------------------
claude = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(
transport=mock("anthropic", 400, ANTHROPIC_400, httpx2, {"request-id": "req_011CTest"})))
try:
claude.messages.create(model="claude-haiku-5-5", max_tokens=1000, messages=[{"role": "user", "content": "..."}],
output_config={"format": {"type": "json_schema", "schema": CONTACT}})
except anthropic.BadRequestError as err:
body = err.body if isinstance(err.body, dict) else {}
print(f"Anthropic {type(err).__name__} {err.status_code} type={body.get('error', {}).get('type')}"
f" request_id={err.request_id} attempts={attempts['anthropic']}\n {body['error']['message']}")
# --- Gemini: "too many states" -----------------------------------------------------------------
gem = genai.Client(api_key="test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=mock("gemini", 400, GEMINI_400, httpx))))
try:
gem.models.generate_content(model="gemini-3.8-flash", contents="...", config=types.GenerateContentConfig(
response_mime_type="application/json", response_json_schema=CONTACT))
except errors.ClientError as err:
print(f"Gemini {type(err).__name__} {err.code} status={err.status} attempts={attempts['gemini']}"
f"\n {err.message}")
# --- Rejected before anything is sent: the SDKs' own checks -----------------------------------
class Card(BaseModel):
kind: Literal["card"]
last4: str
class Bank(BaseModel):
kind: Literal["bank"]
iban: str
class Payment(BaseModel):
method: Annotated[Card | Bank, Field(discriminator="kind")]
print("\nClient-side, nothing sent:")
for label, call in [
("OpenAI text_format=list[Card]", lambda: oai.responses.parse(model="gpt-6-luna", input="...",
text_format=list[Card])),
("Anthropic output_format=dict schema", lambda: claude.messages.parse(
model="claude-haiku-5-5", max_tokens=10, messages=[{"role": "user", "content": "..."}],
output_format={"type": "object"})), # type: ignore[arg-type]
("Gemini response_schema=Payment (discriminator)", lambda: gem.models.generate_content(
model="gemini-3.8-flash", contents="...", config=types.GenerateContentConfig(
response_mime_type="application/json", response_schema=Payment))),
]:
before = sum(attempts.values())
try:
call()
except Exception as err:
print(f" {label:47} {type(err).__name__}: {str(err).splitlines()[0][:70]}"
f" (requests sent: {sum(attempts.values()) - before})")OpenAI BadRequestError 400 code=invalid_json_schema param=text.format.schema attempts=1
Invalid schema for response_format 'Contact': 'required' must include every key in 'properties'. Missing 'email'.
Anthropic BadRequestError 400 type=invalid_request_error request_id=req_011CTest attempts=1
Schema is too complex for compilation.
Gemini ClientError 400 status=INVALID_ARGUMENT attempts=1
The specified schema produces a constraint that has too many states for serving.
Client-side, nothing sent:
OpenAI text_format=list[Card] TypeError: Unsupported response_format type - list[__main__.Card] (requests sent: 0)
Anthropic output_format=dict schema TypeError: `output_format` must be a type; pass a schema dict as `output_config={ (requests sent: 0)
Gemini response_schema=Payment (discriminator) ValidationError: 2 validation errors for Schema (requests sent: 0)- Each SDK raises its normal 400 exception (
openai.BadRequestError,anthropic.BadRequestError,google.genai.errors.ClientError), with the fields you should log: OpenAI'scodeandparam, Anthropic'srequest_id, Gemini'sstatus. attempts=1everywhere: the SDKs don't retry a 400, and neither should you. A schema error is a bug in your request, so retrying just pays for the same rejection again. Fix the schema (and add it to the linter).- Some rejections happen before anything is sent: OpenAI's helpers accept only a Pydantic model (or a Pydantic dataclass) as
text_format, so a rootlist[Card]is aTypeError(wrap it in an object); Anthropic'soutput_formattakes a type, not a dict; google-genai'sSchematype refusesdiscriminator. These are cheap failures. Make them happen in tests, not at 3 a.m.
Error handling in general (which errors to retry, request IDs, how to log them) is lesson 03.8.
Part 5: Schema design for reliability#
Constrained decoding makes a bad schema valid, not good. The model fills the fields you give it, in the order you give them, with the names and descriptions you wrote, and a schema that fights the model's natural way of answering gets worse answers (02.5, 9.3 showed a constraint making an answer wrong). These are the design rules that matter most. Prompt wording itself is Module 04's subject; how to measure whether a schema change helped is Module 10A's.
5.1 Names and descriptions the model understands#
- Name fields for what they mean, in plain words:
invoice_total_including_tax, notamt2. The name is the first thing the model reads about a field, and the only thing if there's no description. - Describe format, source and the missing case: "Payment due date as YYYY-MM-DD, or null if the invoice gives none." Three facts in one sentence.
- Describe enum values that aren't self-explanatory, in the field's description ("billing: charges, refunds, invoices. delivery: parcels, shipping..."), as 9.1 does.
- Don't contradict the schema in the prompt. If the prompt says "give the date as 2 November" and the schema says
format: date, the model is forced to choose. And don't restate the field order in the prompt (Google's troubleshooting advice, 4.4).
5.2 A reasoning or evidence field before the answer#
Models generate left to right, and OpenAI emits keys in schema order, so the order of fields is the order of thought. A field that comes before the answer is space the model can use to work it out; a field that comes after is a justification of an answer already given.
evidencebeforecategory: "quote the words that decide it" makes the model look at the text before it labels it, and gives you something checkable: is the quote really in the input (9.1 checks)?reasoningbeforeanswerfor anything that needs a few steps (a calculation, a policy decision).
The trade-off is cost and latency: every reasoning token is an output token, billed at the output rate and generated one at a time. A two-sentence reasoning field can double the output of a short classification. Three ways to keep it in check: bound it in the description ("one or two sentences"), use a short evidence quote rather than open reasoning, or use the model's built-in reasoning (reasoning.effort, adaptive thinking, thinking_level: 02.8, Part 3), which happens outside the schema on every provider.
5.3 An explicit "unknown" path instead of forced guesses#
A schema with no way to say "I don't know" forces a guess. If due_date must be a date and the invoice has none, the model will invent one, perfectly formatted. Always give missing information a valid representation:
X | Nonewith a description that says when to usenull("or null if the invoice gives none").- An
"unknown"or"other"enum value for classifications. A classifier without"other"must put a shop-hours question into"billing"or"technical". - A status field for the whole result when the input may not contain the thing at all:
found: bool, ordocument_type: Literal["invoice", "receipt", "not_an_invoice"], before the details.
Then treat null as information: count how often each field is null (a field that is never null on documents that often lack it means the model is guessing), and don't fill nulls with defaults before validation (2.10).
5.4 Flat, bounded and enumerated#
- Flat over deep. Every level of nesting is another chance for the model to lose its place, a step towards OpenAI's 10-level limit, and a source of Gemini "too many states" errors.
customer_name,customer_emailat the top level is easier thancustomer.contact.primary.email. Nest only where the data really repeats (line items). - Recursion becomes fixed depth or a flat list. A category tree as
list[Category]where each item hasidandparent_idworks on every provider; a recursiveNodedoesn't work on Anthropic (4.3) and is silently mangled by google-genai's conversion (2.8). - Bound every list with
max_length(andmin_length=1where empty is wrong). An unbounded list is how a model runs to the token limit. But keep bounds modest on Gemini, where a largemaxItemson a nested array is the first named cause of "too many states". - Enums for classification, never free text that you then try to match.
- Avoid giant enums. A field whose enum lists 300 product categories costs about 1,500 tokens on every request (11.1), counts towards OpenAI's 1,000-value and 15,000-character limits, and is a named cause of Gemini's "too many states". Alternatives: classify in two steps (department, then category within it); retrieve the 10 most likely candidates first and put only those in the enum (a per-request schema, which costs a recompile per distinct schema on Anthropic, 11.2); or return free text and map it in code with a lookup table.
5.5 Splitting one huge schema into several calls#
A schema with 80 fields is one long, fragile generation: a single truncation loses everything, one invalid field fails the whole object, and on Anthropic it may exceed the 24 optional or 16 union-typed parameter limits. Split it:
- By section: header fields in one call, line items in another, totals and tax in a third. Each call is smaller, can run in parallel (lesson 03.9), and can be retried alone.
- By dependency: first classify the document (
document_type), then extract with the schema for that type, rather than one union of every document type. - By chunk for long inputs: extract per chunk, then merge and de-duplicate in code (9.4).
The cost is more requests, each re-sending the document: use prompt caching for the shared prefix (lesson 03.7). The win is reliability you can measure: compare field-level accuracy of the single and split versions on a labelled set (Module 10A).
5.6 A checklist#
Before a schema ships:
- Every field has a clear name and a description with format and missing-value rule.
- Every model-filled field that can be missing is
X | Nonewith no default. - Fields the model should think about come first, and they are required.
- Every list is bounded; every classification is an enum with an "other"/"unknown" value.
- No recursion, no
dict[str, X], no discriminator, no giant enum (or a deliberate exception for one provider). - The linter (4.6) passes for every provider you route to.
- Every rule the provider can't enforce (lengths, ranges on Anthropic, cross-field rules) is a Pydantic validator (Part 6).
Part 6: Validation in layers#
6.1 Four layers, and a check before them#
Structured output moves where failures happen; it doesn't remove them. Production code checks a reply in layers, cheapest and most mechanical first:
flowchart LR
R["Response received"] --> O{"Outcome check:<br/>blocked, refused<br/>or truncated?"}
O -- yes --> X["Handle as its own outcome<br/>(no parsing)"]
O -- no --> P["1. Parse<br/>is it JSON?"]
P --> S["2. Schema<br/>types, enums, required"]
S --> V["3. Semantic validators<br/>cross-field rules, ranges,<br/>grounding in the source"]
V --> B["4. Business rules<br/>approval limits, policy"]
B --> U["Use it"]
P -. fail .-> RT["Retry with the error"]
S -. fail .-> RT
V -. fail .-> RT
B -. flag .-> H["Route to a person<br/>(don't retry)"]| Layer | Checks | Who enforces it | On failure |
|---|---|---|---|
| 0. Outcome | Did the provider finish normally? (not refused, blocked or truncated) | Your code, from the finish signal | A distinct outcome: no parsing (6.4) |
| 1. Parse | Is it JSON at all? | json.loads, or Pydantic's model_validate_json |
Retry. Rare under strict structured output; common under rungs 1 and 2 |
| 2. Schema | Types, required fields, enums, formats | The provider's grammar (for the subset it supports), then Pydantic | Retry with the error |
| 3. Semantic | Rules no schema can express: totals that add up, end after start, ranges the provider couldn't enforce, the value really appears in the source | Pydantic validators (@field_validator, @model_validator) |
Retry with the error; if retries don't fix it, a person (7.4) |
| 4. Business | Your organization's policy: approval limits, allowed vendors, dates in an open accounting period | Plain code after validation | Route, flag or reject; don't retry (the model did its job) |
6.2 What structured output guarantees, and what it doesn't#
| Guaranteed (by rung 3 and 4, within the supported subset) | Not guaranteed |
|---|---|
| The reply parses as JSON | That it finished: truncation cuts it off mid-object (02.5, 4.6) |
| Required keys are present, types match, enum values are from the list | That the model answered at all: refusals "may not match your schema" (OpenAI and Anthropic both say so) |
No extra keys (additionalProperties: false) |
Constraints outside the subset: Anthropic's numeric bounds and lengths, OpenAI's and Gemini's maxLength, every Pydantic validator |
| Truth. Valid JSON with a wrong total, an invented date or a mislabelled ticket is still valid (02.5, 9.3) | |
Safety of the values. A schema-valid str can carry markup, SQL, a URL or injected instructions copied from the text you gave the model (6.3) |
|
| Casing of enum values on Anthropic | |
| That a stand-in or an OpenRouter endpoint enforced anything at all (3.6, 3.7) |
6.3 Semantic validators#
Pydantic validators are where the rules your provider can't enforce live, and where your rules live. The invoice model used in Parts 6, 7 and 9 (invoice_model.py) shows the four common kinds:
# invoice_model.py: an invoice schema with semantic validators (used in Parts 6, 7 and 9)
from datetime import date
from decimal import Decimal
from typing import Literal
from pydantic import BaseModel, Field, ValidationInfo, field_validator, model_validator
Currency = Literal["GBP", "EUR", "USD", "INR"]
class InvoiceLine(BaseModel):
description: str = Field(description="The item or service, as written on the invoice")
quantity: int = Field(ge=1, description="How many units")
unit_price: float = Field(ge=0, description="Price of one unit, in the invoice currency")
class Invoice(BaseModel):
invoice_number: str = Field(description="As printed, e.g. INV-2041")
issue_date: date
due_date: date | None = Field(description="Payment due date, or null if the invoice gives none")
currency: Currency = Field(description="ISO 4217 code of the invoice currency")
lines: list[InvoiceLine] = Field(min_length=1, max_length=50)
total: float = Field(ge=0, description="The invoice total as printed, including tax")
@field_validator("currency", mode="before") # runs BEFORE the Literal check
@classmethod
def normalize_currency(cls, value: object) -> object:
symbols = {"£": "GBP", "€": "EUR", "$": "USD", "₹": "INR"}
if isinstance(value, str):
value = value.strip()
return symbols.get(value, value.upper()) # casing isn't guaranteed: normalize it
return value
@field_validator("invoice_number", "total") # grounding: the value must be in the source text
@classmethod
def appears_in_document(cls, value: str | float, info: ValidationInfo) -> str | float:
document = (info.context or {}).get("document")
if document is None: # no source given: skip this check
return value
shown = value if isinstance(value, str) else f"{value:,.2f}"
if shown not in document and shown.replace(",", "") not in document:
raise ValueError(f"{shown} does not appear in the document; copy it exactly as printed")
return value
@model_validator(mode="after") # cross-field rules no schema can express
def check_consistency(self) -> "Invoice":
if self.due_date and self.due_date < self.issue_date:
raise ValueError(f"due_date {self.due_date} is before issue_date {self.issue_date}")
lines_sum = sum(Decimal(str(l.unit_price)) * l.quantity for l in self.lines)
if abs(lines_sum - Decimal(str(self.total))) > Decimal("0.01"):
raise ValueError(f"lines add up to {lines_sum:.2f} but total is {self.total:.2f}; "
"re-read the line items and the total")
return self
def business_checks(invoice: Invoice, today: date) -> list[str]:
"""Layer 4: your organization's rules. Failing these is not the model's fault; don't retry."""
flags = []
if invoice.total > 10_000:
flags.append("total over 10,000: needs a second approver")
if invoice.issue_date > today:
flags.append("issue date is in the future")
if abs((invoice.issue_date - today).days) > 366:
flags.append("issue date is more than a year from today")
return flags- Normalization before checking (
mode="before"):currencyaccepts"gbp"," £"or"GBP"and turns them into the code before theLiteralcheck runs. This is the fix for Anthropic's enum casing, and for models that write a symbol where you asked for a code. - Cross-field rules (
@model_validator(mode="after")): the due date isn't before the issue date, and the line items add up to the total (computed withDecimal, so floating-point noise doesn't fail a correct invoice). - Grounding (
ValidationInfo.context):invoice_numberandtotalmust appear in the source document. You pass the document at validation time withInvoice.model_validate_json(text, context={"document": doc}), and the check is skipped when no document is given. It catches a whole class of invention: a total the model computed (or made up) rather than copied. - Business rules live outside the model, in
business_checks, because failing them is not the model's fault and shouldn't trigger a retry.
Error messages are feedback. The text of each ValueError is what the model will read on a retry (Part 7), so write it as an instruction: "lines add up to 110.00 but total is 101.00; re-read the line items and the total" is useful, "invalid total" isn't.
The layers on seven replies a model might give (pure Python, no network):
# s6_3_validation_layers.py
"""Validation in layers on model output: parse -> schema -> semantic validators -> business rules."""
import json
from datetime import date
from pydantic import ValidationError
from invoice_model import Invoice, business_checks
TODAY = date(2026, 11, 4)
LINES = '[{"description": "Tyres", "quantity": 2, "unit_price": 45.0}, ' \
'{"description": "Fitting", "quantity": 1, "unit_price": 20.0}]'
OUTPUTS = {
"good": f'{{"invoice_number": "INV-2041", "issue_date": "2026-11-02", "due_date": "2026-12-02", '
f'"currency": "GBP", "lines": {LINES}, "total": 110.0}}',
"truncated": '{"invoice_number": "INV-2041", "issue_date": "2026-11-02", "due_d',
"wrong type": f'{{"invoice_number": "INV-2041", "issue_date": "2 Nov 2026", "due_date": null, '
f'"currency": "GBP", "lines": {LINES}, "total": 110.0}}',
"symbol £": f'{{"invoice_number": "INV-2041", "issue_date": "2026-11-02", "due_date": null, '
f'"currency": " £", "lines": {LINES}, "total": 110.0}}',
"bad total": f'{{"invoice_number": "INV-2041", "issue_date": "2026-11-02", "due_date": null, '
f'"currency": "gbp", "lines": {LINES}, "total": 101.0}}',
"dates swapped": f'{{"invoice_number": "INV-2041", "issue_date": "2026-12-02", "due_date": "2026-11-02", '
f'"currency": "GBP", "lines": {LINES}, "total": 110.0}}',
"future, large": '{"invoice_number": "INV-9", "issue_date": "2027-01-05", "due_date": null, "currency": "EUR", '
'"lines": [{"description": "Lease", "quantity": 1, "unit_price": 12000}], "total": 12000}',
}
for label, text in OUTPUTS.items():
try:
json.loads(text) # layer 1: is it JSON at all?
except json.JSONDecodeError as err:
print(f"{label:14} layer 1 (parse) FAIL {err.msg}")
continue
try:
invoice = Invoice.model_validate_json(text) # layers 2 and 3 in one call
except ValidationError as err:
e = err.errors()[0]
layer = "layer 3 (semantic)" if e["type"] == "value_error" else "layer 2 (schema) "
print(f"{label:14} {layer} FAIL {'.'.join(map(str, e['loc'])) or '(model)'}: {e['msg']}")
continue
flags = business_checks(invoice, TODAY) # layer 4: route, don't retry
status = f"layer 4 (business) FLAG {'; '.join(flags)}" if flags else "all layers OK "
print(f"{label:14} {status} currency={invoice.currency} total={invoice.total}")good all layers OK currency=GBP total=110.0
truncated layer 1 (parse) FAIL Unterminated string starting at
wrong type layer 2 (schema) FAIL issue_date: Input should be a valid date or datetime, invalid character in year
symbol £ all layers OK currency=GBP total=110.0
bad total layer 3 (semantic) FAIL (model): Value error, lines add up to 110.00 but total is 101.00; re-read the line items and the total
dates swapped layer 3 (semantic) FAIL (model): Value error, due_date 2026-11-02 is before issue_date 2026-12-02
future, large layer 4 (business) FLAG total over 10,000: needs a second approver; issue date is in the future currency=EUR total=12000.0Each failure is caught at the cheapest layer that can see it, and the error says which field and why. Note the last row: a schema-valid, internally consistent invoice that your business rules still flag. That's the row a retry must not touch.
6.4 Three non-answers: refusal, truncation, safety block#
Before layer 1, check for the three ways a provider can return HTTP 200 without an answer (and a fourth catch-all, below the table). They need different handling, so they must not collapse into "invalid output":
| Outcome | What it means | What to do |
|---|---|---|
| Refused | The model declined (its own judgement, or a classifier) | Don't retry the same input; log the category; a person or a fallback flow. Lesson 02.10, 14.3 covers detection; 03.8 covers errors that arrive as 200s |
| Truncated | It ran out of output tokens (or context) mid-answer | Never parse or repair; retry with a larger budget up to a ceiling, or ask for less (02.5, 4.6) |
| Blocked | A safety system stopped the prompt or the answer | Don't retry unchanged; log the reason; show a fallback |
Where each provider reports them, as of November 2026:
| Provider | Refused | Truncated | Blocked |
|---|---|---|---|
| OpenAI Responses | A refusal content item in the message (status is still "completed") |
status: "incomplete", incomplete_details.reason: "max_output_tokens" |
status: "incomplete", reason "content_filter" |
| OpenAI Chat | message.refusal is set |
finish_reason: "length" (LengthFinishReasonError from .parse) |
finish_reason: "content_filter" (ContentFilterFinishReasonError from .parse) |
| Anthropic | stop_reason: "refusal", with stop_details.category |
stop_reason: "max_tokens" or "model_context_window_exceeded" |
Reported as a refusal (stop_reason: "refusal"); there is no separate block signal |
| Provider | Refused | Truncated | Blocked |
|---|---|---|---|
Gemini generate_content |
Usually a block (next column), or a decline in plain text | finish_reason: MAX_TOKENS |
prompt_feedback.block_reason (prompt blocked: no candidates), or a finish_reason such as SAFETY, PROHIBITED_CONTENT, BLOCKLIST, SPII, RECITATION |
| Gemini Interactions | No refusal field is documented: a decline arrives as plain text with status: "completed" |
status: "incomplete" ("completed, but contains incomplete results (e.g. hitting max_tokens)") |
Not documented. As of November 2026 Google's reference lists safety_settings on the request but not which status or field reports a block. Read interaction.errors (code, message) on a failed status, log it, and test a blocked prompt yourself |
| OpenRouter (Chat) | message.refusal, or a decline in text |
finish_reason: "length" |
finish_reason: "content_filter"; the provider's own value in native_finish_reason |
| OpenRouter (Responses) | As OpenAI Responses | As OpenAI Responses | As OpenAI Responses (extraction_from_openai_response serves both) |
The fourth case is error: a response that is none of the above and carries nothing to validate. OpenAI Responses status of failed or cancelled (with response.error); an OpenRouter Chat response with HTTP 200 and an error body (no choices); Anthropic stop_reason of pause_turn or tool_use; Gemini generate_content with no candidates and no block reason, or a finish_reason such as OTHER; Interactions failed, cancelled, requires_action, requires_continuation, budget_exceeded or queued. These are not safety blocks, and they are not validation failures: there is no text to show the model, so Part 7 retries them without a feedback turn.
6.5 Try it: one outcome type for every provider#
outcomes.py turns each provider's raw response (from create(), not parse()) into one of six outcomes, in the order that matters: blocked, refused, truncated, error, and only then parse and validate. It has a handler for every path Part 3 teaches: OpenAI Responses (also OpenRouter's Responses API), Chat Completions (also OpenRouter's Chat API), Anthropic, Gemini generate_content and Gemini Interactions. It's the foundation for Part 7. Its result type is called Extraction (one provider reply, classified), not Outcome: lesson 03.8 has a check_response.Outcome of its own, and the two modules can sit in one folder without shadowing each other. The functions are named extraction_from_* for the same reason (03.7 owns from_*).
# outcomes.py: turn each provider's response into one of six outcomes, BEFORE parsing.
# (The class is called Extraction, not Outcome, so it never clashes with check_response.Outcome from lesson 03.8.)
"""Order of checks, on every provider: blocked? refused? truncated? failed? Only then parse and validate.
Each function takes the provider's raw response object (from .create(), not .parse()),
so a truncated or refused reply never reaches the JSON parser by accident.
"""
from dataclasses import dataclass, field
from typing import Any, Generic, Literal, TypeVar
from anthropic.types import Message
from google.genai import types as gtypes
from google.genai.interactions import Interaction
from openai.types.chat import ChatCompletion
from openai.types.responses import Response
from pydantic import BaseModel, ValidationError
M = TypeVar("M", bound=BaseModel)
# "invalid" means "the model wrote text that failed validation": the only kind a retry can feed errors back to.
# "error" means the provider ended in a state that is none of the others (failed, cancelled, no
# candidates, an unexpected stop reason): there is nothing to show the model, so it is not a validation retry.
Kind = Literal["ok", "refused", "blocked", "truncated", "invalid", "error"]
@dataclass
class Extraction(Generic[M]):
kind: Kind
value: M | None = None
raw_text: str = "" # what the model wrote (for retries and logs)
detail: str = "" # refusal text, block reason, validation errors
errors: list[str] = field(default_factory=list) # validation errors, one per line, for feedback
def validate(model: type[M], text: str, context: dict[str, Any] | None = None) -> "Extraction[M]":
"""The last step on every provider: JSON syntax, the schema, and your own validators.
`context` reaches validators as info.context (e.g. the source document, for grounding checks)."""
try:
return Extraction("ok", model.model_validate_json(text, context=context), raw_text=text)
except ValidationError as err:
errors = [f"{'.'.join(map(str, e['loc'])) or '(root)'}: {e['msg']}" for e in err.errors()]
return Extraction("invalid", raw_text=text, detail=f"{len(errors)} validation error(s)", errors=errors)
def extraction_from_openai_response(r: Response, model: type[M], context: dict[str, Any] | None = None) -> "Extraction[M]":
for item in r.output:
if item.type == "message":
for part in item.content:
if part.type == "refusal": # does not follow the schema
return Extraction("refused", detail=part.refusal)
if r.status == "incomplete":
reason = r.incomplete_details.reason if r.incomplete_details else None
if reason == "content_filter":
return Extraction("blocked", raw_text=r.output_text, detail="content_filter")
return Extraction("truncated", raw_text=r.output_text, detail=str(reason))
if r.status != "completed": # failed, cancelled, queued, in_progress
why = f" ({r.error.code}: {r.error.message})" if r.error else ""
return Extraction("error", detail=f"status={r.status}{why}")
return validate(model, r.output_text, context)
def extraction_from_openai_chat(c: ChatCompletion, model: type[M], context: dict[str, Any] | None = None) -> "Extraction[M]":
if not c.choices: # OpenRouter can send an error body with HTTP 200
return Extraction("error", detail=f"no choices: {(c.model_extra or {}).get('error')}")
choice = c.choices[0] # also OpenRouter's shape
if choice.message.refusal:
return Extraction("refused", detail=choice.message.refusal)
if choice.finish_reason == "content_filter":
native = (choice.model_extra or {}).get("native_finish_reason") # OpenRouter adds this
return Extraction("blocked", detail=f"content_filter (native: {native})")
if choice.finish_reason == "length":
return Extraction("truncated", raw_text=choice.message.content or "", detail="length")
if choice.finish_reason != "stop": # tool_calls, function_call: not our answer
return Extraction("error", detail=f"unexpected finish_reason={choice.finish_reason}")
return validate(model, choice.message.content or "", context)
def extraction_from_anthropic(m: Message, model: type[M], context: dict[str, Any] | None = None) -> "Extraction[M]":
text = "".join(b.text for b in m.content if b.type == "text") # skip thinking blocks
if m.stop_reason == "refusal": # HTTP 200; may not match the schema
category = m.stop_details.category if m.stop_details else None
return Extraction("refused", raw_text=text, detail=f"refusal (category: {category})")
if m.stop_reason in ("max_tokens", "model_context_window_exceeded"):
return Extraction("truncated", raw_text=text, detail=m.stop_reason)
if m.stop_reason != "end_turn":
return Extraction("error", detail=f"unexpected stop_reason={m.stop_reason}")
return validate(model, text, context)
GEMINI_BLOCKED = {"SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY", "LANGUAGE"}
def extraction_from_gemini(r: gtypes.GenerateContentResponse, model: type[M], context: dict[str, Any] | None = None) -> "Extraction[M]":
if r.prompt_feedback and r.prompt_feedback.block_reason: # the prompt itself was blocked
return Extraction("blocked", detail=f"prompt blocked: {r.prompt_feedback.block_reason.value}")
if not r.candidates:
return Extraction("error", detail="no candidates")
reason = r.candidates[0].finish_reason
name = reason.value if reason else "UNSPECIFIED"
text = r.text or ""
if name in GEMINI_BLOCKED:
return Extraction("blocked", raw_text=text, detail=f"finish_reason={name}")
if name == "MAX_TOKENS":
return Extraction("truncated", raw_text=text, detail=name)
if name != "STOP":
return Extraction("error", detail=f"finish_reason={name}") # OTHER, MALFORMED_FUNCTION_CALL, ...
return validate(model, text, context) # don't trust r.parsed: it is None on any failure
def extraction_from_gemini_interaction(i: Interaction, model: type[M], context: dict[str, Any] | None = None) -> "Extraction[M]":
"""Interactions has no finish_reason. The documented signal is `status`: "completed",
"incomplete" ("completed, but contains incomplete results (e.g. hitting max_tokens)") or one
of the states below. As of November 2026 Google's reference doesn't say which status or field
reports a safety block (the request side has `safety_settings`), so no outcome is "blocked"
here: read `i.errors` and log it, and test a blocked prompt before you assume anything."""
if i.status == "incomplete":
return Extraction("truncated", raw_text=i.output_text or "", detail="status=incomplete")
if i.status != "completed": # failed, cancelled, requires_action, requires_continuation, budget_exceeded, ...
problems = "; ".join(f"{e.code}: {e.message}" for e in i.errors or [])
return Extraction("error", detail=f"status={i.status}" + (f" ({problems})" if problems else ""))
return validate(model, i.output_text or "", context)Every provider and every outcome, on mock servers whose fixtures copy each API's documented response shape (layer 3; the Interactions failed fixture is modelled on the SDK's Interaction type, because Google's reference shows no example of one); the last block shows the Chat Completions helper's two exceptions, including LengthFinishReasonError:
# s6_5_outcomes.py
"""Refusals, truncation, safety blocks, provider errors and invalid output as distinct outcomes, on MOCK servers.
Every fixture copies the documented response shape of its provider (sources in the lesson).
The Interactions "failed" fixture is modelled on the SDK's Interaction type: the docs show no example.
The real SDKs parse them; outcomes.py classifies them. Nothing leaves the machine.
"""
from typing import Literal
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from pydantic import BaseModel, Field
from outcomes import (extraction_from_anthropic, extraction_from_gemini, extraction_from_gemini_interaction, extraction_from_openai_chat,
extraction_from_openai_response)
class Refund(BaseModel):
amount: float = Field(ge=0)
currency: Literal["GBP", "EUR", "USD"]
OK, BAD, CUT = '{"amount": 42.5, "currency": "GBP"}', '{"amount": -3, "currency": "gbp"}', '{"amount": 42.5, "curr'
def openai_resp(text: str = OK, status: str = "completed", reason: str | None = None, refusal: str | None = None):
part = {"type": "refusal", "refusal": refusal} if refusal else {"type": "output_text", "text": text, "annotations": []}
return {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-6-luna", "status": status,
"incomplete_details": {"reason": reason} if reason else None,
"output": [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed", "content": [part]}]}
def chat(text: str | None = OK, finish: str = "stop", refusal: str | None = None, native: str | None = None):
choice = {"index": 0, "finish_reason": finish, "message": {"role": "assistant", "content": text, "refusal": refusal}}
if native:
choice["native_finish_reason"] = native # an OpenRouter extra field
return {"id": "c1", "object": "chat.completion", "created": 0, "model": "gpt-6-luna", "choices": [choice],
"usage": {"prompt_tokens": 30, "completion_tokens": 12, "total_tokens": 42}}
def claude(text: str = OK, stop: str = "end_turn", category: str | None = None):
return {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": text}] if text else [], "stop_reason": stop,
"stop_details": {"type": "refusal", "category": category, "explanation": "..."} if category else None,
"usage": {"input_tokens": 30, "output_tokens": 12}}
def gemini(text: str = OK, finish: str = "STOP", block: str | None = None):
if block:
return {"promptFeedback": {"blockReason": block}} # no candidates at all
return {"candidates": [{"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": finish}]}
def interaction(text: str = OK, status: str = "completed", errors: list[dict] | None = None):
body = {"id": "int_1", "status": status, "model": "gemini-3.8-flash",
"steps": [{"type": "model_output", "content": [{"type": "text", "text": text}]}] if text else [],
"usage": {"total_input_tokens": 30, "total_output_tokens": 12}}
if errors:
body["errors"] = errors
return body
def queue(fixtures: list[dict], lib):
replies = iter(fixtures)
return lib.MockTransport(lambda request: lib.Response(200, json=next(replies)))
CASES: dict[str, list[tuple[str, dict]]] = {
"OpenAI Responses": [
("schema-valid", openai_resp()),
("refusal item", openai_resp(refusal="I'm sorry, I can't help with that.")),
("incomplete: max_output_tokens", openai_resp(CUT, "incomplete", "max_output_tokens")),
("incomplete: content_filter", openai_resp("", "incomplete", "content_filter")),
("valid JSON, wrong values", openai_resp(BAD)),
("status: failed", {**openai_resp(""), "status": "failed", "output": [],
"error": {"code": "server_error", "message": "The model failed."}})],
"OpenAI Chat / OpenRouter": [
("schema-valid", chat()),
("message.refusal", chat(None, refusal="I'm sorry, I can't help with that.")),
("finish_reason: length", chat(CUT, "length")),
("finish_reason: content_filter", chat(None, "content_filter", native="SAFETY")),
("valid JSON, wrong values", chat(BAD)),
# OpenRouter's documented shape for a failure with HTTP 200: a bare error body, no `choices` at all
("HTTP 200 with an error body", {"error": {"code": 502, "message": "Provider returned error"}})],
"Anthropic": [
("schema-valid", claude()),
("stop_reason: refusal (cyber)", claude("", "refusal", "cyber")),
("stop_reason: max_tokens", claude(CUT, "max_tokens")),
("refusal, category null", claude("", "refusal", None)),
("valid JSON, wrong values", claude(BAD)),
("stop_reason: pause_turn", claude("", "pause_turn"))],
"Gemini": [
("schema-valid", gemini()),
("finish_reason: SAFETY", gemini("", "SAFETY")),
("finish_reason: MAX_TOKENS", gemini(CUT, "MAX_TOKENS")),
("prompt blocked", gemini(block="PROHIBITED_CONTENT")),
("valid JSON, wrong values", gemini(BAD)),
("finish_reason: OTHER", gemini("", "OTHER")),
("no candidates, no block", {"candidates": []})],
"Gemini Interactions": [
("status: completed", interaction()),
("status: incomplete", interaction(CUT, "incomplete")),
("status: failed", interaction("", "failed", [{"code": "internal", "message": "Internal error."}])),
("status: requires_action", interaction("", "requires_action")),
("valid JSON, wrong values", interaction(BAD))],
}
oai = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(
transport=queue([f for _, f in CASES["OpenAI Responses"]], httpx2)))
oai_chat = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(
transport=queue([f for _, f in CASES["OpenAI Chat / OpenRouter"]], httpx2)))
ant = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(
transport=queue([f for _, f in CASES["Anthropic"]], httpx2)))
gem = genai.Client(api_key="test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=queue([f for _, f in CASES["Gemini"]], httpx))))
ints = genai.Client(api_key="test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=queue([f for _, f in CASES["Gemini Interactions"]], httpx))))
for name, cases in CASES.items():
print(f"===== {name} =====")
for label, _fixture in cases:
if name == "OpenAI Responses":
out = extraction_from_openai_response(oai.responses.create(model="gpt-6-luna", input="..."), Refund)
elif name.startswith("OpenAI Chat"):
out = extraction_from_openai_chat(oai_chat.chat.completions.create(
model="gpt-6-luna", messages=[{"role": "user", "content": "..."}]), Refund)
elif name == "Anthropic":
out = extraction_from_anthropic(ant.messages.create(model="claude-haiku-5-5", max_tokens=200,
messages=[{"role": "user", "content": "..."}]), Refund)
elif name == "Gemini":
out = extraction_from_gemini(gem.models.generate_content(model="gemini-3.8-flash", contents="..."), Refund)
else:
out = extraction_from_gemini_interaction(ints.interactions.create(model="gemini-3.8-flash", input="...",
store=False), Refund)
shown = out.value if out.kind == "ok" else (out.errors or out.detail)
print(f" {label:30} -> {out.kind:9} {shown}")
# The Chat Completions parse helper raises instead of returning, for truncation and filtering
print("===== chat.completions.parse raises =====")
helper = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(
transport=queue([chat(CUT, "length"), chat(None, "content_filter")], httpx2)))
for _ in range(2):
try:
helper.chat.completions.parse(model="gpt-6-luna", messages=[{"role": "user", "content": "..."}],
response_format=Refund)
except openai.LengthFinishReasonError as err: # err.completion keeps usage for your logs
print(f" LengthFinishReasonError: completion_tokens={err.completion.usage.completion_tokens}")
except openai.ContentFilterFinishReasonError as err:
print(f" ContentFilterFinishReasonError: {err}")===== OpenAI Responses =====
schema-valid -> ok amount=42.5 currency='GBP'
refusal item -> refused I'm sorry, I can't help with that.
incomplete: max_output_tokens -> truncated max_output_tokens
incomplete: content_filter -> blocked content_filter
valid JSON, wrong values -> invalid ['amount: Input should be greater than or equal to 0', "currency: Input should be 'GBP', 'EUR' or 'USD'"]
status: failed -> error status=failed (server_error: The model failed.)
===== OpenAI Chat / OpenRouter =====
schema-valid -> ok amount=42.5 currency='GBP'
message.refusal -> refused I'm sorry, I can't help with that.
finish_reason: length -> truncated length
finish_reason: content_filter -> blocked content_filter (native: SAFETY)
valid JSON, wrong values -> invalid ['amount: Input should be greater than or equal to 0', "currency: Input should be 'GBP', 'EUR' or 'USD'"]
HTTP 200 with an error body -> error no choices: {'code': 502, 'message': 'Provider returned error'}
===== Anthropic =====
schema-valid -> ok amount=42.5 currency='GBP'
stop_reason: refusal (cyber) -> refused refusal (category: cyber)
stop_reason: max_tokens -> truncated max_tokens
refusal, category null -> refused refusal (category: None)
valid JSON, wrong values -> invalid ['amount: Input should be greater than or equal to 0', "currency: Input should be 'GBP', 'EUR' or 'USD'"]
stop_reason: pause_turn -> error unexpected stop_reason=pause_turn
===== Gemini =====
schema-valid -> ok amount=42.5 currency='GBP'
finish_reason: SAFETY -> blocked finish_reason=SAFETY
finish_reason: MAX_TOKENS -> truncated MAX_TOKENS
prompt blocked -> blocked prompt blocked: PROHIBITED_CONTENT
valid JSON, wrong values -> invalid ['amount: Input should be greater than or equal to 0', "currency: Input should be 'GBP', 'EUR' or 'USD'"]
finish_reason: OTHER -> error finish_reason=OTHER
no candidates, no block -> error no candidates
===== Gemini Interactions =====
status: completed -> ok amount=42.5 currency='GBP'
status: incomplete -> truncated status=incomplete
status: failed -> error status=failed (internal: Internal error.)
status: requires_action -> error status=requires_action
valid JSON, wrong values -> invalid ['amount: Input should be greater than or equal to 0', "currency: Input should be 'GBP', 'EUR' or 'USD'"]
===== chat.completions.parse raises =====
LengthFinishReasonError: completion_tokens=12
ContentFilterFinishReasonError: Could not parse response content as the request was rejected by the content filterEvery row lands in the right bucket, and the "valid JSON, wrong values" rows show both layer-2 errors at once (an amount below zero, and a lower-case currency the Literal rejects). Four details worth noting:
- The order of checks. A refusal is checked before the status, because OpenAI reports it inside a
"completed"response. Truncation is checked before parsing, so a cut-off reply can never be mistaken for bad output and retried with the same budget. A provider state with no text (failed,pause_turn, no candidates) is anerror, not aninvalid: nothing was written, so there is nothing to feed back. - The HTTP-200 error body has no
choicesat all. OpenRouter documents that a non-streaming failure can arrive as a200 OKwhose JSON holds only anerrorobject, and the mock sends exactly that. With theopenaiSDK's default settings (non-strict response validation), the missing required fields of theChatCompletionare simplyNoneand the unknownerrorkey lands inmodel_extra, sochoicesisNone, not[]: that is whyextraction_from_openai_chattestsnot c.choices, which catches both. If you create the client with strict response validation (the_strict_response_validationoption, used in some test suites), the same body raisesAPIResponseValidationErrorfromcreate()instead, before your classifier sees it, so keep the call inside your error handling as well (03.8). - Interactions is the thinnest row. Its
statustells you finished, cut off or failed, but nothing documented tells you why a prompt was blocked, so the handler never returnsblocked. If you rely on Interactions for user-supplied text, test a prompt that should be blocked and see whichstatusanderrorscome back. raw_textis kept on every outcome that has text. A retry needs to show the model what it wrote, and your logs need it too (lesson 03.10 covers what to log, and what to redact).
Part 7: Validate-and-retry, provider-native#
7.1 From the defensive wrapper to production#
Lesson 02.10, 21.3 built the core pattern (validate, retry with the exact error, fall back to a person) around prompt-plus-parse, and explained why feeding the error back works: it gives the model new, external information to correct against. The production version keeps that core and adds what a real system needs:
| 02.10's wrapper | Production extractor |
|---|---|
| Prompt plus parse | The provider's native structured output (rung 3), so format failures are rare |
| One kind of failure | Six outcomes, checked before parsing: refused, blocked, truncated and provider errors are not retried like invalid output |
| Retry the same model | Bounded retries per model, then escalation to a stronger model with a fresh conversation |
Return None |
A typed result with a status, every attempt's model, outcome, tokens and latency, and the last errors for a reviewer |
| Schema checks | Schema plus semantic validators plus grounding in the source document |
7.2 The design#
stateDiagram-v2
[*] --> Call
Call --> Ok: valid
Call --> Refused: refusal or safety block
Call --> Truncated: token limit hit
Call --> Invalid: parse, schema or validator error
Call --> Failed: HTTP error or provider error state
Truncated --> Call: budget below ceiling, raise it
Truncated --> GiveUpTruncated: at the ceiling
Invalid --> Call: tries left, feed the errors back
Invalid --> Escalate: tries used up
Failed --> Stop: not retryable (auth, quota, bad request)
Failed --> Call: retryable, tries left, ask again as is
Failed --> Escalate: tries used up
Escalate --> Call: next model, fresh conversation
Escalate --> Review: no models left
Ok --> [*]
Refused --> Review
GiveUpTruncated --> Review
Stop --> Review
Review --> [*]The decisions, and why:
- Invalid → retry with the errors, as a new user turn after the model's own reply (prefill is gone, lesson 03.2, 4.2). Send at most ten errors, phrased as instructions, plus the standing advice to use
nullrather than guess. - Bound the retries per model (two is plenty). Each retry re-sends the document, the schema, the previous answer and the errors, so a retry costs more than the first call (10.1 shows the prompt growing).
- Escalate with a fresh conversation. The stronger model doesn't need to see the weaker one's mistakes, and a clean prompt is cheaper.
- Truncated → raise the budget, without counting it as a try, up to a ceiling; then give up with
truncated(a different fix: ask for less, or split, 5.5). - Refused or blocked → stop. Retrying the same input is unlikely to change a classifier's mind and may look like probing. Route it to a person, with the category.
- Call failed or the provider ended in an error state → ask again, without a feedback turn. Two different things land here. An HTTP error raised by the SDK goes through 03.8's
llm_errors.classify(): a non-retryable kind (bad key, no quota, a 400 for a bad schema) stops at once with statuserror, because retrying pays for the same failure; a retryable kind (the SDK has already retried 429s and 5xx with backoff) gets one more try after a short pause. A response that finished in a state with no text (failed,pause_turn, no candidates, 6.4) is retried as it was. In neither case is there anything to show the model, so no assistant turn is added: an empty assistant message is a request bug on Anthropic ("text content blocks must be non-empty") and lesson 03.2, 5.4 defines how no-text turns are handled. The same rule covers aninvalidreply whose text is empty. - Reasoning is budgeted, not forgotten. Current models think by default, thinking tokens count against the output cap, and they are billed as output (02.8). Each backend therefore takes one portable
effort("low"by default: OpenAIreasoning.effort, Claudeoutput_config.effort, Geminithinking_level; Claude's thinking stays adaptive), and the first budget is 4,000 tokens, with a 16,000 ceiling, so thinking plus the answer fits. If a reply is still cut off, the truncation branch doubles the budget. Passeffort=Noneto send nothing and keep the model's own default. (Models differ in the levels they accept:lowworks on every model in this lesson's ladders,noneonly on some OpenAI models.) - Everything else → human review, with the last errors attached so the reviewer knows what to check.
- Business rules run after a successful extraction, outside the retry loop.
7.3 Try it: a production extractor#
extractor.py implements the design for three provider-native backends: OpenAI Responses (create with a strict text.format), Anthropic (create with output_config.format) and Gemini generate_content (response_json_schema, 3.4). It imports classify from llm_errors.py, the module built in lesson 03.8, 4.4. Each backend makes one call and returns an Extraction from outcomes.py, so the retry logic is written once:
# extractor.py: a provider-native validate-and-retry extractor with escalation and a result type.
"""extract() runs one schema against one provider backend:
call failed (HTTP error) -> llm_errors.classify() (lesson 03.8): retryable? try again; else stop
check the outcome first (refused / blocked / truncated / error) -> validate (schema + your validators)
invalid: feed the exact errors back and retry, up to `attempts_per_model`
provider "error" state or an empty reply: ask the same question again (no feedback turn: nothing to show)
still failing: escalate to the next model in `models`, with a fresh conversation
all models exhausted: "invalid_after_retries" (or "error"), for human review
Needs llm_errors.py and retry_after.py from lesson 03.8 (4.4 and 7.3) in the same folder.
"""
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import Generic, Literal, TypeVar
import anthropic
import httpx
import openai
from anthropic import transform_schema
from google import genai
from google.genai import errors as genai_errors
from google.genai import types
from openai import OpenAI
from openai.lib._pydantic import to_strict_json_schema # private helper: may change in any openai release
from pydantic import BaseModel
from llm_errors import classify # lesson 03.8, 4.4
from outcomes import Extraction, extraction_from_anthropic, extraction_from_gemini, extraction_from_openai_response
M = TypeVar("M", bound=BaseModel)
Status = Literal["ok", "refused", "blocked", "truncated", "invalid_after_retries", "error"]
Effort = Literal["low", "medium", "high"]
Messages = list[dict[str, str]] # canonical turns: {"role": "user" | "assistant", "content": ...}
# What a failed call can raise from the three SDKs (the SDKs already retried 429s and 5xx themselves)
CALL_ERRORS = (openai.OpenAIError, anthropic.AnthropicError, genai_errors.APIError, httpx.HTTPError)
@dataclass
class Attempt:
model: str
kind: str
detail: str
raw_input_tokens: int # the provider's own input count: includes cached tokens on OpenAI and Gemini,
# excludes them on Anthropic. Not 03.7's `input` (uncached); convert with cost_calc.from_*
output_tokens: int # includes reasoning tokens: they are billed as output
seconds: float
@dataclass
class ExtractionResult(Generic[M]):
status: Status
value: M | None
attempts: list[Attempt] = field(default_factory=list)
errors: list[str] = field(default_factory=list) # the last errors, for a reviewer
@property
def needs_review(self) -> bool:
return self.status != "ok"
# A backend makes ONE provider-native call and returns (outcome, raw input tokens, output tokens)
Backend = Callable[[str, str, Messages, type[M], int, dict], tuple[Extraction[M], int, int]]
# Current models think by default, and thinking tokens count against the output cap. `effort` is
# the portable low/medium/high request: OpenAI reasoning.effort, Claude output_config.effort and
# Gemini thinking_level. None sends nothing, so the model's own default applies (and a local model
# that cannot think, like the 0.5B stand-in, doesn't get a setting it rejects with a 400).
def openai_backend(client: OpenAI, effort: Effort | None = "low") -> Backend:
def call(model: str, system: str, messages: Messages, schema: type[M], budget: int, context: dict):
r = client.responses.create(
model=model, instructions=system, input=messages, # type: ignore[arg-type] (role/content dicts)
max_output_tokens=budget, store=False,
reasoning={"effort": effort} if effort else openai.omit, # omit: send nothing at all
text={"format": {"type": "json_schema", "name": schema.__name__, "strict": True,
"schema": to_strict_json_schema(schema)}})
usage = r.usage
return extraction_from_openai_response(r, schema, context), usage.input_tokens if usage else 0, usage.output_tokens if usage else 0
return call
def anthropic_backend(client: anthropic.Anthropic, effort: Effort | None = "low") -> Backend:
def call(model: str, system: str, messages: Messages, schema: type[M], budget: int, context: dict):
config: anthropic.types.OutputConfigParam = {"format": {"type": "json_schema", "schema": transform_schema(schema)}}
if effort:
config["effort"] = effort # thinking itself stays adaptive (the default)
m = client.messages.create(
model=model, system=system, max_tokens=budget,
messages=messages, # type: ignore[arg-type] (role/content dicts are valid MessageParams)
output_config=config)
return extraction_from_anthropic(m, schema, context), m.usage.input_tokens, m.usage.output_tokens
return call
def gemini_backend(client: genai.Client, effort: Effort | None = "low") -> Backend:
def call(model: str, system: str, messages: Messages, schema: type[M], budget: int, context: dict):
contents = [types.Content(role="model" if t["role"] == "assistant" else "user",
parts=[types.Part.from_text(text=t["content"])]) for t in messages]
r = client.models.generate_content(model=model, contents=contents, config=types.GenerateContentConfig(
system_instruction=system, max_output_tokens=budget,
thinking_config=types.ThinkingConfig(thinking_level=types.ThinkingLevel(effort.upper())) if effort else None,
# Google's recommended field: standard JSON Schema, sent as written (3.4)
response_mime_type="application/json", response_json_schema=schema.model_json_schema()))
u = r.usage_metadata
out = ((u.candidates_token_count or 0) + (u.thoughts_token_count or 0)) if u else 0
return extraction_from_gemini(r, schema, context), (u.prompt_token_count or 0) if u else 0, out
return call
def feedback(errors: list[str]) -> str:
listed = "\n".join(f"- {e}" for e in errors[:10]) # bounded: don't echo 300 errors
return (f"Your previous answer failed validation:\n{listed}\n"
"Re-read the document and answer again with corrected values. If a value is not in the "
"document, use null where the schema allows it rather than guessing.")
def extract(backend: Backend, schema: type[M], document: str, *, system: str,
models: Sequence[str], attempts_per_model: int = 2,
budget: int = 4000, max_budget: int = 16000) -> ExtractionResult[M]:
"""`budget` must cover the thinking tokens AND the answer, or the first call comes back truncated."""
context = {"document": document} # for grounding validators
log: list[Attempt] = []
errors: list[str] = []
last_kind = "invalid"
for model in models: # escalation ladder: cheap -> strong
messages: Messages = [{"role": "user", "content": document}]
tries = 0
while tries < attempts_per_model:
started = time.perf_counter()
try:
outcome, tokens_in, tokens_out = backend(model, system, messages, schema, budget, context)
except CALL_ERRORS as exc: # the call itself failed: no outcome to read
failure = classify(exc) # 03.8: what went wrong, and may we retry?
detail = f"{failure.kind.value}: {failure.message[:100]}"
log.append(Attempt(model, "error", detail, 0, 0, round(time.perf_counter() - started, 2)))
if not failure.retryable: # auth, quota, a 400 for a bad schema: a retry
return ExtractionResult("error", None, log, [detail]) # pays for the same failure
tries, errors, last_kind = tries + 1, [detail], "error"
time.sleep(min(failure.retry_after or 0.5, 5.0)) # the SDK already backed off; keep this short
continue
log.append(Attempt(model, outcome.kind, outcome.detail, tokens_in, tokens_out,
round(time.perf_counter() - started, 2)))
if outcome.kind == "ok":
return ExtractionResult("ok", outcome.value, log)
if outcome.kind in ("refused", "blocked"): # retrying the same input won't help
return ExtractionResult(outcome.kind, None, log, [outcome.detail])
if outcome.kind == "truncated":
if budget >= max_budget: # ask for less, or split the task
return ExtractionResult("truncated", None, log, [outcome.detail])
budget = min(budget * 2, max_budget) # retry with room; doesn't count as a try
continue
tries += 1
last_kind = outcome.kind
if outcome.kind == "error": # failed, cancelled, odd stop reason: the model
errors = [outcome.detail] # wrote nothing to correct, so ask again as is
continue
errors = outcome.errors or [outcome.detail]
if outcome.raw_text.strip(): # feed back only when there IS a reply to answer:
messages += [{"role": "assistant", "content": outcome.raw_text}, # no prefill, and never an
{"role": "user", "content": feedback(errors)}] # empty assistant turn (03.2, 5.4)
# else: the model wrote nothing. Ask the same question again.
return ExtractionResult("error" if last_kind == "error" else "invalid_after_retries", None, log, errors)Each Attempt records raw_input_tokens, the provider's own input count, so a log line can show what an attempt cost roughly. It is not the module's input: from lesson 03.7, 3.1 on, input means uncached input tokens and total_input = input + cached + written, and the providers disagree about what their raw field holds (OpenAI's and Gemini's include cached tokens, Anthropic's excludes them). That doesn't matter for these short, uncached calls, but to price an attempt, keep the whole response and convert it with cost_calc.from_* instead of using this number.
Why create() and not the parse helpers: the helpers raise on truncation before you can see the finish reason (3.9), and the extractor must tell truncation from invalid output. The schemas come from the same transforms the helpers use (to_strict_json_schema, private, and transform_schema, public), and validation always runs against your original Pydantic model, with the document passed in as context for the grounding check.
Try it free, on the OpenAI Responses path (Ollama serves it; the Anthropic path needs output_config, which Ollama ignores, and Gemini has no local stand-in, so both are hosted-only: the same extract call works with anthropic_backend and gemini_backend and a hosted key). Two invoices: a simple one, and one with VAT:
# s7_3_extractor.py
"""Try it free: the validate-and-retry extractor on the local stand-in, OpenAI Responses path.
OpenAI Responses -> Ollama. (Anthropic needs output_config, which Ollama ignores, and Gemini has
no local stand-in: use anthropic_backend and gemini_backend with hosted keys.) The "stronger"
model in the ladder is an alias of the same 0.5B model locally, so escalation is shown, not its benefit.
"""
from datetime import date
from openai import OpenAI
from extractor import extract, openai_backend
from invoice_model import Invoice, business_checks
SYSTEM = "Extract the invoice. Copy numbers exactly as printed; use ISO dates (YYYY-MM-DD)."
SIMPLE = """INVOICE INV-2041 Date: 2 November 2026 Due: 2 December 2026
2 x Winter tyre @ £45.00 £90.00
1 x Fitting @ £20.00 £20.00
TOTAL DUE £110.00"""
WITH_TAX = """INVOICE INV-2042 Date: 3 November 2026
1 x Annual service @ £100.00 £100.00
Subtotal £100.00 VAT 20% £20.00
TOTAL DUE £120.00"""
# effort=None: the 0.5B model cannot think and rejects reasoning settings with a 400. Hosted, keep the default "low"
backends = {
"openai": (openai_backend(OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", timeout=60), effort=None),
["gpt-6-luna", "gpt-6.1-terra"]),
}
for provider, (backend, models) in backends.items():
for name, document in [("INV-2041", SIMPLE), ("INV-2042 (with VAT)", WITH_TAX)]:
result = extract(backend, Invoice, document, system=SYSTEM, models=models, attempts_per_model=2)
print(f"\n{provider} / {name}: {result.status}")
for a in result.attempts:
print(f" {a.model:17} {a.kind:9} in={a.raw_input_tokens:<4} out={a.output_tokens:<4} {a.seconds:>5}s {a.detail}")
if result.value:
print(" ->", result.value.model_dump(mode="json"))
flags = business_checks(result.value, today=date(2026, 11, 4))
if flags:
print(" business rules:", "; ".join(flags), "-> route to a person")
elif result.errors:
print(" last errors:", result.errors[:2])openai / INV-2041: ok
gpt-6-luna ok in=113 out=122 0.83s
-> {'invoice_number': 'INV-2041', 'issue_date': '2026-11-25', 'due_date': '2026-12-02', 'currency': 'GBP', 'lines': [{'description': 'Winter tyre', 'quantity': 2, 'unit_price': 45.0}, {'description': 'Fitting', 'quantity': 1, 'unit_price': 20.0}], 'total': 110.0}
business rules: issue date is in the future -> route to a person
openai / INV-2042 (with VAT): ok
gpt-6-luna invalid in=106 out=171 1.03s 1 validation error(s)
gpt-6-luna ok in=360 out=139 0.74s
-> {'invoice_number': 'INV-2042', 'issue_date': '3111-11-20', 'due_date': '3111-11-20', 'currency': 'GBP', 'lines': [{'description': 'Annual service', 'quantity': 1, 'unit_price': 100.0}, {'description': 'Subtotal', 'quantity': 1, 'unit_price': 20.0}], 'total': 120.0}
business rules: issue date is in the future; issue date is more than a year from today -> route to a personLocally, the "stronger" model in the ladder is an alias for the same 0.5B model, so this shows the mechanics of escalation, not its benefit; on hosted models the second rung (gpt-6.1-terra, claude-sonnet-5-5, gemini-4-argon) is where most of the remaining failures get fixed. The local sample passes effort=None because the 0.5B model can't think and rejects a reasoning setting with a 400; hosted, keep the default. Read the run closely, because the tiny model makes kinds of mistake that larger models make too, just less often:
- The simple invoice succeeds on the first attempt, and the attempt log shows what each call cost. One run still put a wrong issue date into a perfectly valid object (
2026-11-25when the invoice says 2 November), which only the business rule ("issue date is in the future") caught. - The VAT invoice fails validation on the first attempt: the lines add up to £100, the printed total is £120, and our rule says they must match. The retry's input grew from 106 to 360 tokens because it carries the document, the previous answer and the errors.
- On the retry, the model "fixed" the data to pass the rule. On its second attempt it invented a
Subtotalline item of £20.00 so that the lines add up to £120, and wrote an issue date in the year 3111. The grounding check passed (bothINV-2042and120.00are in the document) and so did the sum; only the business rules flagged the date. A validator the model can satisfy by changing the facts is a validator that will be satisfied that way. That's the subject of the next section.
7.4 When retries don't help#
Retrying with feedback fixes slips: a misread number, a wrong format, a forgotten field. It can't fix two things, and when they are the cause, more retries make results worse:
- The schema or the rule is wrong. Our consistency rule assumed lines add up to the total, which is false for any invoice with tax. Each retry pressured the model to make the data fit, and one complied by inventing a line. The fix is to change the schema: give tax its own field and make the rule
lines + tax = total. - The information isn't in the input. If an invoice has no due date and
due_datecan't be null, every retry produces a new invention. The fix is the unknown path (5.3).
Signs you're in this situation: the same validation error on every attempt, errors that move around between fields as the model shuffles values, and stronger models failing in the same way. Track failure reasons per field in production; a field that fails often is a schema problem, not a model problem.
Here is the schema fix, run three times against the stand-in:
# s7_4_fix_the_schema.py
"""When retries don't help, fix the schema: give the tax a field, and make the rule match reality."""
from decimal import Decimal
from openai import OpenAI
from pydantic import Field, model_validator
from extractor import extract, openai_backend
from invoice_model import Invoice
class InvoiceWithTax(Invoice):
tax: float = Field(ge=0, description="Total tax (VAT/GST) as printed, or 0 if the invoice shows none")
@model_validator(mode="after")
def check_consistency(self) -> "InvoiceWithTax": # same name: replaces the parent's rule
lines_sum = sum(Decimal(str(l.unit_price)) * l.quantity for l in self.lines)
if abs(lines_sum + Decimal(str(self.tax)) - Decimal(str(self.total))) > Decimal("0.01"):
raise ValueError(f"lines ({lines_sum:.2f}) plus tax ({self.tax:.2f}) must equal total ({self.total:.2f})")
return self
WITH_TAX = """INVOICE INV-2042 Date: 3 November 2026
1 x Annual service @ £100.00 £100.00
Subtotal £100.00 VAT 20% £20.00
TOTAL DUE £120.00"""
# effort=None: the local 0.5B model cannot think and rejects reasoning settings (hosted: keep the default)
backend = openai_backend(OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", timeout=60), effort=None)
for run in range(1, 4):
result = extract(backend, InvoiceWithTax, WITH_TAX, models=["gpt-6-luna", "gpt-6.1-terra"],
system="Extract the invoice. Copy numbers exactly as printed; use ISO dates (YYYY-MM-DD).")
v = result.value
print(f"run {run}: {result.status:22} attempts={len(result.attempts)}",
f"lines={[l.unit_price for l in v.lines]} tax={v.tax} total={v.total}" if v else result.errors[:1])run 1: ok attempts=1 lines=[100.0] tax=20.0 total=120.0
run 2: ok attempts=1 lines=[100.0, 20.0] tax=0.0 total=120.0
run 3: invalid_after_retries attempts=4 ['(root): Value error, lines (240.00) plus tax (2.40) must equal total (120.00)']With a tax field and an honest rule, run 1 extracts lines=[100.0] tax=20.0 total=120.0 on the first attempt, with no invented line items. Run 2 shows the limit of any rule: the model passed it by writing a £20.00 Subtotal line and tax=0.0, which is consistent and wrong. Only a grounding check on the rows (Exercise 6) or a person would notice. Run 3 failed every attempt and went to review, which is the extractor working as designed. A 0.5B model is erratic (in most other batches of this script at most one run in three succeeded, and this is the best of several batches, picked for what it shows); a hosted model fails such runs rarely. Subclassing with a validator of the same name replaces the parent's rule, which is how you version a schema without copying it.
7.5 Try it: the non-validation paths#
Everything above retried validation failures. The extractor also has paths for a call that fails and for a provider that ends in a state with no text. This sample exercises them without a model: fake backends play scripted outcomes and record the roles of the turns they were sent, and a mock OpenAI server raises real SDK exceptions (layer 3; max_retries=0 switches off the SDK's own retries so the extractor's handling is what you see):
# s7_5_extractor_failures.py
"""The extractor's non-validation paths, on fake backends and a MOCK OpenAI server (layer 3).
Checks what the conversation looks like on each retry: a retry after a provider "error" state or an
empty reply must not contain an empty assistant turn. Nothing leaves the machine.
"""
import httpx2
from openai import OpenAI
from pydantic import BaseModel, Field
from extractor import extract, openai_backend
from outcomes import Extraction, validate
class Refund(BaseModel):
amount: float = Field(ge=0)
def scripted(*steps: Extraction[Refund]):
"""A fake backend that plays the given outcomes in order and records the messages it was sent."""
seen: list[list[dict]] = []
queue = iter(steps)
def call(model, system, messages, schema, budget, context):
seen.append([dict(m) for m in messages])
return next(queue), 10, 5
return call, seen
def show(title: str, result, seen=None) -> None:
print(f"\n{title}: status={result.status}, attempts={[a.kind for a in result.attempts]}")
for i, turns in enumerate(seen or [], 1):
print(f" call {i} sent roles: {[t['role'] for t in turns]}")
GOOD = '{"amount": 5}'
ok = validate(Refund, GOOD)
backend, seen = scripted(Extraction("error", detail="status=failed (server_error: The model failed.)"), ok)
show("provider 'failed' state, then fine", extract(backend, Refund, "doc", system="s", models=["m"]), seen)
backend, seen = scripted(validate(Refund, ""), ok) # a completed reply with no text at all
show("empty reply, then fine", extract(backend, Refund, "doc", system="s", models=["m"]), seen)
backend, seen = scripted(validate(Refund, '{"amount": -1}'), ok) # text that broke a rule
show("invalid text, then fine (feedback sent)", extract(backend, Refund, "doc", system="s", models=["m"]), seen)
backend, seen = scripted(Extraction("error", detail="status=cancelled"), Extraction("error", detail="status=cancelled"))
show("error twice, one model", extract(backend, Refund, "doc", system="s", models=["m"]), seen)
# Real SDK exceptions from a mock server, classified by lesson 03.8's llm_errors.classify().
# max_retries=0 switches off the SDK's own retries, so the extractor's handling is what you see.
UNAUTHORIZED = (401, {"error": {"message": "Incorrect API key provided.", "type": "invalid_request_error",
"code": "invalid_api_key"}})
OVERLOADED = (503, {"error": {"message": "The server is overloaded.", "type": "server_error", "code": None}})
RESPONSE = (200, {"id": "resp_1", "object": "response", "created_at": 0, "model": "gpt-6-luna",
"status": "completed", "output": [{"type": "message", "id": "msg_1", "role": "assistant",
"status": "completed", "content": [{"type": "output_text", "text": GOOD, "annotations": []}]}]})
def openai_with(*replies: tuple[int, dict]):
queue = iter(replies)
transport = httpx2.MockTransport(lambda request: httpx2.Response((r := next(queue))[0], json=r[1]))
return openai_backend(OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=transport)),
effort=None)
result = extract(openai_with(UNAUTHORIZED, RESPONSE), Refund, "doc", system="s", models=["gpt-6-luna", "gpt-6.1-terra"])
show("HTTP 401 (not retryable)", result)
print(" detail:", result.errors)
result = extract(openai_with(OVERLOADED, RESPONSE), Refund, "doc", system="s", models=["gpt-6-luna"])
show("HTTP 503, then fine (retryable)", result)
print(" detail:", [a.detail for a in result.attempts])provider 'failed' state, then fine: status=ok, attempts=['error', 'ok']
call 1 sent roles: ['user']
call 2 sent roles: ['user']
empty reply, then fine: status=ok, attempts=['invalid', 'ok']
call 1 sent roles: ['user']
call 2 sent roles: ['user']
invalid text, then fine (feedback sent): status=ok, attempts=['invalid', 'ok']
call 1 sent roles: ['user']
call 2 sent roles: ['user', 'assistant', 'user']
error twice, one model: status=error, attempts=['error', 'error']
call 1 sent roles: ['user']
call 2 sent roles: ['user']
HTTP 401 (not retryable): status=error, attempts=['error']
detail: ['auth: Error code: 401 - Incorrect API key provided.']
HTTP 503, then fine (retryable): status=ok, attempts=['error', 'ok']
detail: ['overloaded: Error code: 503 - The server is overloaded.', '']- A provider
failedstate and an empty reply are retried with the conversation unchanged (['user']both times). Only the case with real text that broke a rule sends['user', 'assistant', 'user']: the model's reply and the errors. - Two
erroroutcomes in a row end as statuserror, notinvalid_after_retries: nothing was ever written, so there is nothing for a reviewer to correct, only an incident to look into. - The 401 is classified
authand stops at once, on the first model: the second model in the ladder would hit the same key problem. The 503 is classifiedoverloadedand retried, and the second call succeeds.llm_errors.classify()also tells you about quota, context-length and bad-request failures, andretry_after; the full taxonomy is lesson 03.8.
Part 8: Streaming partial objects#
Deep-dive
8.1 Why stream structured output, and the one rule#
Structured output and streaming pull in opposite directions: the schema guarantees a valid object at the end, and the stream gives you an invalid prefix of it at every moment before that. Backend code should simply wait for the end. Streaming earns its complexity only when a person is watching: a form that fills in field by field, a list of extracted items that grows, a long summary object whose title appears first. The mechanics (SSE, event types, each SDK's stream helper, and a table of which helpers partially parse for you) are in lesson 03.3, 6.3. This part adds the structured-output side: what is safe to show, and when.
The one rule: render drafts, act on the validated final object. Nothing from a partial object may trigger an action (a payment, a database write, an enabled "Submit" button), because any field can still change or be cut off, and none of it has passed your validators.
8.2 Partial JSON parsing, and which fields are "settled"#
pydantic_core.from_json(text, allow_partial=...) parses an incomplete JSON document into whatever is complete so far. The choice of mode matters for display, and so does a rule for which keys are finished. Pure Python, simulating the deltas a stream delivers:
# s8_2_partial_json.py
"""Rendering a half-written object safely: partial JSON parsing, with no network at all.
pydantic_core.from_json(..., allow_partial=...) parses an incomplete JSON document into
whatever is complete so far. We simulate the text deltas a stream delivers.
"""
from pydantic_core import from_json
FINAL = ('{"customer": "Ana Lima", "priority": "urgent", "items": [{"sku": "ABC-1234", "quantity": 2}, '
'{"sku": "XYZ-0042", "quantity": 1}], "gift_message": null}')
deltas = [FINAL[i:i + 18] for i in range(0, len(FINAL), 18)] # pretend each is one stream event
def settled(snapshot: dict) -> dict:
"""Keys before the last one are final (a later key has started); the last may still grow."""
keys = list(snapshot)
return {k: snapshot[k] for k in keys[:-1]}
buffer = ""
for i, delta in enumerate(deltas, 1):
buffer += delta
dropped = from_json(buffer, allow_partial=True) # drops an unfinished string
kept = from_json(buffer, allow_partial="trailing-strings") # keeps it, half-written
if i in (1, 4, 6, 8, len(deltas)):
print(f"delta {i:2}: ...{buffer[-24:]!r}")
print(f" allow_partial=True {dropped}")
print(f" 'trailing-strings' {kept}")
print(f" settled (safe to show) {settled(dropped)}")delta 1: ...'{"customer": "Ana '
allow_partial=True {}
'trailing-strings' {'customer': 'Ana '}
settled (safe to show) {}
delta 4: ...'items": [{"sku": "ABC-12'
allow_partial=True {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{}]}
'trailing-strings' {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-12'}]}
settled (safe to show) {'customer': 'Ana Lima', 'priority': 'urgent'}
delta 6: ...'ty": 2}, {"sku": "XYZ-00'
allow_partial=True {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {}]}
'trailing-strings' {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-00'}]}
settled (safe to show) {'customer': 'Ana Lima', 'priority': 'urgent'}
delta 8: ...'ty": 1}], "gift_message"'
allow_partial=True {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
'trailing-strings' {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}
settled (safe to show) {'customer': 'Ana Lima', 'priority': 'urgent'}
delta 9: ...'], "gift_message": null}'
allow_partial=True {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}], 'gift_message': None}
'trailing-strings' {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}], 'gift_message': None}
settled (safe to show) {'customer': 'Ana Lima', 'priority': 'urgent', 'items': [{'sku': 'ABC-1234', 'quantity': 2}, {'sku': 'XYZ-0042', 'quantity': 1}]}allow_partial=Truedrops an unfinished string, so you never display"Ana "as a customer name or"ABC-12"as an SKU. The price is an empty{}for the line item being written.allow_partial="trailing-strings"keeps it, which is what you want for text that grows naturally (a summary, a description), and what you don't want for identifiers and numbers.- "Settled" keys are the ones before the last key in the draft: because keys are generated in order, a later key starting means the earlier ones are done. Show settled fields normally and the last one as "still writing", or not at all. It's conservative:
itemsonly settles when the next key begins.
Key order is generated in schema order on OpenAI and Gemini (with propertyOrdering), and required-then-optional on Anthropic (4.1). If you stream to a UI, put what the user should see first at the top of the schema.
8.3 Try it: stream from the Responses API#
responses.stream(text_format=Order) streams raw JSON text: each response.output_text.delta event carries event.snapshot, the text so far, and the helper parses and validates only at the end. So the partial parsing is ours:
# s8_3_stream_partial.py
"""Try it free: stream a structured answer from the Responses API and render it as it grows.
responses.stream(text_format=Order) gives raw JSON text deltas (event.snapshot is the text so
far) and a validated object only at the end, so the partial parsing is ours.
"""
from openai import OpenAI
from pydantic_core import from_json
from order_model import Order
EMAIL = ("From: Ana Lima\nSent: 2 November 2026\n\nHi, please send 2 x ABC-1234 and 1 x XYZ-0042 "
"as soon as possible, it's urgent. No gift message needed. Thanks!")
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
def settled(snapshot: str) -> dict:
"""The keys that are finished: every key before the one still being written."""
draft = from_json(snapshot, allow_partial=True) if snapshot.strip() else {}
return dict(list(draft.items())[:-1])
with client.responses.stream(model="gpt-6-luna", instructions="Extract the order from the email.",
input=EMAIL, text_format=Order, max_output_tokens=400) as stream:
shown: dict = {}
for event in stream:
if event.type == "response.output_text.delta":
now = settled(event.snapshot)
if now != shown: # re-render only when a field settles
new = {k: v for k, v in now.items() if k not in shown}
print(" settled:", new)
shown = now
elif event.type == "response.refusal.delta": # a refusal streams as its own events
print(" refusal text:", event.delta)
final = stream.get_final_response() # the whole Response, parsed
print("status:", final.status)
print("validated:", final.output_parsed) # act on THIS, never on a draft settled: {'customer': 'Ana Lima'}
settled: {'order_date': '2026-11-02'}
settled: {'priority': 'urgent'}
settled: {'channel': 'email'}
settled: {'gift_message': None}
settled: {'discount_code': None}
status: completed
validated: customer='Ana Lima' order_date=datetime.date(2026, 11, 2) priority=<Priority.URGENT: 'urgent'> channel='email' gift_message=None discount_code=None items=[LineItem(sku='ABC-1234', quantity=2), LineItem(sku='XYZ-0042', quantity=1)]Each field appears once, when the next one starts. items never "settles" during the stream because nothing follows it, so a UI would show it as in-progress until the final object arrives, and only final.output_parsed (after you've checked final.status) is used for anything real. This run happened to get every field right, but the tiny model does not always: the Chat Completions run in 3.7 wrote an order_date in the year 2195. A draft can look complete and still be wrong; only validation and business rules can tell.
How the other SDKs differ, briefly (details and runnable samples in lesson 03.3, 6.3):
| SDK path | Partial object during the stream | Final object |
|---|---|---|
OpenAI chat.completions.stream(response_format=M) |
Yes: every content.delta event has parsed, a partial dict |
get_final_completion().choices[0].message.parsed |
OpenAI responses.stream(text_format=M) |
No: text snapshots; parse them yourself | get_final_response().output_parsed |
Anthropic messages.stream(output_format=M) |
No: text deltas | get_final_message().parsed_output. A truncated answer raises ValidationError inside the loop, before stop_reason arrives |
| SDK path | Partial object during the stream | Final object |
|---|---|---|
Gemini generate_content_stream(response_schema=M) |
No: chunk.parsed is always None |
Join chunk.text, then M.model_validate_json(...) |
Gemini Interactions (stream=True) |
No: join the text deltas | Validate yourself |
| OpenRouter | As the OpenAI helper you use; response healing does not apply to streams | As OpenAI |
Refusals stream too: on OpenAI Responses as response.refusal.delta events (handled in the sample), on Chat Completions as refusal deltas, on Anthropic as a final stop_reason: "refusal". A UI that renders drafts must be able to replace a half-drawn form with a refusal message.
Part 9: Patterns#
Deep-dive
The five shapes most structured-output work takes. Each is shown on the stand-in, where the tiny model's mistakes make the point of every safeguard; real evaluation of accuracy on real data is Module 10A's job. For brevity these samples call the parse helpers and treat any ValidationError as "invalid"; production code checks the outcome first and uses extract() from Part 7.
9.1 Classification with enums, evidence and confidence#
A classifier's schema has three parts, in this order: evidence (the words that decide it, quoted from the input), the category (an enum with an "other" value and a description of each category), and a confidence label. Then a small labelled set tells you whether it works at all:
# s9_1_classify.py
"""Try it free: classification with an enum, an evidence field and a confidence label,
plus a quick accuracy check on 10 labelled messages (a smoke test, not an evaluation)."""
from collections import Counter
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
Category = Literal["billing", "delivery", "technical", "account", "other"]
class TicketLabel(BaseModel):
evidence: str = Field(description="The few words of the message that decide the category, quoted exactly")
category: Category = Field(description="billing: charges, refunds, invoices. delivery: parcels, shipping. "
"technical: bugs, crashes, errors. account: login, password, profile. "
"other: anything else")
confidence: Literal["low", "medium", "high"]
LABELLED: list[tuple[str, Category]] = [
("I was charged twice for my subscription this month!", "billing"),
("My parcel says delivered but nothing arrived.", "delivery"),
("The app crashes every time I open settings.", "technical"),
("I can't log in, it says my password is wrong.", "account"),
("Please send me a copy of invoice INV-2041.", "billing"),
("The courier left my package in the rain.", "delivery"),
("Error 500 when I upload a photo.", "technical"),
("How do I change the email address on my profile?", "account"),
("Do you have a shop in Leeds?", "other"),
("I want a refund for the broken kettle.", "billing"),
]
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
results = []
for message, expected in LABELLED:
try:
r = client.responses.parse(model="gpt-6-luna", input=message, max_output_tokens=150,
instructions="Classify the customer message.", text_format=TicketLabel)
label = r.output_parsed
except ValidationError:
label = None
got = label.category if label else "INVALID"
grounded = bool(label) and label.evidence.lower() in message.lower() # is the quote really there?
results.append((expected, got, grounded))
print(f"{'ok ' if got == expected else 'BAD'} {expected:9} -> {got:9} "
f"{label.confidence if label else '':6} grounded={grounded!s:5} {message[:44]}")
correct = sum(e == g for e, g, _ in results)
print(f"\naccuracy {correct}/{len(results)}, evidence found in the message {sum(g for *_, g in results)}/{len(results)}")
print("confusions:", Counter((e, g) for e, g, _ in results if e != g).most_common())BAD billing -> other high grounded=False I was charged twice for my subscription this
ok delivery -> delivery high grounded=False My parcel says delivered but nothing arrived
ok technical -> technical high grounded=False The app crashes every time I open settings.
ok account -> account high grounded=False I can't log in, it says my password is wrong
ok billing -> billing high grounded=False Please send me a copy of invoice INV-2041.
BAD delivery -> other high grounded=False The courier left my package in the rain.
ok technical -> technical low grounded=False Error 500 when I upload a photo.
ok account -> account high grounded=False How do I change the email address on my prof
ok other -> other high grounded=False Do you have a shop in Leeds?
ok billing -> billing high grounded=True I want a refund for the broken kettle.
accuracy 8/10, evidence found in the message 1/10
confusions: [(('billing', 'other'), 1), (('delivery', 'other'), 1)]What the run teaches, beyond "8 out of 10 from a 0.5B model":
- Confidence labels are not probabilities. Both mistakes were labelled
high. Models report confidence poorly; a categoricallow/medium/highis at least easy to threshold and audit, but calibrate it against labelled data before you route on it (Module 10A). For a real probability, logprobs on the category token are a better signal where the provider offers them. - Evidence is checkable. Only one "quote" actually appeared in the message: the tiny model paraphrased the rest. A grounding check (is the evidence a substring of the input?) is a cheap semantic validator; failing it is a strong hint that the label deserves a second look. Make it a validator and the extractor will retry it (10.1 does exactly that with instructor).
- Ten examples is a smoke test, not an evaluation. It catches a broken prompt or schema; it can't tell 92% from 95%. Keep the labelled set in your repo and run it in CI, then build a real evaluation set (Module 10A).
- Normalize casing before comparing on Anthropic (2.3); the
Literalvalidation rejects"Billing"unless amode="before"validator lowers it first.
9.3 Nested lists: line items#
Invoices, orders, receipts and timesheets all have a header and a list of repeating rows. The invoice in Parts 6 and 7 is the template; the rules that make it reliable:
- A model for the row (
InvoiceLine), with a description on each field, and a bounded list of them (min_length=1, max_length=50). - Copy, don't compute. Ask for values "as printed", and do arithmetic in validators. A model asked for
line_totalmay multiply; a model asked to copy it copies. - Cross-check rows against the header (sum of lines plus tax equals the total, 7.4), and ground key values in the document.
- Very long tables: extract rows in pages ("rows 1 to 40", then "41 to 80"), because one huge array is the likeliest thing to hit the output limit, and on Gemini a large
maxItemson a nested array is a "too many states" risk. - Money: amounts as numbers in the schema,
Decimalin your code (6.3), currency as an ISO code with a normalizing validator. Never let floating-point arithmetic decide whether an invoice balances.
9.4 Many entities from long text#
When the input is long (a contract, a meeting transcript, a support thread) and you want every instance of something, one call over the whole text tends to miss items in the middle (02.7, Part 5) and risks truncation. The pattern is chunk, extract per chunk, merge:
# s9_4_multi_entity.py
"""Try it free: many entities from a long text: chunk, extract per chunk, merge and de-duplicate."""
from openai import OpenAI
from pydantic import BaseModel, Field
class ActionItem(BaseModel):
owner: str = Field(description="First name of the person who will do it")
task: str = Field(description="What they will do, in a few words")
due: str | None = Field(description="The deadline exactly as said, or null if none was given")
class ActionItems(BaseModel): # wrap the list: OpenAI needs an object at the root
items: list[ActionItem] = Field(max_length=20, description="Every action item in this part of the notes")
NOTES = """Meeting notes, 3 November.
Priya will send the revised quote to the customer by Friday.
Tom said the warehouse move is on track. Tom will book the van.
---
Ana raised the late invoices. Ana will chase the two oldest invoices this week.
Priya to send the revised quote (same as above, she confirmed).
---
Kenji will update the returns policy page. No date agreed.
Tom will book the van for the 12th."""
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
chunks = [c.strip() for c in NOTES.split("---")] # real code: split by tokens, with overlap
found: list[ActionItem] = []
for i, chunk in enumerate(chunks, 1):
r = client.responses.parse(model="gpt-6-luna", input=chunk, text_format=ActionItems, max_output_tokens=300,
instructions="List the action items in these meeting notes.")
items = r.output_parsed.items if r.output_parsed else []
print(f"chunk {i}: {len(items)} item(s): {[(a.owner, a.task) for a in items]}")
found += items
STOP = {"the", "a", "an", "to", "for", "of", "by", "on", "this", "same", "as"}
def words(item: ActionItem) -> set[str]:
return {w.strip(".,").lower() for w in item.task.split()} - STOP
def same_item(a: ActionItem, b: ActionItem) -> bool:
"""Same owner, and most of the shorter task's words appear in the longer one."""
if a.owner.strip().lower() != b.owner.strip().lower():
return False
wa, wb = words(a), words(b)
return len(wa & wb) / max(1, min(len(wa), len(wb))) >= 0.6
merged: list[ActionItem] = []
for item in found:
match = next((m for m in merged if same_item(m, item)), None)
if match is None:
merged.append(item)
elif match.due is None and item.due: # keep the version with more detail
merged[merged.index(match)] = item
print(f"\n{len(found)} extracted, {len(merged)} after de-duplication:")
for item in merged:
print(f" {item.owner:6} {item.task:40} due={item.due}")chunk 1: 2 item(s): [('Priya', 'Send revised quote to customer by Friday'), ('Tom', 'Book warehouse van for move on track')]
chunk 2: 2 item(s): [('Ana', 'Raised late invoices.'), ('Ana', 'Chase oldest two invoices this week.')]
chunk 3: 2 item(s): [('Kenji', 'Update Returns Policy Page'), ('Tom', 'Book Van for 12th')]
6 extracted, 5 after de-duplication:
Priya Send revised quote to customer by Friday due=3 November 2015
Tom Book warehouse van for move on track due=31 October 2015
Ana Raised late invoices. due=None
Ana Chase oldest two invoices this week. due=None
Kenji Update Returns Policy Page due=The mechanics worked: three chunks, six items, one duplicate (Tom's van) merged by the word-overlap rule. The content shows why this pattern needs care even on a hosted model:
- The root is an object (
ActionItemswith anitemslist), because OpenAI's strict mode requires an object at the root. - Duplicates across chunks are normal (Priya's quote appears twice in the notes, Tom's van twice). De-duplication by exact text fails on paraphrases; a word-overlap rule like
same_itemcatches the easy cases, and embeddings (Module 06) or a second, small "merge these lists" call handle the rest. - Context lost at chunk boundaries: "Priya to send the revised quote (same as above...)" only makes sense with the chunk before it. Overlap chunks a little, or pass a one-line summary of earlier chunks.
- Wrong and invented items: the tiny model recorded "Raised late invoices" (a topic, not an action) as an action item, and invented due dates such as "3 November 2015"; in other runs it missed items entirely.
due: str | Nonewith "exactly as said, or null" in the description gives a hosted model a way to say "no date"; a grounding check (theduetext appears in the chunk) catches the inventions. - Splitting by tokens, not by a separator, is what production code does; chunking strategy belongs to Module 05.
9.5 Normalization and "fill what you can"#
Two related patterns. Normalization: the model turns messy input into canonical forms (ISO dates, ISO currency codes, plain numbers), and validators accept the near-misses. Fill what you can: every field is nullable, and a partial result with honest nulls is better than a complete one with guesses:
# s9_5_normalize_and_nulls.py
"""Try it free: normalization (dates, currencies) and "fill what you can" with explicit nulls."""
from datetime import date
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError, field_validator
TODAY = date(2026, 11, 4)
class Payment(BaseModel):
payer: str | None = Field(description="Who paid, or null if not stated")
amount: float | None = Field(description="The amount as a plain number (no symbols or commas), or null")
currency: Literal["GBP", "EUR", "USD", "INR"] | None = Field(description="ISO 4217 code, or null")
paid_on: date | None = Field(description="ISO date (YYYY-MM-DD). Resolve 'yesterday' etc. from today's "
"date. Null if no date is given")
reference: str | None = Field(description="Invoice or payment reference, or null")
@field_validator("payer", "reference", mode="before")
@classmethod
def placeholder_is_null(cls, value: object) -> object: # models write "null", "n/a"... as text
if isinstance(value, str) and value.strip().lower() in {"", "null", "none", "n/a", "unknown", "/"}:
return None
return value
@field_validator("currency", mode="before")
@classmethod
def currency_code(cls, value: object) -> object:
symbols = {"£": "GBP", "€": "EUR", "$": "USD", "₹": "INR", "RS": "INR", "RUPEES": "INR"}
return symbols.get(value.strip().upper(), value.strip().upper()) if isinstance(value, str) else value
@field_validator("paid_on")
@classmethod
def not_in_future(cls, value: date | None) -> date | None:
if value and value > TODAY:
raise ValueError(f"{value} is after today ({TODAY}); payments can't be in the future")
return value
NOTES = ["Got £1,250.50 from Priya yesterday, ref INV-2041",
"Tom paid 300 EUR on 1 November",
"Payment received.",
"₹4,500 from Kenji on 28 Oct 2026"]
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
for note in NOTES:
try:
r = client.responses.parse(model="gpt-6-luna", input=note, text_format=Payment, max_output_tokens=150,
instructions=f"Extract the payment. Today is {TODAY.isoformat()}. "
"Use null for anything the note doesn't state.")
p = r.output_parsed
filled = sum(v is not None for v in p.model_dump().values()) if p else 0
print(f"{note[:38]:38} filled {filled}/5 {p.model_dump(mode='json') if p else None}")
except ValidationError as err:
print(f"{note[:38]:38} INVALID {err.errors()[0]['loc']}: {err.errors()[0]['msg']}")Got £1,250.50 from Priya yesterday, re filled 5/5 {'payer': 'Priya', 'amount': 1250.5, 'currency': 'GBP', 'paid_on': '2026-11-04', 'reference': 'INV-2041'}
Tom paid 300 EUR on 1 November filled 3/5 {'payer': '300EUR', 'amount': None, 'currency': 'EUR', 'paid_on': '2026-11-04', 'reference': None}
Payment received. filled 2/5 {'payer': 'today is 2026-11-04', 'amount': None, 'currency': None, 'paid_on': '2026-11-04', 'reference': None}
₹4,500 from Kenji on 28 Oct 2026 INVALID ('paid_on',): Value error, 2810-11-03 is after today (2026-11-04); payments can't be in the futureThe first row is the pattern working: £1,250.50 became 1250.5 and GBP, and the reference was found. (The date shows today's date rather than yesterday's; a hosted model resolves "yesterday" correctly when it's told today's date, and the instructions do that.) The other rows are the tiny model guessing, and they show where each safeguard sits:
- Placeholder text instead of null. Models often write
"null","none","n/a"or"unknown"as a string. Theplaceholder_is_nullvalidator turns those into realNones; without it, an earlier run of this script stored'null'as the payer's name. - Guessing to fill a field.
"Payment received."contains no payer, amount or date, and the model still wrote a payer ('today is 2026-11-04') and a date. In the Tom row it put'300EUR'inpayerand leftamountempty: the right value, in the wrong field. The honest answer is five nulls. A hosted model with these descriptions mostly gives it; a grounding check (the payer's name appears in the note) catches the rest. - Impossible values caught. The Kenji row was rejected because the model wrote a date in the year 2810:
not_in_futureturned that into a clear, retryable error rather than a payment recorded eight centuries ahead. - Relative dates need a reference. "Yesterday" only means something if the model knows today's date, so the instructions include it, and the validator checks the result is not in the future.
Count the filled fields, as the script does, and log the distribution: a field that is always filled on inputs that often lack it is a field the model is inventing.
9.2 Gemini enum mode#
For a classifier whose whole answer is one label, Gemini's generate_content has a lighter option than a JSON object: response_mime_type="text/x.enum" with an Enum as response_schema. The reply text is the bare value. On a mock server (layer 3: Gemini has no local stand-in), with a clean value, a casing slip and an invented value:
# s9_2_gemini_enum_mode.py
"""Gemini's enum mode (generate_content only): the wire, and what .parsed does, on a MOCK server.
response_mime_type="text/x.enum" plus an Enum class asks for ONE bare value instead of JSON.
The mock replies with documented-shape responses; the real SDK builds and parses them.
"""
import json
from enum import Enum
import httpx
from google import genai
from google.genai import types
class Category(str, Enum):
BILLING = "billing"
DELIVERY = "delivery"
TECHNICAL = "technical"
OTHER = "other"
replies = iter(["delivery", "Delivery", "shipping"]) # a clean value, a casing slip, an invention
sent: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
sent.append(json.loads(request.content))
return httpx.Response(200, json={"candidates": [{"content": {"role": "model", "parts": [{"text": next(replies)}]},
"finishReason": "STOP"}]})
client = genai.Client(api_key="test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))
config = types.GenerateContentConfig(response_mime_type="text/x.enum", response_schema=Category)
for _ in range(3):
r = client.models.generate_content(model="gemini-3.8-flash", contents="My parcel never arrived.", config=config)
print(f"text={r.text!r:12} parsed={r.parsed!r}")
print("generationConfig sent:", json.dumps(sent[0]["generationConfig"]))text='delivery' parsed=<Category.DELIVERY: 'delivery'>
text='Delivery' parsed=None
text='shipping' parsed=None
generationConfig sent: {"responseMimeType": "text/x.enum", "responseSchema": {"enum": ["billing", "delivery", "technical", "other"], "title": "Category", "type": "STRING"}}On the wire it's an ordinary STRING schema with an enum list. response.parsed maps the text to an Enum member when it matches exactly and is None otherwise, silently, as always on Gemini. On the hosted API, constrained decoding makes "shipping" impossible; normalizing case before you compare is still cheap insurance. Enum mode has no room for evidence or confidence, so prefer a JSON object when you need either.
Part 10: Libraries: instructor and Pydantic AI#
Deep-dive
The native SDK helpers (Part 3) cover one provider each. Two widely used libraries put one structured-output interface over many providers. Both are worth knowing; neither replaces understanding what they send. The broader comparison of wrapper libraries (LiteLLM, any-llm, aisuite, gateways) is lesson 03.11. If you build on LangChain, with_structured_output is the optional LangChain route to the same provider-native modes: you will meet it in 08F.6, Part 8, with the per-provider defaults in Part 9 and the retry ladder in Part 11.
10.1 instructor#
instructor (1.17.0, released 9 September 2026) wraps a provider client so that you pass response_model=YourModel and get a validated instance back, with automatic re-asking on validation errors. Its pieces:
instructor.from_provider("openai/...")builds a patched client for a provider string ("anthropic/...","google/...","ollama/..."and others);from_openai(...),from_anthropic(...)wrap a client you built.client.create(response_model=M, messages=[...], max_retries=N, context={...}):contextreaches your validators asinfo.context, exactly as in 6.3.- Re-asking: on a validation (or JSON) error, instructor appends the model's reply and a user message containing the error (its docs show the tools-mode wording, "Please correct the function call; errors encountered:" followed by the error), and calls again.
- Modes choose the mechanism. The core modes are
TOOLS,JSON_SCHEMA,MD_JSON,JSON,PARALLEL_TOOLSandRESPONSES_TOOLS. The older provider-prefixed modes (ANTHROPIC_TOOLS,GENAI_STRUCTURED_OUTPUTS,OPENROUTER_STRUCTURED_OUTPUTSand the rest) still work, but in 1.17.0 they warn: "Mode.{X} is deprecated and will be removed in v3.0. Use Mode.{core} instead. The provider is determined by the client". - Streaming:
create_partialyields progressively filled objects,create_iterableyields list items one by one, andcreate_with_completionreturns the raw completion alongside the object (for usage and IDs). - Hooks:
client.on("completion:kwargs" | "completion:response" | "completion:usage" | "completion:error" | "parse:error" | "completion:last_attempt", handler)for logging.
Try it free, in a throwaway environment: uv run --with instructor python s10_1_instructor.py builds an ephemeral overlay for that one command (uv's CLI reference, as of November 2026: with --with, "these dependencies will be layered on top of the project environment in a separate, ephemeral environment" and "are allowed to conflict with those specified by the project"), so your project's own openai is not touched (uv resolves instructor with openai 3.3.0 inside the overlay), with a grounding validator that requires the evidence to be a quote:
# s10_1_instructor.py
"""Try it free: instructor's response_model and automatic re-asking, on the local stand-in.
Run in its own environment: instructor 1.17.0 pins jiter<0.15, which conflicts with
openai>=3.3.1, so uv installs openai 3.3.0 for it (see 10.1):
uv run --with instructor python s10_1_instructor.py
"""
from typing import Literal
import instructor
from instructor.core import InstructorRetryException
from pydantic import BaseModel, Field, ValidationInfo, field_validator
class TicketLabel(BaseModel):
evidence: str = Field(description="The few words of the message that decide the category, quoted exactly")
category: Literal["billing", "delivery", "technical", "account", "other"]
@field_validator("evidence")
@classmethod
def quoted_exactly(cls, value: str, info: ValidationInfo) -> str:
message = (info.context or {}).get("message", "")
if value.lower() not in message.lower():
raise ValueError(f"'{value}' is not in the message; quote the message's own words")
return value
client = instructor.from_provider("ollama/gpt-6-luna") # Ollama at localhost:11434, an alias model
print("mode chosen:", client.mode)
prompt_tokens: list[int] = [] # one entry per API call
client.on("completion:response", lambda response: prompt_tokens.append(response.usage.prompt_tokens))
client.on("parse:error", lambda error: print(" re-asking after:", str(error).splitlines()[2].strip()[:80]))
for message in ["I was charged twice for my subscription this month!",
"The courier left my package in the rain."]:
prompt_tokens.clear()
try:
label = client.create(response_model=TicketLabel, max_retries=3, max_tokens=150,
context={"message": message}, # reaches validators as info.context
messages=[{"role": "system", "content": "Classify the customer message."},
{"role": "user", "content": message}])
print(f"{message[:42]:42} -> {label.category:9} evidence={label.evidence!r} prompt tokens per call: {prompt_tokens}")
except InstructorRetryException as err:
print(f"{message[:42]:42} -> gave up after {err.n_attempts} attempts; prompt tokens per call: {prompt_tokens}")Output (local model qwen2.5:0.5b via Ollama; the first lines are instructor's own log message, on stderr):
Max retries exceeded. Total attempts: 4, Last error: 1 validation error for TicketLabel
evidence
Input should be a valid string [type=string_type, input_value={'evidence': 'charged twi...bscription this month!'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.14/v/string_type
mode chosen: Mode.JSON
re-asking after: Input should be a valid string [type=string_type, input_value={'evidence': 'char
re-asking after: Input should be a valid string [type=string_type, input_value={'evidence': 'char
re-asking after: Input should be a valid string [type=string_type, input_value={'evidence': 'char
re-asking after: Input should be a valid string [type=string_type, input_value={'evidence': 'char
I was charged twice for my subscription th -> gave up after 4 attempts; prompt tokens per call: [203, 320, 437, 554]
The courier left my package in the rain. -> delivery evidence='the courier' prompt tokens per call: [202]Look at the token counts. The first message failed four times (three re-asks, so max_retries=3 meant four calls), and each re-ask re-sent the whole conversation plus the error, so the prompt grew from 203 to 554 tokens: the cost of a failing document rises with every retry. The second message passed first time. Notice also mode chosen: Mode.JSON: for an unrecognized model name on Ollama, from_provider picked JSON mode, not schema-constrained output. Know which mode you're getting; set mode= explicitly in production.
10.2 Pydantic AI output modes#
Pydantic AI (2.65.0, 3 November 2026, the version this lesson's samples use; PyPI showed 2.67.0 from 11 November 2026; version 2 since June 2026) is an agent framework, and its output_type gives structured output with three interchangeable mechanisms:
| Mode | Mechanism | Pydantic AI's description |
|---|---|---|
ToolOutput(M) |
A final_result tool whose arguments are your schema (rung 4). The default |
"supported by virtually all models" |
NativeOutput(M) |
The provider's structured-output feature (rung 3) | "not supported by all models" |
PromptedOutput(M) |
Schema in the prompt, plus JSON mode where available (rungs 1 and 2) | "usable with all models, but is often the least reliable approach" |
Validation failures are retried within an output-retry budget (in v2, Agent(retries={"output": N}); the old output_retries= argument was replaced, and the default budget is 1), and @agent.output_validator functions can raise ModelRetry to ask again with a message. On the stand-in, with an event hook recording what each mode sends:
# s10_2_pydantic_ai.py
"""Try it free: Pydantic AI's three structured-output modes, and what each puts on the wire.
The agent talks to Ollama through the openai SDK; an httpx2 event hook records each request
body so we can see which mechanism the mode used (a tool, response_format, or a prompt).
"""
import json
import os
from typing import Literal
os.environ.setdefault("PYDANTIC_AI_NO_BANNER", "1") # skip the start-up banner
import httpx2
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
from pydantic_ai import Agent, NativeOutput, PromptedOutput, ToolOutput
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider
class TicketLabel(BaseModel):
evidence: str = Field(description="The few words of the message that decide the category")
category: Literal["billing", "delivery", "technical", "account", "other"]
bodies: list[dict] = []
async def record(request: httpx2.Request) -> None:
bodies.append(json.loads(request.content))
client = AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama",
http_client=httpx2.AsyncClient(event_hooks={"request": [record]}))
model = OpenAIChatModel("gpt-6-luna", provider=OpenAIProvider(openai_client=client))
MESSAGE = "The courier left my package in the rain."
for label, output_type in [("ToolOutput (default)", ToolOutput(TicketLabel)),
("NativeOutput", NativeOutput(TicketLabel)),
("PromptedOutput", PromptedOutput(TicketLabel))]:
agent = Agent(model, output_type=output_type, instructions="Classify the customer message.",
retries={"output": 2})
bodies.clear()
try:
result = agent.run_sync(MESSAGE)
outcome = repr(result.output)
except Exception as err: # e.g. UnexpectedModelBehavior after the retries
outcome = f"{type(err).__name__}: {str(err)[:70]}"
first = bodies[0]
mechanism = {"tools": [t["function"]["name"] for t in first.get("tools", [])],
"tool_choice": first.get("tool_choice"),
"response_format": (first.get("response_format") or {}).get("type")}
print(f"{label:21} requests={len(bodies)} {mechanism}\n{'':21} -> {outcome}")ToolOutput (default) requests=3 {'tools': ['final_result'], 'tool_choice': 'required', 'response_format': None}
-> UnexpectedModelBehavior: Exceeded maximum output retries (2)
NativeOutput requests=1 {'tools': [], 'tool_choice': None, 'response_format': 'json_schema'}
-> TicketLabel(evidence='the rain', category='other')
PromptedOutput requests=1 {'tools': [], 'tool_choice': None, 'response_format': 'json_object'}
-> TicketLabel(evidence='left a package in 100 rain.', category='delivery')The wire tells you what each mode is. ToolOutput sent a final_result tool with tool_choice: "required", which Ollama ignores, so the tiny model answered in text three times and the run failed after the retries: on a hosted model the forced tool call would have worked (though remember that forced tool choice is a 400 on Claude Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1, 1.5; Pydantic AI's docs note that on Anthropic, a request that thinks uses native output even without the marker class). NativeOutput sent response_format: json_schema and PromptedOutput sent json_object. Both returned a schema-valid label, and the native one was wrong ("other" for a delivery complaint), as a 0.5B model's answer can be.
10.3 What they add, and what they cost#
| Native SDK helpers | instructor | Pydantic AI | |
|---|---|---|---|
| Providers | One each | Many, one interface | Many, one interface |
| Retry with errors | You write it (Part 7) | Built in (max_retries) |
Built in (output retry budget) |
| Mechanism control | Exact | mode= |
ToolOutput / NativeOutput / PromptedOutput |
| Streaming partial objects | Per SDK (Part 8) | create_partial, create_iterable |
run_stream + stream_output() |
| Outcome handling (refusal vs truncation vs invalid) | Visible, if you use create() |
Folded into exceptions | Folded into exceptions |
| Dependencies | None beyond the SDK | instructor's pins (see 10A.1) | A framework (pydantic-ai-slim[openai] for one provider) |
| Best for | Production code where you own the details | Structured output across providers, quickly | Agents with typed outputs and tools |
What you give up with either library is mostly visibility: the provider's raw finish reason, the exact schema sent (check it with a wire capture, as above), and control over how a truncated or refused reply is treated. Use them where their convenience matters, and keep a test that captures what they put on the wire, so an upgrade can't silently switch your mechanism.
Part 11: Cost and latency#
Deep-dive
11.1 Schemas are input tokens#
The schema travels with every request, and the model reads it as input (02.2, 4.4 shows the same for tool definitions). A rough count with OpenAI's tokenizer, no network:
# s11_1_schema_tokens.py
"""Schemas are input tokens, on every request. A rough count with tiktoken (no network).
o200k_base is OpenAI's tokenizer for current models; other providers tokenize differently
and add their own hidden instructions, so treat these as relative sizes, not bills.
"""
import json
from typing import Literal
import tiktoken
from anthropic import transform_schema
from openai.lib._pydantic import to_strict_json_schema # private: the transform .parse() uses
from pydantic import BaseModel, Field, create_model
from invoice_model import Invoice
from order_model import Order
enc = tiktoken.get_encoding("o200k_base")
def tokens(schema: dict) -> int:
return len(enc.encode(json.dumps(schema, separators=(",", ":"))))
# A product classifier with a 300-value enum, and the same task with a short enum
PRODUCTS = tuple(f"product_category_{i:03d}" for i in range(300))
BigEnum = create_model("BigEnum", category=(Literal[PRODUCTS], Field(description="The product category")))
SmallEnum = create_model("SmallEnum", category=(Literal["electronics", "home", "garden", "toys", "other"], ...))
class Wordy(BaseModel):
"""An order. Please read the email carefully and extract every field below with great care."""
customer: str = Field(description="The full name of the customer who wrote the email, exactly as they "
"signed it, including any middle names, titles or suffixes they used.")
order_date: str = Field(description="The date on which the customer sent the email, which you should "
"write in ISO 8601 format, that is year, month and day (YYYY-MM-DD).")
for name, model in [("Order", Order), ("Invoice", Invoice), ("Wordy (2 fields)", Wordy),
("SmallEnum (5 values)", SmallEnum), ("BigEnum (300 values)", BigEnum)]:
raw = model.model_json_schema()
print(f"{name:22} pydantic={tokens(raw):5} openai strict={tokens(to_strict_json_schema(model)):5} "
f"anthropic={tokens(transform_schema(model)):5}")
per_request = tokens(to_strict_json_schema(BigEnum)) - tokens(to_strict_json_schema(SmallEnum))
print(f"\nBigEnum costs ~{per_request:,} extra input tokens per request; "
f"at 1M requests that is ~{per_request * 1_000_000 / 1e9:.1f}B tokens")Order pydantic= 295 openai strict= 303 anthropic= 319
Invoice pydantic= 309 openai strict= 319 anthropic= 336
Wordy (2 fields) pydantic= 130 openai strict= 135 anthropic= 135
SmallEnum (5 values) pydantic= 42 openai strict= 47 anthropic= 47
BigEnum (300 values) pydantic= 1537 openai strict= 1542 anthropic= 1542
BigEnum costs ~1,495 extra input tokens per request; at 1M requests that is ~1.5B tokens- A realistic schema is a few hundred tokens, often more than the instructions, and it's re-sent on every call, including every retry.
- Wordy descriptions cost real tokens: two fields with long descriptions cost 130 tokens. Say what's needed, once.
- Giant enums are the expensive case: 300 values cost about 1,500 tokens on every request, before you count the hidden instructions providers add (Anthropic, for example, injects a system prompt for structured output, which is billed as input).
- These counts are approximate, and only for OpenAI's tokenizer. For real numbers, use the providers' token-counting endpoints, which lesson 03.7 covers along with pricing.
11.2 First-request compile latency#
A schema has to be compiled into a grammar before decoding can be constrained, and the first request with a new schema pays for it:
- OpenAI: the Responses version of the guide says "the first request you make with any schema will have additional latency as our API processes the schema, but subsequent requests with the same schema will not have additional latency." The Chat Completions version of the same page currently limits this to fine-tuned models ("Other models do not have this limitation"). The two pages disagree as of November 2026; plan for a slower first request with each new schema and measure it on your models. For fine-tuned models, schemas "are cached for performance, and are not eligible for zero data retention".
- Anthropic: "additional latency while the grammar compiles", then "Compiled grammars are cached for 24 hours from last use". Changing the schema's structure or the set of tools invalidates the cached grammar; editing only
nameordescriptionfields doesn't. The compile can take up to the 180-second timeout for a schema near the limits. - Gemini and OpenRouter document no compile latency; OpenRouter inherits whatever the routed provider does.
What this means for you: keep schemas stable (a schema built per request, such as an enum of retrieved candidates, may recompile on every call), warm a new schema with one request after deployment, and set timeouts that allow for a slow first call (lesson 03.8).
11.3 Prompt-caching interactions#
Prompt caching (02.7, Part 7; every API in depth in lesson 03.7) reuses an identical request prefix. The schema is part of what the model sees, so:
- Anthropic: "Changing the
output_config.formatparameter will invalidate any prompt cache for that conversation thread." Switching schemas between turns of one conversation, or building a schema per request, throws away cached prefixes. Keep one schema per conversation where you can. - All providers: a stable schema is part of a stable prefix. Retries in the same conversation share the document and schema prefix, which caching makes cheaper.
11.4 Output tokens: what your fields cost#
Output tokens are the expensive ones (02.2, Part 10), and every key name is generated as output too. A reasoning field can double a short answer (5.2), long key names repeat for every item in a 50-row list, and a retry pays all of it again. Measure tokens per successful extraction, retries included (the extractor's attempt log has the numbers), not tokens per call.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "JSON mode guarantees my schema." | It guarantees parseable JSON (where enforced) and nothing about keys, types or values (1.3). Schemas need rung 3 or 4. |
| "Structured output means the data is correct." | It guarantees the format, within the provider's subset. Values can be wrong, invented or inconsistent (6.2). |
| "If the SDK accepted my Pydantic model, the provider enforces all of it." | The SDKs transform your schema; Anthropic moves numeric bounds and lengths into descriptions, and Gemini silently ignores maxLength (2.9, 4.4). Only your validation enforces the rest. |
"Optional[str] = None is the way to make a field optional." |
For strict modes, use str | None with no default: nullable but required (2.4). |
"response.parsed being None means the model returned nothing." |
On Gemini it means any failure, silently; on OpenAI Chat it can mean a refusal (3.9). Check the finish reason. |
| "The parse helpers handle truncation for me." | responses.parse and messages.parse raise a plain ValidationError on truncated JSON and hide the finish reason (3.9). |
| "Force a tool call to get structured output on any Claude model." | Forced tool_choice returns 400 on Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1. Use output_config.format, or auto with strict (1.5). |
| "OpenRouter supports structured outputs for this model, so every request is enforced." | Support is per endpoint; without require_parameters an endpoint may ignore your schema (3.6). |
| "If validation fails, retry until it passes." | Retries fix slips, not wrong schemas or missing information, and a model can "pass" by changing the facts (7.4). Bound them and send the rest to a person. |
| "A confidence field tells me how likely the answer is right." | Self-reported confidence is poorly calibrated; both mistakes in 9.1 were "high". Calibrate on labelled data. |
| "A schema-valid string is a safe string." | The schema fixes the shape, not the content: a str field can carry markup, SQL or instructions copied from the text you gave the model. Treat extracted values as untrusted user input (6.3). |
"Gemini's Pydantic path, response_schema=Model, is the way to do it." |
Google's reference now steers to response_json_schema; response_schema=Model is a convenience with silent drops and client-side rejections (3.4). |
| "It works on the local model, so the hosted API will accept it." | The stand-in ignores many settings (Anthropic output_config on Ollama, strict tools) and has its own grammar limits (3.7). |
| "A schema costs nothing; only the prompt counts." | The schema is input tokens on every request, and a big enum can cost more than the prompt (11.1). |
Key takeaways#
- Four rungs: prompt plus parse, JSON mode, schema-constrained structured output, strict tools. Use rung 3 for "give me this data", rung 4 when the model must choose a shape, and validate on every rung.
- Pydantic is the schema language: descriptions are prompt text,
Literal/Enumclose a value set,X | Nonewith no default means nullable-but-required, lists are bounded, unions are plain and tagged, and model-filled fields have no defaults. - The SDKs transform your schema before sending it. OpenAI makes every field required and adds
additionalProperties: false; Anthropic moves unsupported constraints into descriptions; google-genai converts to its ownSchematype and rejects or silently drops some constructs. Check what goes over the wire. - Each provider supports a different subset. OpenAI: everything required, no
allOf/not/if, size limits. Anthropic: no recursion, no numeric or length constraints, complexity limits (20 strict tools, 24 optional, 16 union-typed parameters). Gemini: some keywords silently unenforced, "too many states" for complex schemas. OpenRouter: whatever the endpoint supports. - Check the outcome before you parse. Refused, blocked and truncated replies are distinct outcomes, reported differently by every provider; the parse helpers raise or return
Nonein ways that hide which one happened. - Validate in layers: parse, schema, semantic validators (cross-field rules, ranges, grounding in the source), then business rules, which route rather than retry.
- Validate-and-retry with the exact errors, bounded per model, then escalate, then a person. When the same error repeats, fix the schema or accept that the information is missing.
- Stream structured output only for people, render drafts, and act only on the validated final object.
- Extracted values are untrusted input. Parameterize, escape on render, allow-list URLs, and let only enums and validators drive behaviour; redact
raw_textin logs. - On Gemini, prefer
response_json_schemaplusmodel_validate_json;response_schema=Modelis the convenience with.parsed, and both silently ignoremaxLength. - Libraries (instructor, Pydantic AI) give one interface and built-in retries, at the cost of visibility and dependency pins.
- Schemas cost input tokens on every request, new schemas cost compile latency, and on Anthropic changing the format invalidates the prompt cache.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Structured output | Model output with a known, machine-checkable shape (usually JSON matching a schema) |
| JSON Schema | The standard JSON-based language for describing the shape of JSON data |
| JSON mode | An API setting that makes the model produce valid JSON, without a schema |
| Structured Outputs (schema-constrained output) | Decoding constrained to a supplied JSON Schema, so the reply matches it |
Strict mode (strict: true) |
The setting that turns schema enforcement on for a response format or tool definition |
| Strict tool | A tool definition whose arguments are constrained to its schema |
| Parse helper | An SDK method (responses.parse, chat.completions.parse, messages.parse) that sends a schema from a Pydantic model and returns a parsed object |
| Schema transform | The rewriting an SDK applies to your schema before sending it (required fields, additionalProperties: false, moved constraints) |
| Supported subset | The JSON Schema keywords and structures a provider's grammar engine accepts |
| Nullable but required | A field that must always be present but may be null: how strict modes express "optional" |
| Discriminated union | A union whose variants are told apart by a tag field (kind: "card") |
propertyOrdering |
Gemini's schema field that fixes the order of keys in the output |
| Enum mode | Gemini's text/x.enum response type, which returns one bare enum value |
| Response healing | OpenRouter's plugin that repairs malformed JSON syntax in non-streaming responses |
require_parameters |
OpenRouter's routing option that only uses endpoints supporting every parameter sent |
| Semantic validation | Checks on meaning that a schema can't express: cross-field rules, ranges, consistency |
| Grounding check | A validator that requires an extracted value to appear in the source text |
| Outcome check | Classifying a reply as ok, refused, blocked, truncated, invalid or error before parsing it |
| Validate-and-retry | Re-asking the model with the validation errors, a bounded number of times |
| Model escalation | Moving to a stronger model after a cheaper one keeps failing |
| Partial object | A best-effort object built from the incomplete JSON prefix of a streamed structured answer; only its settled fields are safe to use (the parsing technique itself is 03.3, 6.3) |
| Settled field | In a streamed object, a field followed by a later key, and therefore finished |
| Schema linter | A pre-flight check of a schema against a provider's documented rules |
$ref / $defs |
JSON Schema's named definitions: define a shape once under $defs, reuse it by reference |
anyOf |
JSON Schema's "one of these shapes", used for unions and for nullable fields |
additionalProperties: false |
JSON Schema's "no extra keys" for an object, required by strict modes |
| Re-asking | instructor's name for retrying with the validation error appended to the conversation |
| Output mode (Pydantic AI) | The mechanism a framework uses for structured output: tool, native or prompted |
All terms are also collected in the glossary.
Exercises#
- Extraction (1.2): add a reply to
REPLIESins1_2_extract_json.pythat defeatsparse_reply, such as the person wrapped in an envelope ({"result": {"name": "Priya", "age": 29}}). Change the function to support it without breaking the existing cases. Then try a JSON array of two people and decide whatparse_replyshould return for it. - Transforms (2.8): add
class Tags(BaseModel): tags: set[str]andclass Money(BaseModel): amount: Decimalto the construct matrix. Predict what each SDK will do before you run it, then explain any surprise. - Wire (2.9): change
discount_codeto have no default. Which of the four schemas change, and how? - Linter (4.6): Anthropic's limit of 16 union-typed parameters is per request, and
lint_anthropiccounts union nodes in one schema. Writelint_anthropic_request(schemas: list[dict])that counts union-typed parameters (properties whose value isanyOfor a type array, not every nested union node) across several schemas combined, such as two strict tools plus an output schema, and a test with three schemas of six nullable fields each that passes one at a time and fails together. - Streaming outcomes (6.5, 8.3):
outcomes.pyclassifies complete responses. Writeextraction_from_openai_streamforresponses.stream(...): after the loop, build the sameExtractionfrom the final response (see the hint:get_final_response()is not safe for every ending), and handleresponse.refusal.deltaevents seen along the way. Test it with the SSE fixtures from lesson 03.3, including one that ends inresponse.incomplete. - Validators (6.3): add a rule to
Invoicethat everyInvoiceLine.descriptionappears in the document (grounding at the row level), and runs6_3_validation_layers.pywith and without a document incontext. - Retry (7.3): add a total-attempts cap and a per-document token budget to
extract(). What should the status be when the budget runs out? - Schema fix (7.4): run
s7_3_extractor.pywithInvoiceWithTaxinstead ofInvoiceand compare the attempt logs for INV-2042. - Streaming (8.3): change
settled()so the last key is shown when its value is a complete number,true,falseornull, and explain why that is safe while a half-written string isn't. - Classification (9.1): add five tricky messages (two categories in one message, sarcasm, a non-English message) to
LABELLED. What does the accuracy check tell you, and what can't it tell you? - OpenRouter (3.6): pick another open-weight model from the live catalogue and list which of its endpoints support
structured_outputs. Then write theextra_bodythat would keep a request off the others. - Cost (11.1): replace the 300-value enum with a two-step classification (department, then category) and count the tokens of both schemas.
- Untrusted values (6.3): add a validator to a
website: str | Nonefield that accepts onlyhttpsURLs whose host is on an allow-list, and one to anotes: strfield that rejects<and>. Which extracted fields in your own projects drive an action, a query or a render?
Hints and what you should see
- The wrapped reply fails with
no valid Person in reply (1 JSON object(s) failed validation):iter_json_objectsyields only the outer dict, which has nonameorage, and then skips past its end, so the inner object is never tried. One fix is to walk each decoded value, yielding the dict and then every dict nested inside it (including dicts inside lists):def walk(v): if isinstance(v, dict): yield v; for x in v.values(): yield from walk(x), with alistbranch that walks each item, andyield from walk(value)in place ofyield value. Then re-run all the old replies to make sure nothing regressed (they should print exactly as before). A JSON array of two people does not defeat the original: the scan starts at the first{, which is inside the array, so each person is yielded in turn andparse_replyreturns the first one that validates, silently ignoring the second. Decide whether that is what you want, or whether alist[Person]variant should return all valid objects, and document it. A reply such as[1, 2]contains no objects and must still fail cleanly. - Verified with the SDK versions named in Setup (offline):
set[str]gives{"type": "array", "items": {"type": "string"}, "uniqueItems": true}. OpenAI's transform passesuniqueItemsthrough (the linter flags it as undocumented), Anthropic's moves it into the description as{uniqueItems: True}, and google-genai'sresponse_schema=Modelconversion raises aValidationErrorfor it (an extra input itsSchemadoes not allow).Decimalgives{"anyOf": [{"type": "number"}, {"type": "string"}]}, unchanged by the OpenAI and Anthropic transforms, and google-genai converts it toany_ofwithNUMBERandSTRING. So both constructs are "valid but loosely enforced": uselist[str]plus a validator, and afloator an integer count of minor units on the wire, withDecimalin your own code. - In Pydantic's own schema,
discount_codemoves intorequiredand loses"default": null. The OpenAI schema does not change at all (it already listed it as required and dropped theNonedefault). Anthropic's changes in two ways:discount_codebecomes required, and the"description": "{default: None}"text disappears. Gemini'sresponse_schemaoutput now listsdiscount_codeinrequiredand keepsnullable: true. - Count one union per property whose value is
anyOfor a type array. In the test, give each of three schemas sixstr | Nonefields: each alone has 6 (limit 16), together 18, solint_anthropic_requestmust report it and the single-schema linter must not. - For
response.completed,response.incompleteandresponse.failed, the event carries a fullResponseinevent.response, so after the loop you can pass the terminal event's response straight toextraction_from_openai_response. Do not rely onget_final_response(): it raisesRuntimeErrorunless the stream ended withresponse.completed(03.3, 4.2). If the stream ended with no terminal event at all, returnExtraction("error", detail="stream ended without a terminal event"). The refusal deltas are only needed for a UI: the terminal response already contains the refusal content item. - A description-grounding rule fits as a
field_validator("description")onInvoiceLine(nested models receive the samecontext) or as a loop inInvoice.check_consistency. Without a document incontextthe check must be skipped, as forinvoice_number, so the output is unchanged; with a document that lacks "Tyres" (say, one that says "Winter tyre"), the "good" reply fails at layer 3 with a message naming the line. Phrase the message as an instruction (copy the description exactly as printed), since it goes back to the model on a retry. - Count tokens and attempts across the whole
extract()call, including the doubled budgets of truncation retries, and stop before the next call if the total would exceed the cap. A dedicated status such as"budget_exceeded"(added toStatus) is better than"invalid_after_retries"or"error", because nothing is wrong with the document or the provider;needs_reviewalready covers every non-okstatus. - Locally the results vary (a 0.5B model), so compare the shape of the logs: with the honest rule, a successful run needs one attempt and no invented line item, while the old
Invoicefails the same consistency error on every attempt (see 7.3 and 7.4). A hosted model should succeed first time on both. - A
true,falseornullliteral can't change once it is fully spelled, so it is safe to show as soon asfrom_jsonreturns it. A number is only complete when the character after it (,or}) has arrived: a buffer ending in2could still become20or2.5. So test the raw buffer, not just the parsed value, before showing a number. A half-written string can still grow or change its meaning, which is whyallow_partial=Truedrops it. - A smoke test tells you whether the prompt, schema and parsing work at all and which categories get confused. It cannot tell you how accurate the system is on your real traffic (ten messages), how well calibrated the confidence labels are, or how it behaves on inputs you didn't think of: that needs a larger, representative labelled set (Module 10A).
- Use the same two requests as
s3_6_openrouter_endpoints.pywith your model ID.extra_body={"provider": {"require_parameters": True}}already keeps the request off endpoints that lackstructured_outputs. For an explicit allow-list, OpenRouter's provider-routing object takesonly(a list of provider slugs to allow),order(slugs to try in sequence) andallow_fallbacks(a boolean, defaulttrue), as listed on its provider selection page in November 2026; for exampleextra_body={"provider": {"only": ["<slug>"], "require_parameters": True}}, with<slug>read from the model's endpoint list rather than guessed. - Reuse
tokens()froms11_1_schema_tokens.py. Add the token counts of the two small schemas (a department enum, then one category enum per department) and compare with the single big enum: a request carries only one of the second-step enums, so the per-request cost is the first schema plus one second schema. Note what you pay for it: two calls, so about double the latency, and a second chance to be wrong. - For example:
urlparse(value).scheme == "https"andurlparse(value).hostname in ALLOWED_HOSTS(an exact-match set, notendswith, which a host likeevil-example.comdefeats), andif "<" in value or ">" in value: raise ValueError(...). The point of the second part is that you list your own fields: anything that is fetched, stored in a query, rendered as HTML, or decides a branch needs a validator or an enum.
Check yourself#
- What does JSON mode guarantee, and what doesn't it?That the reply is syntactically valid JSON (where the provider enforces it). Not which keys appear, their types, or their values: the local run in 1.3 produced valid JSON with extra keys every time.
- Why does OpenAI require the word "JSON" in the context when you use JSON mode?Without an instruction to produce JSON, "the model may generate an unending stream of whitespace and the request may run continually until it reaches the token limit". OpenAI documents the unending-whitespace failure and says the API returns an error when "JSON" is missing; the lesson infers that the check exists to stop that failure, but OpenAI doesn't state its motive.
- When is a strict tool a better structured-output channel than a response format?When the model must choose between several actions or output shapes (one tool per shape), or when you're already in a tool-calling flow. For a single "give me this data" shape, use the response format.
- How do you make a field "optional" in OpenAI's strict mode, and how do you write it in Pydantic?List it in
requiredand allownull:{"anyOf": [{"type": "string"}, {"type": "null"}]}. In Pydantic,field: str | None = Field(description=...)with no default. - What does Anthropic's SDK do with
Field(ge=1, le=999)before sending the schema, and who enforces the bounds?It removesminimumandmaximumfrom the schema and appends{maximum: 999, minimum: 1}to the field's description. The grammar doesn't enforce them; the SDK validates the reply against your original Pydantic model, which does. - Your Gemini extraction returns
response.parsed is Noneand no exception. What are the possible causes, and what do you check first?Truncation (MAX_TOKENS), a safety stop or blocked prompt (finish_reasonorprompt_feedback.block_reason), JSON that doesn't validate against the model, or (withresponse_json_schema) you got a dict rather than a model. Checkprompt_feedbackandcandidates[0].finish_reasonfirst, then validateresponse.textyourself to see the error. - Why can't you use
responses.parseto tell a truncated reply from an invalid one, and what do you use instead?It parses while building the result, so truncated JSON raisesValidationErrorfrom the call and you never seestatusorincomplete_details. Useresponses.create(text={"format": ...}), checkstatusfirst, then validateoutput_text. - A colleague's code forces
tool_choice={"type": "tool", "name": "extract"}onclaude-sonnet-5-5and gets a 400. Why, and what are the two fixes?Forcedtool_choice(anyortool) returns a 400 on Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1. Useoutput_config.formatfor a fixed JSON shape, ortool_choice={"type": "auto"}withstrict: trueon the tool (and check that the model called it). - Which provider supports recursive schemas, and which rejects them? What does google-genai's
response_schema=Modeldo with a recursive Pydantic model?OpenAI supports recursion ($ref: "#"or explicit$refs); Anthropic doesn't support recursive schemas. google-genai's Pydantic conversion silently drops the recursion, turningchildreninto an array of anything (items: {}). - What is the difference between OpenRouter's default routing and
provider.require_parameters: truefor a structured-output request?By default, OpenRouter prefers endpoints that support your response format, but may route to one that ignores it if none of the model's providers support it. Withrequire_parameters: true, only endpoints that support every parameter you sent can serve the request. - Name the four validation layers and say which failures should be retried.Parse, schema, semantic validators, business rules. Parse, schema and semantic failures are retried with the errors (within a bound); business-rule failures are routed to a person or policy, not retried.
- Why must an outcome check run before parsing, rather than treating every failure as "invalid output"?Because refusals, blocks and truncation need different handling: a truncated reply needs a bigger budget, not "please fix your JSON"; a refusal shouldn't be retried at all. Parsing first turns all three into the same
ValidationError. - Your extractor fails with the same validation error on every attempt, on every model. What are the two likely causes?The schema or rule doesn't match reality (like requiring lines to sum to a total that includes tax), or the information isn't in the input and the schema has no way to say so. Fix the schema; don't add retries.
- Why should a
reasoningfield come before the answer field, what does it cost, and what's the extra risk on Claude?Fields are generated in order, so a reasoning field before the answer lets the model work it out first, rather than justify an answer already given. It costs output tokens and latency. On Claude, step-by-step reasoning in a schema property "might lead to areasoning_extractionrefusal", so prefer adaptive thinking plus a short evidence field. - What is safe to show to a user while a structured response streams, and what must wait for the end?Draft values, clearly marked as drafts, preferably only "settled" fields (those followed by a later key), and never half-written identifiers or numbers. Any action, and anything that depends on validation, waits for the final, validated object.
- A model extracts a
websitefield from a customer's email and your code fetches it. What can go wrong even though the reply passed schema validation, and what do you do about it?The URL may point at an internal address, a malicious site or a link the email's author planted to make your server fetch something (the model copies text it was given). Schema validation only proves it is a string. Treat it as untrusted input: allow-list schemes and hosts, block private address ranges, escape it when rendered, and never let extracted text decide an action on its own (6.3, and Module 12).
Further resources#
- OpenAI, Structured Outputs guide: the strict-mode rules, supported schemas and limits, refusals, and JSON mode.
- OpenAI, Function calling guide: strict mode for tools, and the Responses normalization behaviour.
- Anthropic, Structured outputs and Strict tool use: the schema subset, complexity limits, SDK transformation and feature compatibility.
- Anthropic, Refusals and fallback:
stop_reason: "refusal"andstop_details. - Google, Structured output and the generateContent API reference: supported keywords, the not-enforced list, "too many states",
propertyOrderingand enum mode. - OpenRouter, Structured outputs, Provider selection and Response healing.
- JSON Schema (Understanding JSON Schema): the full language the providers subset.
- Pydantic, JSON Schema and Validators: how models become schemas, and every validator mode used here.
- instructor (GitHub) and Pydantic AI: Output.
- SDK sources: openai-python (
src/openai/lib/_pydantic.py,lib/_parsing/), anthropic-sdk-python (lib/_parse/_transform.py) and python-genai: read them when a helper surprises you.
← 03.3 — Streaming Responses | Module 03 overview | 03.5 — Tool Calling: The API Mechanics →