ExamplescriptintermediateRunnableguided-flow
Output
Runnable example (intermediate) for script using pydantic.
Key Facts
- Level
- intermediate
- Runtime
- Python • Pydantic
- Pattern
- Inspectable flow with visible system boundaries
- Interaction
- Live sandbox • Script
- Updated
- 14 March 2026
Navigate this example
Library
Browse examplesReopen the wider library to compare adjacent patterns and linked learning paths.Interaction
Run sandbox nowTry the interaction directly in this example’s guided sandbox surface.Source
Open full sourceRead the real implementation, highlighted checkpoints, and runtime requirements.MCP
Call via MCPUse the same resource inside agents, deterministic exports, and MCP setup flows.
Linked principles
4-output.py
python
import nest_asyncio
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext, ModelResponse
nest_asyncio.apply()
# --------------------------------------------------------------
# Basic output
# --------------------------------------------------------------
class CityLocation(BaseModel):
city: str
country: str
agent = Agent("openai:gpt-4o-mini", output_type=CityLocation)
result = agent.run_sync("Where were the olympics held in 2012?")
print(result.output)
print(result.usage())
# --------------------------------------------------------------
# Returning either text or structured data
# --------------------------------------------------------------
class Box(BaseModel):
width: int
height: int
depth: int
units: str
agent = Agent(
"openai:gpt-4o-mini",
output_type=[Box, str],
instructions=(
"Extract me the dimensions of a box, "
"if you can't extract all data, ask the user to try again."
),
)
result = agent.run_sync("The box is 10x20x30")
print(result.output)
result = agent.run_sync("The box is 10x20x30 cm")
print(result.output)
# --------------------------------------------------------------
# Union of output types
# --------------------------------------------------------------
agent = Agent(
"openai:gpt-4o-mini",
output_type=list[str] | list[int],
instructions="Extract either colors or sizes from the shapes provided.",
)
result = agent.run_sync("red square, blue circle, green triangle")
print(result.output)
result = agent.run_sync("square size 10, circle size 20, triangle size 30")
print(result.output)
# --------------------------------------------------------------
# Output functions - function as output_type
# --------------------------------------------------------------
def uppercase(ctx: RunContext[None], message: ModelResponse) -> str:
"""Uppercase the model's text response."""
return message.text.upper()
agent = Agent(
"openai:gpt-4o-mini",
output_type=uppercase,
)
result = agent.run_sync("Tell me a quick joke")
print(result.output)
Related principles
- P4trustApply progressive disclosure to system agencyProvide the minimum information necessary by default, while enabling users to inspect additional detail when confidence, understanding, or intervention is required.Open principle →
- P7trustEstablish trust through inspectabilityUsers should be able to examine how a result was produced when confidence, accountability, or decision quality is important.Open principle →
- P8trustMake hand-offs, approvals, and blockers explicitWhen the system cannot proceed, the reason should be immediately visible, along with any action required from the user or another dependency.Open principle →
- P9orchestrationRepresent delegated work as a system, not merely as a conversationWhere work involves multiple steps, agents, dependencies, or concurrent activities, it should be represented as a structured system rather than solely as a message stream.Open principle →