Structured outputs
When code consumes model output, constrain it to a schema and validate it.
Evolving: the basics hold, details shift. Reviewed 17 Oct 2026.
Key ideas
- Prefer native structured-output or JSON-schema modes; they constrain decoding so output always parses.
- Define schemas with Pydantic (Python) or Zod (TypeScript) and generate the JSON schema from them.
- Tool calling is a structured-output mechanism: a tool's input schema is the output contract.
- Validate anyway, and on failure retry once with the validation error in the prompt.
- Keep schemas shallow; add descriptions to fields because the model reads them.
In code
from pydantic import BaseModel, Field
from pydantic_ai import Agent
class Invoice(BaseModel):
vendor: str
total: float = Field(description='Grand total incl. tax')
currency: str = Field(pattern='^[A-Z]{3}$')
agent = Agent('anthropic:claude-sonnet-5-5', output_type=Invoice)
result = agent.run_sync(invoice_text)
print(result.output.total)Common mistakes
- Forcing JSON on reasoning-heavy tasks can lower quality; let the model think first, then emit the structure.