Pydantic AI is the agent framework from the team behind Pydantic, and it is now on version 2.79.0 (4 Dec 2026). It lets you build typed, testable AI agents in plain Python, with the same code working across OpenAI, Anthropic, Gemini and Ollama.
This tutorial walks you through install, your first agent, typed output, tools, dependencies, streaming and MCP. Every code sample was checked against the v2.79 package and the official docs.
- Current version: pydantic-ai 2.79.0 on PyPI, needs Python 3.11 or newer. V2 shipped on 23 June 2026.
- Install:
pip install pydantic-ai, or the slim package with only the providers you need. - Model strings:
openai:gpt-6.2-sol,anthropic:claude-sonnet-5-5,google:gemini-4-neon,ollama:qwen3. - Typed output: pass a Pydantic model as
output_typeandresult.outputcomes back validated. - MCP: V1’s
MCPServerStdioand friends are gone. Use theMCPcapability orMCPToolset. - Cost: the framework is free and open source. You only pay the model provider.
What Pydantic AI Is and When to Use It
Pydantic AI is an open-source Python framework for building LLM agents. An agent is a model plus instructions, tools and an output type. The framework runs the loop of calling the model, running tools and validating the answer.
Its big idea is type safety. Your tools, dependencies and outputs are normal Python types, so your editor and type checker can catch mistakes before you run anything.
Good fits
- Structured extraction: turn emails, invoices or tickets into validated objects.
- Tool-using assistants: agents that query a database, call an API or read files.
- Multi-provider apps: switch between OpenAI, Claude and Gemini by changing one string.
- Production services: you get usage limits, retries, testing models and OpenTelemetry tracing built in.
What changed in V2
Pydantic AI v2.0.0 was released on 23 June 2026. The release post lists a few headline changes that matter for this tutorial.
- Capabilities: a capability bundles instructions, tools, hooks and model settings into one reusable unit.
- Responses API by default:
openai:model names now use OpenAI’s Responses API. Useopenai-chat:to stay on Chat Completions. - Leaner install: OpenAI, Anthropic and Google stay in the default install. Groq, Mistral, Bedrock and others are opt-in extras.
- Renamed parts:
google-gla:becamegoogle:,OpenAIModelbecameOpenAIChatModel, and the MCP server classes merged intoMCPToolset.
Note: Many blog posts and AI answers still show V1 code such as MCPServerStdio or google-gla:. That code fails on 2.79. The examples below use the current names.
Install Pydantic AI (Step by Step)
You need Python 3.11 or newer, an API key for at least one provider, and a terminal. Ollama users need no key at all.
- Check your Python version. Run
python --version. If it says 3.10 or lower, install a newer Python first. - Create a virtual environment. Run
python -m venv .venv, then activate it withsource .venv/bin/activateon Mac and Linux, or.venv\Scripts\activateon Windows. - Install the package. Run
pip install pydantic-aifor the full install. For a smaller install, usepip install "pydantic-ai-slim[openai,anthropic,google]"and add only what you need. - Add extras as needed. Use
mcpfor MCP servers,logfirefor tracing, andgroqormistralfor those providers. Ollama uses theopenaiextra. - Set your API key. Export
OPENAI_API_KEY,ANTHROPIC_API_KEYorGOOGLE_API_KEYin your shell. Never paste a key into your code. - Test without a key. Run
Agent('test')with the built-in test model to confirm the install works before you spend any tokens.

If you still need provider keys, see how to get an OpenAI API key and how to get a Claude API key.
Your First Agent
An Agent takes a model string and optional instructions. Call run_sync() for a simple script, or await agent.run() inside async code.
from pydantic_ai import Agent
agent = Agent(
'openai:gpt-6.2-sol',
instructions='Answer in one short, friendly sentence.',
)
result = agent.run_sync('What is the capital of Japan?')
print(result.output)
print(result.usage) # RunUsage(input_tokens=..., output_tokens=..., requests=1)
Three things to notice here:
- result.output holds the answer. With no
output_type, it is a plain string. - result.usage is now a property in V2. The old
result.usage()call still works but warns. - Instructions are the recommended way to set a system-level prompt.
system_promptstill exists for older code.
Keep a conversation going
Each run is stateless. To continue a chat, pass the previous messages back in with message_history.
first = agent.run_sync('My name is Asha.')
second = agent.run_sync('What is my name?', message_history=first.all_messages())
print(second.output)
Tip: On startup, v2.79 prints a small banner that suggests turning on observability. Set PYDANTIC_AI_NO_BANNER=1 in your environment to hide it.
Model Strings for OpenAI, Anthropic, Gemini and Ollama
Models are named as provider:model. The table below shows the prefixes and the environment variables that v2.79 asks for when a key is missing.
| Provider | Example model string | Env variable | Extra |
|---|---|---|---|
| OpenAI (Responses API) | openai:gpt-6.2-sol |
OPENAI_API_KEY |
openai |
| OpenAI (Chat Completions) | openai-chat:gpt-6.2-sol |
OPENAI_API_KEY |
openai |
| Anthropic Claude | anthropic:claude-sonnet-5-5 |
ANTHROPIC_API_KEY |
anthropic |
| Google Gemini API | google:gemini-4-neon |
GOOGLE_API_KEY |
|
| Google Cloud (Vertex) | google-cloud:gemini-4-neon |
Cloud credentials | |
| Ollama (local or cloud) | ollama:qwen3 |
OLLAMA_BASE_URL |
openai |
Other known model names in v2.79 include openai:gpt-6.2-astra, anthropic:claude-opus-5-5, anthropic:claude-haiku-5-5, anthropic:claude-fable-5-2 and google:gemini-4-hydrogen.
Run an agent on local Ollama
Start Ollama, pull a model, and point Pydantic AI at the local OpenAI-compatible endpoint. First, check that the server answers:
ollama pull qwen3
export OLLAMA_BASE_URL='http://localhost:11434/v1'
curl http://localhost:11434/v1/models
Then use the ollama: prefix, or build the model object yourself if you want to set the URL in code:
from pydantic_ai import Agent
from pydantic_ai.models.ollama import OllamaModel
from pydantic_ai.providers.ollama import OllamaProvider
model = OllamaModel('qwen3', provider=OllamaProvider(base_url='http://localhost:11434/v1'))
agent = Agent(model, instructions='Be concise.')
print(agent.run_sync('Give me one tip for writing clean Python.').output)
Small local models are weaker at tool calls and structured output. Our best Ollama models list can help you pick one that handles tools well.
Typed Output with output_type
This is where Pydantic AI shines. Pass a Pydantic model as output_type, and the agent forces the LLM to return data in that shape. If validation fails, the error goes back to the model so it can try again.
from pydantic import BaseModel, Field
from pydantic_ai import Agent
class CityInfo(BaseModel):
city: str
country: str
population_millions: float = Field(description='Population in millions')
agent = Agent(
'anthropic:claude-sonnet-5-5',
output_type=CityInfo,
instructions='Extract facts about the city the user mentions.',
)
result = agent.run_sync('Tell me about Tokyo.')
info = result.output # a real CityInfo object
print(info.city, info.country, info.population_millions)
Other output options
- Unions: use
output_type=[CityInfo, str]to let the model return either an object or a plain answer. - ToolOutput: the default for models; the output is sent as a special tool call.
- NativeOutput: uses the provider’s own structured output (JSON schema) mode where supported.
- PromptedOutput: puts the schema in the prompt, handy for small local models.
Field descriptions are sent to the model, so write them like short instructions. For a provider-by-provider view of JSON modes, see our structured outputs guide.
Tools and Dependencies
Tools are Python functions the model can call. Dependencies are objects you pass into a run, such as a database client or the current user. Tools read them through RunContext.
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext, ModelRetry
@dataclass
class ShopDeps:
user_name: str
discount: float # 0.1 means 10% off
agent = Agent(
'openai:gpt-6.2-sol',
deps_type=ShopDeps,
instructions='You are a helpful shop assistant.',
)
@agent.instructions
def add_user_name(ctx: RunContext[ShopDeps]) -> str:
return f"The customer's name is {ctx.deps.user_name}."
@agent.tool
def get_price(ctx: RunContext[ShopDeps], product: str) -> float:
"""Return the discounted price of a product in USD."""
prices = {'mouse': 20.0, 'keyboard': 45.0}
if product not in prices:
raise ModelRetry(f'Unknown product {product!r}. Try mouse or keyboard.')
return prices[product] * (1 - ctx.deps.discount)
@agent.tool_plain
def store_hours() -> str:
"""Return the store opening hours."""
return 'Mon to Sat, 9am to 6pm'
result = agent.run_sync('How much is a keyboard for me?', deps=ShopDeps('Asha', 0.1))
print(result.output)
How the pieces fit
- @agent.tool: the first argument is
RunContext, which gives the tool access toctx.deps. - @agent.tool_plain: for tools that need no context.
- Docstrings: become the tool description the model sees. Type hints become the JSON schema.
- ModelRetry: tells the model what went wrong so it can fix its arguments and call again.
- Dynamic instructions:
@agent.instructionsfunctions run on every request, so they can use live data.
Warning: The default tool retry count is 1. If a tool raises ModelRetry twice in a row, the run stops with UnexpectedModelBehavior. Raise it with retries=3 on the Agent or on a single tool.
V2 also adds ready-made capabilities such as WebSearch, WebFetch and Thinking in pydantic_ai.capabilities. They plug in through capabilities=[...] on the Agent.
Streaming Responses
For chat UIs, you want text to appear as it is generated. Use run_stream() as an async context manager and read chunks with stream_text().
import asyncio
from pydantic_ai import Agent
agent = Agent('google:gemini-4-neon', instructions='Write vivid, short answers.')
async def main():
async with agent.run_stream('Write a haiku about Python.') as result:
async for chunk in result.stream_text(delta=True):
print(chunk, end='', flush=True)
print()
print(result.usage)
asyncio.run(main())
A few streaming details worth knowing:
- delta=True gives only the new text. Without it, each item is the full text so far.
- stream_output() streams partial structured objects when you use an
output_type. In V2 it replaces the oldstream()method. - run_stream_sync() gives the same result in non-async scripts.
- run_stream_events() exposes every event, including tool calls. In V2 you use it as
async with agent.run_stream_events(...) as events:.
MCP Support
Pydantic AI can act as an MCP client, so your agent can use tools from any Model Context Protocol server. In V2 this is built on the FastMCP client.

Option 1: the MCP capability (remote URL)
For a remote Streamable HTTP server, the docs recommend the MCP capability. Install with pip install "pydantic-ai-slim[mcp]".
from pydantic_ai import Agent
from pydantic_ai.capabilities import MCP
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[MCP(url='http://localhost:8000/mcp')],
)
print(agent.run_sync('What is 7 plus 5?').output)
The capability also takes allowed_tools, headers and native=True. The last one lets the model provider call the MCP server directly instead of your app.
Option 2: MCPToolset with a local stdio server
Here is a tiny FastMCP server. Save it as mcp_server.py and install the server package with pip install fastmcp.
import random
from fastmcp import FastMCP
mcp = FastMCP('dice')
@mcp.tool
def roll(sides: int = 6) -> int:
"""Roll one die with the given number of sides."""
return random.randint(1, sides)
if __name__ == '__main__':
mcp.run()
Now connect it with MCPToolset and a stdio transport. Pydantic AI starts the server process for you.
import asyncio
from fastmcp.client.transports import StdioTransport
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPToolset
toolset = MCPToolset(StdioTransport(command='python', args=['mcp_server.py']))
agent = Agent('openai:gpt-6.2-sol', toolsets=[toolset])
async def main():
async with agent: # keeps the MCP connection open across runs
result = await agent.run('Roll a 20-sided die for me.')
print(result.output)
asyncio.run(main())
Want to build your own server? See build an MCP server in Python and our list of the best MCP servers.
Logfire Observability
Pydantic Logfire is the team’s tracing tool. It shows every model call, tool call, token count and cost in a timeline. Pydantic AI also works with any OpenTelemetry backend.
- Install it. Run
pip install "pydantic-ai-slim[logfire]"(the fullpydantic-aipackage already includes it). - Connect a project. Run
uvx logfire-cli authand thenuvx logfire-cli init. - Add two lines. Call
logfire.configure()andlogfire.instrument_pydantic_ai()before you run any agents.
import logfire
from pydantic_ai import Agent
logfire.configure()
logfire.instrument_pydantic_ai()
agent = Agent('openai:gpt-6.2-sol')
agent.run_sync('Hello!')
To send traces somewhere else, set OTEL_EXPORTER_OTLP_ENDPOINT and call logfire.configure(send_to_logfire=False). Logfire has its own pricing; check the Logfire site before you send production traffic.
Cost, Limits and Usage Caps
Pydantic AI itself is free and open source (MIT licence). Your bill comes from the model provider. Here are standard prices from the official pricing pages on 5 Dec 2026.
| Model string | Input / 1M tokens | Output / 1M tokens |
|---|---|---|
openai:gpt-6.2-sol |
$2.00 | $10.00 |
openai:gpt-6.2-astra |
$8.00 | $40.00 |
anthropic:claude-sonnet-5-5 |
$2.00 | $10.00 |
anthropic:claude-opus-5-5 |
$4.00 | $20.00 |
anthropic:claude-haiku-5-5 |
$0.10 (prompts up to 100K) | $0.50 (prompts up to 100K) |
ollama:qwen3 (local) |
$0 | $0 (your hardware) |
Worked example: an extraction agent on GPT-6.2 Sol uses 3,000 input and 500 output tokens per run. That is $0.006 + $0.005 = $0.011 per run, or about $11 for 1,000 runs. Tool calls add extra requests, so check result.usage on real traffic.
Gemini prices changed on 1 Dec 2026, so check our Gemini API pricing guide for current numbers. For the bigger picture, see the AI API pricing comparison.
Built-in limits
| Setting | Default in v2.79 | How to change |
|---|---|---|
| Model requests per run | 50 | UsageLimits(request_limit=10) |
| Tool or output retries | 1 | Agent(..., retries=3) |
| Token caps | None | UsageLimits(total_tokens_limit=20000) |
| Cost cap | None | UsageLimits(cost_limit=Decimal('0.50')) |
| Tool calls | None | UsageLimits(tool_calls_limit=5) |
Pass limits per run with agent.run_sync(prompt, usage_limits=UsageLimits(...)). When a limit is hit, the run raises UsageLimitExceeded.
Pydantic AI vs LangChain vs OpenAI Agents SDK
All three build agents in Python, but they feel different. Here is a quick side-by-side based on each project’s docs and PyPI page on 5 Dec 2026.
| Feature | Pydantic AI | LangChain | OpenAI Agents SDK |
|---|---|---|---|
| Latest version | 2.79.0 | 1.5.2 (LangGraph 1.2.25) | 0.26.2 |
| Python | 3.11+ | 3.11+ | 3.10+ |
| Create an agent | Agent('openai:...') |
create_agent(model=...) |
Agent(...) + Runner |
| Typed output | output_type, validated with Pydantic |
response_format |
output_type |
| Multi-provider | Built in, one string | Built in, one string | OpenAI first; others via LiteLLM or Any-LLM adapters |
| MCP client | Yes (FastMCP based) | Yes (adapters) | Yes |
| Tracing | Logfire or any OpenTelemetry | LangSmith | Built-in OpenAI tracing |
| Best for | Typed, testable services | Large ecosystem, graphs and state | OpenAI-centric agents with handoffs |
For deeper dives, read our OpenAI Agents SDK guide and the Claude Agent SDK guide, which covers Anthropic’s agent harness.
Troubleshooting: Common Errors and Fixes
These are real error messages from pydantic-ai 2.79, with the fix for each one.
| Error message | Cause | Fix |
|---|---|---|
UserError: Set the `OPENAI_API_KEY` environment variable... |
No key in the environment | Export the key in the same shell, or pass OpenAIProvider(api_key=...). Same pattern for Anthropic and Google. |
UserError: Set the `OLLAMA_BASE_URL` environment variable... |
Ollama URL not set | Export OLLAMA_BASE_URL='http://localhost:11434/v1' or use OllamaProvider(base_url=...). |
Unknown model: google-gla:... Did you mean 'google:...'? |
V1 prefix | Change google-gla: to google:, and google-vertex: to google-cloud:. |
ImportError: Please install the `groq` package... |
Provider extra missing | Run pip install "pydantic-ai-slim[groq]" (or the extra the message names). |
ImportError on MCPServerStdio or OpenAIModel |
V1 class names | Use MCPToolset and OpenAIChatModel. |
Tool 'get_price' exceeded max retries count of 1 |
Tool raised ModelRetry again |
Improve the tool description, or set retries=3. |
UsageLimitExceeded: The next request would exceed the request_limit... |
Agent looped too many times | Raise the limit, or fix the tool that keeps failing. |
FastMCP server support is not installed |
Only the client package is present | Run pip install fastmcp for your server script. |
Other common problems
- “This event loop is already running” in Jupyter: use
await agent.run(...)in notebooks instead ofrun_sync(). - 429 or 529 errors: these come from the provider. See our Claude 429 and 529 fix guide and rate limits explainer.
- Weird output on small local models: try
PromptedOutputor a bigger model.
Frequently Asked Questions
What is the latest version of Pydantic AI?
The latest release on PyPI is 2.79.0, published on 4 December 2026. Pydantic AI v2.0.0 came out on 23 June 2026, and new minor versions ship several times a week.
Is Pydantic AI free?
Yes. The framework is open source under the MIT licence. You pay only for the model API you call, and local models through Ollama cost nothing beyond your hardware.
Which Python version does Pydantic AI need?
Pydantic AI 2.x requires Python 3.11 or newer. Older Python versions will fail to install the current release.
Does Pydantic AI work with Claude and Gemini?
Yes. Use anthropic:claude-sonnet-5-5 for Claude and google:gemini-4-neon for Gemini. Both providers are in the default install.
Can I use Pydantic AI with local models?
Yes. Set OLLAMA_BASE_URL to your Ollama server and use a model string like ollama:qwen3. vLLM and other OpenAI-compatible servers work too.
Why does my old MCPServerStdio code fail?
V2 merged the old per-transport MCP classes into one MCPToolset. Use the MCP capability for remote URLs, or MCPToolset with a StdioTransport for local servers.
Do I need Logfire to use Pydantic AI?
No. Logfire is optional. Pydantic AI runs fine without it, and you can send traces to any OpenTelemetry backend instead.
Sources
- pydantic-ai on PyPI (version 2.79.0)
- Pydantic: Pydantic AI v2 release post
- Pydantic AI docs: Installation
- Pydantic AI docs: V1 to V2 migration map
- Pydantic AI docs: Models overview
- Pydantic AI docs: Ollama
- Pydantic AI docs: MCP client
- Pydantic AI docs: Logfire
- OpenAI API pricing
- Claude API pricing
- OpenAI Agents SDK docs
- LangChain docs: Agents




