What is Pydantic AI? Type-Safe Agent Framework in 2026
What is Pydantic AI? The MIT-licensed Python agent framework from the Pydantic team. See how V2 capabilities, typed tools, output validation and tracing work.
Table of Contents
What is Pydantic AI? It is an open-source Python agent framework from the team behind Pydantic. You declare what an agent must return as a typed output_type, and the framework validates each answer, retries on validation failures, and runs on OpenAI, Anthropic, Google or local models with a one-string model swap. An invoice agent built this way returns a validated Invoice object, not free text to parse.
That combination is the niche Pydantic AI fills. Pydantic AI treats type safety as a first-class invariant. The framework is opinionated about validation and is a strong fit for teams already using Pydantic and FastAPI who want the same ergonomics for agents. This guide covers what Pydantic AI is, what changed in V2, how its primitives work, and when to pick it.
What is Pydantic AI, in short
- Pydantic AI is an MIT-licensed Python agent framework from Pydantic Services Inc. Its GitHub repo had more than 21,000 stars on November 4, 2026.
- V2 has been stable since June 23, 2026, and current releases require Python 3.11 or newer.
- Core primitives: Agent, typed tools,
output_type,deps_typewithRunContext, a model string, and V2 capabilities that bundle tools, hooks, instructions and model settings. - Instrumentation is plain OpenTelemetry, so Future AGI can trace a run through traceAI.
Why Pydantic AI matters in 2026
Three forces made type-safe agent frameworks a procurement consideration. First, structured output became the default in production. A 2024 LLM application returned freeform text that downstream code parsed, while a 2026 application returns a typed object that downstream code consumes directly. Frameworks that bake validation into the run loop (Pydantic AI, OpenAI Agents SDK with output_type, Instructor) saved teams from rolling their own validation layer.
Second, multi-provider production stacks are common. A team that runs OpenAI for the main path, Anthropic for the long-context path, Gemini for the vision path, and Ollama for the local-eval path needs a framework that abstracts provider differences without leaking them. Pydantic AI’s Model abstraction with a string identifier (e.g. openai:gpt-6.1-sol) keeps the provider choice to one string.
Third, the Pydantic ecosystem ran ahead. The Pydantic library itself is the de facto Python validation standard, and FastAPI built on it. Pydantic Logfire followed for observability. A Pydantic-branded agent framework with the same ergonomics as those products had a built-in audience the day it launched.
The anatomy of a Pydantic AI application
Agent. The central class. You construct it with a model identifier, a system prompt, an optional deps_type, an optional output_type, and a set of decorated tool methods. The Agent runs through run, run_sync, run_stream, run_stream_events, or iter.

Tool. A function decorated with @agent.tool (with RunContext access) or @agent.tool_plain (without). The function signature defines the tool’s argument schema; type hints feed straight into the model’s tool-calling format. Tool arguments are validated against the schema; if you also need the return value validated, call Model.model_validate(result) inside the tool, since Pydantic AI serializes tool return values without validating them.
output_type. A Pydantic model that the agent’s final answer must validate against. If validation fails, the framework retries with the validation error as a hint to the model. The retry budget is configurable.
deps_type. A typed dependency object passed into agent.run and accessible inside tools as ctx.deps. The pattern is FastAPI-style: dependencies are objects that tools borrow per-call.
RunContext. The per-call context passed to tools. Carries deps, messages, the model, retry count, and metadata.
Model. The provider abstraction. Use a string identifier such as openai:gpt-6.1-sol, anthropic:claude-sonnet-5-5, google:gemini-3.8-flash, ollama:llama3.3, groq:openai/gpt-oss-120b, or mistral:mistral-large-latest. Since V2, the openai: prefix calls the OpenAI Responses API; use openai-chat: to stay on Chat Completions.
What is new in Pydantic AI V2
Pydantic AI V2 became stable on June 23, 2026, after seven betas. V1, released in September 2025, promised no breaking changes until V2, so V2 collects the API changes that promise held back. Its central idea is the capability, one composable unit that bundles an agent’s tools, hooks, instructions and model settings.
Capabilities attach to any agent through the capabilities argument. The core package ships the ones that need model or framework support, such as MCP and web search. Pydantic AI Harness, a separate MIT-licensed package, adds the rest, from memory, guardrails, sub-agents and planning to complete agents such as Coder and Researcher.
Upgrading from V1 changes a few defaults. A bare pip install pydantic-ai now bundles only the OpenAI, Anthropic and Google model libraries, so Groq, Mistral or Bedrock need extras. The openai: prefix now calls the Responses API, google-gla: became google:, and pydantic_graph.persistence is gone; to save and resume agent run state, the Harness ships a StepPersistence capability.
Pydantic AI in 30 lines
Install
Pydantic AI installs from PyPI and requires Python 3.11 or newer. The base install includes the OpenAI, Anthropic and Google model libraries plus the CLI, MCP, Evals, Web UI and Logfire integrations. Other providers, such as Groq and Mistral, install as extras.
# Base install (OpenAI, Anthropic, Google included)
pip install pydantic-ai
# Optional: slim install, only the extras you name
pip install "pydantic-ai-slim[openai]"
# Optional: providers the base install leaves out
pip install "pydantic-ai[groq,mistral]"
Set provider credentials as environment variables before running the agent. The framework reads each one automatically based on the model string you pass, so an openai: model needs only OPENAI_API_KEY:
export OPENAI_API_KEY=sk-... # for openai:gpt-6.1-sol
export ANTHROPIC_API_KEY=sk-ant-... # for anthropic:claude-sonnet-5-5
export GOOGLE_API_KEY=... # for google:gemini-3.8-flash
Minimum viable agent
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
@dataclass
class SupportDeps:
customer_id: str
db_pool: object # your real database connection pool
class SupportResult(BaseModel):
response: str = Field(description="Reply to send to the customer.")
needs_escalation: bool
agent = Agent(
"openai:gpt-6.1-sol",
deps_type=SupportDeps,
output_type=SupportResult,
system_prompt="You are a support agent for the FastAPI hosting platform.",
)
@agent.tool
async def lookup_account(ctx: RunContext[SupportDeps]) -> dict:
"""Return the customer's plan, usage, and last invoice."""
return await ctx.deps.db_pool.fetchrow("SELECT plan, usage, last_invoice FROM customers WHERE id=$1", ctx.deps.customer_id)
result = agent.run_sync(
"Why was my last bill higher than usual?",
deps=SupportDeps(customer_id="cust_123", db_pool=pool),
)
print(result.output.response, result.output.needs_escalation)
The agent calls the model, the model calls lookup_account, the framework validates the tool’s argument schema, the model produces a final answer, and the framework validates the final answer against SupportResult. The result.output value is a typed SupportResult.
How Pydantic AI compares to alternatives
| Framework | Lead with | Best for | License |
|---|---|---|---|
| Pydantic AI | Type-safe agents, provider neutrality | Validated outputs, multi-provider stacks, FastAPI-shaped teams | MIT |
| OpenAI Agents SDK | Agent loop with tools, handoffs, guardrails, HITL | OpenAI-first, multi-agent handoff patterns | MIT |
| LangChain + LangGraph | Chains and stateful graphs | Multi-agent orchestration, broad ecosystem | MIT |
| Instructor | Structured output decoration on LLM clients | Structured outputs without full agent loop | MIT |
Pydantic AI’s positioning: type-safe agents with provider neutrality, written by Pythonistas who like FastAPI. If that description fits the team, the framework is a strong choice. If the team is heavily invested in LangChain or OpenAI’s ecosystem, the switching cost may not pay back.
Production patterns with Pydantic AI
Pattern 1: Validated single-agent extraction. An Agent with a Pydantic output_type for structured extraction, no tools, used in a synchronous run_sync call. Common for invoice extraction, resume parsing, and structured-data ingestion. The framework’s validation retry loop handles models that occasionally produce malformed JSON.
Pattern 2: Tool-using agent with deps for shared infra. An Agent with several @agent.tool functions that all access ctx.deps for database, HTTP, and config. The deps pattern keeps tools stateless and testable. The Agent runs synchronously inside an HTTP request handler.
Pattern 3: pydantic-graph for stateful workflows. A graph of typed nodes, each potentially backed by an Agent. A typed state object flows through the graph, and each node reads and updates it. The pattern competes directly with LangGraph for state-machine workflows where Pydantic validation and Python ergonomics matter more than maximum flexibility.
Common mistakes when adopting Pydantic AI
- Skipping output_type. A free-form text result loses one of the framework’s main benefits. Declare a Pydantic result model wherever the output is consumed by downstream code.
- Threading deps manually. If your tool functions take a db parameter directly instead of pulling it from ctx.deps, you lose the testability benefit. Always go through deps.
- Hardcoding the model identifier in production. Read it from config so you can swap providers without code changes. The string-based Model abstraction makes this trivial.
- Forgetting tool docstrings. The framework feeds the docstring into the model as the tool description. A function with no docstring is a tool with no description.
- Using @agent.tool when @agent.tool_plain is enough. tool_plain is for tools that do not need RunContext. Use the smaller decorator when you can; the contract is clearer.
- Skipping the retry budget. Validation retries can amplify cost. Configure max retries explicitly for production.
- Treating pydantic-graph as required. Many Pydantic AI applications never need graphs. Only reach for the graph module when state machines and explicit flow control matter.
How to trace Pydantic AI with Future AGI
Pydantic AI ships optional OpenTelemetry instrumentation that emits standard OTel spans, and traceAI adds a dedicated traceai-pydantic-ai package. To ship traces to Future AGI’s observability platform or any other OTel backend with traceAI:
pip install fi-instrumentation-otel traceai-pydantic-ai
from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType
from traceai_pydantic_ai import PydanticAIInstrumentor
trace_provider = register(
project_type=ProjectType.OBSERVE,
project_name="invoice-extraction",
set_global_tracer_provider=True,
)
PydanticAIInstrumentor().instrument(tracer_provider=trace_provider, use_builtin=True)
# Your Pydantic AI agents now emit span trees once instrumentation is registered.
The resulting trace tree has the agent run at the root, each model call as a chat child span, and each tool call as an execute_tool span with its arguments. Each chat span also records the model name and the tool schemas sent with that request.

Closing the loop around Pydantic AI agents
Tracing tells you what happened. Evals tell you whether it was right. The deep-dive on evaluating Pydantic AI agents that use MCP tools walks the full eval workflow. Pydantic AI handles the agent runtime, traceAI handles the spans, and the rest of the loop runs on Future AGI:
-
Tool and outcome evals. Built-in evals such as Task Completion, Evaluate Function Calling and Detect Hallucination, plus custom LLM-as-Judge and code evals, score the traces your agent emits. BYOK judges run on your own model key at $0 platform cost, and
turing_flashis the managed judge when you want one. -
Simulation. Persona-driven text and voice scenarios test typed agents before production, and every simulated conversation gets a score from the evals you attach to the run.
- Gateway. The Agent Command Center is Future AGI’s AI gateway, with one API for routing across 100+ providers, guardrails, caching and cost tracking, so a model swap is a config change instead of a code change.
- Guardrails. Gateway guardrails such as PII Detection, Prompt Injection, Secret Detection and Content Moderation screen traffic and compose with Pydantic AI’s typed-tool validation. Validation handles structure; guardrails handle intent.
- Optimizer. The prompt optimizers in agent-learning-kit, including GEPA, ProTeGi and PromptWizard, take a prompt and the evals that score it, then search for a version that scores higher. Install them with
pip install agent-learning-kit.
The Future AGI Apache-2.0 core is self-hostable. The Free plan needs no credit card, Pay-as-you-go starts at $0 a month plus usage, and add-ons cover compliance, with Boost adding SOC 2 Type II and Scale adding a HIPAA BAA, SAML SSO and SCIM (pricing). For more on the underlying tracing model, see What is LLM Tracing?.
To see every model and tool call your invoice agent makes, send your first Pydantic AI trace to Future AGI Observe and attach an eval to the spans it emits.
Sources
- Pydantic AI GitHub repo
- Pydantic AI documentation
- Pydantic AI installation guide
- Pydantic AI agents guide
- Pydantic AI function tools guide
- Pydantic AI capabilities overview
- Pydantic AI Harness documentation
- pydantic-graph documentation
- Pydantic AI changelog
- Pydantic AI v2.0.0 release
- Pydantic AI V1 to V2 migration map
- Pydantic AI vs LangChain and LangGraph
- OpenAI API deprecations
- Claude model deprecations
- Gemini API deprecations
- Groq model deprecations
Series cross-link
Related: What is CrewAI?, What is LangGraph?, What is the OpenAI Agents SDK?
Frequently Asked Questions
What is Pydantic AI?
What is Pydantic AI used for?
Pydantic vs Pydantic AI, what is the difference?
What is Pydantic AI Harness?
Pydantic AI vs LangGraph, which should I use?
Evaluate Pydantic AI agents that call MCP tools in 2026: per-typed-output rubrics, tool-call argument fidelity, MCP security checks, dependency invariants.
Five Pydantic AI alternatives on multi-agent depth, language reach, observability without Logfire, optimizer. What each actually fixes past type-system.
OpenAI Agents SDK is OpenAI's open-source framework for agent loops, handoffs, guardrails, and sessions. Architecture, primitives, and how to trace it.