Skip to content
AI Agent How-To

Home ›Framework how-tos

Pydantic AI: How to Build an Agent

Intermediate ~6 min read Last tested November 2026

Updated 2026-12-01

Pydantic AI is a typed Python agent loop: construct an Agent with a model string (provider:model), register tools on the agent, optionally set output_type, and call run_sync() or await run(). Outputs and tool arguments are validated with Pydantic. This guide mirrors the official roulette-style tutorial without extra harness packages. For MCP tools instead, see Connect an AI agent to an MCP server. Last tested 2026-12-01.

Prerequisites

  • Python 3.10+
  • An API key for your model provider (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)

Docs used:

Steps

1. Install Pydantic AI

python -m venv .venv && source .venv/bin/activate
pip install pydantic-ai
export OPENAI_API_KEY="sk-..."

You can use uv add pydantic-ai if your project uses uv (install docs).

2. Create a minimal Agent

# pydantic_agent.py
from pydantic_ai import Agent

agent = Agent(
    "openai:gpt-4.1-mini",
    instructions="Answer briefly. Use tools when the user asks for live data.",
)

Model strings use the provider:model format documented on the Agents page.

3. Register a tool with @agent.tool

from pydantic_ai import Agent, RunContext

agent = Agent(
    "openai:gpt-4.1-mini",
    deps_type=int,
    output_type=bool,
    instructions=(
        "Use the roulette_wheel tool to check if the user's number wins."
    ),
)

@agent.tool
async def roulette_wheel(ctx: RunContext[int], square: int) -> str:
    """Return whether the square matches the winning number in ctx.deps."""
    return "winner" if square == ctx.deps else "loser"

RunContext carries dependencies (deps) your tools may need (Agents introduction).

4. Run synchronously for a script

winning = 18
result = agent.run_sync("Put my money on square eighteen", deps=winning)
print(result.output)  # validated bool

result.output is typed from output_type.

5. Run asynchronously in an app

import asyncio

async def main() -> None:
    result = await agent.run("Is square 5 a winner?", deps=18)
    print(result.output)

asyncio.run(main())

Use agent.run_stream() when you need token streaming (running agents).

6. Reuse one Agent like a FastAPI app

Instantiate Agent once at import time and call run from routes or jobs. Multiple specialized agents are also fine; both patterns are supported in the docs.

7. Add structured final output (optional)

from pydantic import BaseModel

class Summary(BaseModel):
    headline: str
    bullets: list[str]

summarizer = Agent(
    "openai:gpt-4.1-mini",
    output_type=Summary,
    instructions="Return a short headline and two bullet points.",
)

out = summarizer.run_sync("Summarize why agents use tools.")
print(out.output.bullets)

Pydantic validates the model’s JSON into Summary.

Common errors

Validation error on result.output. The model returned JSON that does not match output_type. Narrow the instructions or switch to str output until prompts stabilize.

Tool never called. The user message may not require it, or instructions omit when to use the tool. Mention the tool by name in instructions.

Unknown model string. Use the provider:model IDs listed in Pydantic AI model docs; typos fail at runtime.

Async tool in a sync script. Use run_sync only with sync-compatible tools, or call asyncio.run(agent.run(...)) for async tools.

FAQ

How do I build an agent in Pydantic AI?

Install pydantic-ai, create Agent("provider:model"), attach tools with @agent.tool, then run_sync() or await run().

How is Pydantic AI different from a raw OpenAI tool loop?

Build your first AI agent in Python shows manual message history. Pydantic AI validates outputs and tool args and exposes streaming helpers.

Can Pydantic AI call MCP servers?

Not as a first-class MCP client in the minimal Agent API. Use Connect an AI agent to an MCP server or Claude Agent SDK MCP.

Does Pydantic AI replace LangGraph?

No. LangGraph adds checkpointing, interrupts, and multi-node graphs (LangGraph: build an agent, human in the loop). Pydantic AI focuses on a single typed agent loop.