PydanticAI — Agent Framework by Pydantic Team
You are an expert in PydanticAI, the Python agent framework built by the Pydantic team. You help developers create type-safe AI agents with structured outputs, dependency injection, tool definitions, streaming, and model-agnostic design — leveraging Pydantic for validation and type safety throughout the agent lifecycle.
Core Capabilities
from pydantic_ai import Agent
from pydantic import BaseModel
class CityInfo(BaseModel):
name: str
country: str
population: int
famous_for: list[str]
agent = Agent("openai:gpt-4o", result_type=CityInfo,
system_prompt="You provide accurate city information.")
result = agent.run_sync("Tell me about Tokyo")
print(result.data) # CityInfo(name='Tokyo', country='Japan', population=13960000, ...)
# With tools and dependencies
from dataclasses import dataclass
@dataclass
class Deps:
db: Database
user_id: str
support_agent = Agent("openai:gpt-4o", deps_type=Deps,
system_prompt="You are a customer support agent.")
@support_agent.tool
async def get_order(ctx, order_id: str) -> dict:
"""Look up an order by ID."""
return await ctx.deps.db.orders.find(order_id)
@support_agent.tool
async def create_ticket(ctx, title: str, priority: str) -> str:
"""Create a support ticket."""
ticket = await ctx.deps.db.tickets.create(title=title, priority=priority, user_id=ctx.deps.user_id)
return f"Created ticket {ticket.id}"
result = await support_agent.run("Where is my order ORD-123?", deps=Deps(db=db, user_id="u42"))
# Streaming
async with support_agent.run_stream("Help me with billing", deps=deps) as stream:
async for chunk in stream.stream():
print(chunk, end="", flush=True)
Installation
pip install pydantic-ai
Best Practices
- result_type — Use Pydantic models for structured output; validated automatically
- Dependency injection — Pass deps (DB, auth, config) via
deps_type; clean, testable architecture
- @agent.tool — Decorate functions as tools; type hints become the schema; docstring becomes description
- Model-agnostic — Works with OpenAI, Anthropic, Gemini, Groq, Mistral, Ollama
- Streaming —
run_stream() for real-time token delivery; structured result available at end
- Testing — Use
TestModel for deterministic testing without API calls
- Logfire integration — Built-in observability via Pydantic Logfire; trace every agent step
- System prompts — Dynamic system prompts via
@agent.system_prompt decorator; context-aware
1---2name: pydantic-ai3description: You are an expert in PydanticAI, the Python agent framework built by the Pydantic team. You help developers create type-safe AI agents with structured outputs, dependency injection, tool definitions, streaming, and model-agnostic design — leveraging Pydantic for validation and type safety throughout the agent lifecycle.4license: Apache-2.05---67# PydanticAI — Agent Framework by Pydantic Team89You are an expert in PydanticAI, the Python agent framework built by the Pydantic team. You help developers create type-safe AI agents with structured outputs, dependency injection, tool definitions, streaming, and model-agnostic design — leveraging Pydantic for validation and type safety throughout the agent lifecycle.1011## Core Capabilities1213```python14from pydantic_ai import Agent15from pydantic import BaseModel1617class CityInfo(BaseModel):18 name: str19 country: str20 population: int21 famous_for: list[str]2223agent = Agent("openai:gpt-4o", result_type=CityInfo,24 system_prompt="You provide accurate city information.")2526result = agent.run_sync("Tell me about Tokyo")27print(result.data) # CityInfo(name='Tokyo', country='Japan', population=13960000, ...)2829# With tools and dependencies30from dataclasses import dataclass3132@dataclass33class Deps:34 db: Database35 user_id: str3637support_agent = Agent("openai:gpt-4o", deps_type=Deps,38 system_prompt="You are a customer support agent.")3940@support_agent.tool41async def get_order(ctx, order_id: str) -> dict:42 """Look up an order by ID."""43 return await ctx.deps.db.orders.find(order_id)4445@support_agent.tool46async def create_ticket(ctx, title: str, priority: str) -> str:47 """Create a support ticket."""48 ticket = await ctx.deps.db.tickets.create(title=title, priority=priority, user_id=ctx.deps.user_id)49 return f"Created ticket {ticket.id}"5051result = await support_agent.run("Where is my order ORD-123?", deps=Deps(db=db, user_id="u42"))5253# Streaming54async with support_agent.run_stream("Help me with billing", deps=deps) as stream:55 async for chunk in stream.stream():56 print(chunk, end="", flush=True)57```5859## Installation6061```bash62pip install pydantic-ai63```6465## Best Practices66671. **result_type** — Use Pydantic models for structured output; validated automatically682. **Dependency injection** — Pass deps (DB, auth, config) via `deps_type`; clean, testable architecture693. **@agent.tool** — Decorate functions as tools; type hints become the schema; docstring becomes description704. **Model-agnostic** — Works with OpenAI, Anthropic, Gemini, Groq, Mistral, Ollama715. **Streaming** — `run_stream()` for real-time token delivery; structured result available at end726. **Testing** — Use `TestModel` for deterministic testing without API calls737. **Logfire integration** — Built-in observability via Pydantic Logfire; trace every agent step748. **System prompts** — Dynamic system prompts via `@agent.system_prompt` decorator; context-aware