TL;DR

Pydantic AI is the agent framework to pick if your agent’s job ends in a typed Python object rather than a chat transcript. I ran v2.68.0 entirely offline with its built-in test models, and three things held up. Validation errors go back to the model as structured feedback, docstrings turn into tool schemas with per-argument descriptions, and policy code can sit in hooks outside your tools. You also get a real testing story without an API key. The costs: import pydantic_ai alone took a median 1.1 seconds on a 2-vCPU box (about 3 seconds once the Anthropic SDK loads), the package ships roughly 200,000 lines of Python, releases land about three times a week, and the first agent run in a process prints a Logfire advert to stderr. For an extraction or tool-calling service in a long-lived process, use it. For a cold-start-sensitive serverless function or a team that can’t absorb API churn, think twice.

FactValueSourceVerified
Latest releasev2.68.0, published Nov 12, 2026GitHub releasesNov 15, 2026
V2 stablev2.0.0, June 23, 2026Pydantic AI changelogNov 15, 2026
LicenseMITGitHub repoNov 15, 2026
GitHub stars~21.2kGitHub repo pageNov 15, 2026
Downloads, last month~6.7M (pydantic-ai, raw count incl. CI)pypistatsNov 15, 2026
Thoughtworks RadarTrial (Nov 2025 edition; not on the current one)Thoughtworks RadarNov 15, 2026
import pydantic_ai1,120 ms medianMy run, belowNov 15, 2026

What Pydantic AI is in v2

Pydantic AI is an agent framework from the team behind Pydantic, the validation library that FastAPI, the OpenAI SDK and most of the Python LLM tooling already sit on. The pitch has stayed the same since 1.0 shipped in September 2025: an agent is a typed Python object, its dependencies are injected through a typed context, and its output is a Pydantic model that either validates or gets sent back to the LLM with the errors.

V2 went stable on June 23, 2026, after a run of betas that started in May. The V2 announcement by Douwe Maan centers on one new idea, the capability: a composable unit that bundles instructions, tools, hooks and model settings, attached with Agent(capabilities=[...]). Thinking budgets, web search, MCP servers, history processing, model fallback and instrumentation are all capabilities now. Memory, guardrails and file-system access live in a separate first-party package, pydantic-ai-harness, so the core stays smaller (in theory; more on size below).

Upgrading from 1.x means touching code. The upgrade guide lists, among others:

  • a bare openai: model string now targets the Responses API, and Chat Completions needs openai-chat:
  • builtin_tools became native_tools, OpenAIModel became OpenAIChatModel and GeminiModel became GoogleModel
  • the default end_strategy changed from 'early' to 'graceful'
  • history_processors=, prepare_tools= and event_stream_handler= moved off the Agent constructor into capabilities
  • Agent.to_a2a() and the bundled fasta2a left the core
  • the no-breaking-changes window between majors shrank from six months to three

Plan around that last change: V1 ran 100+ releases without breaking changes, while V2 promises a shorter quiet period before the next major.

How I tested it

There’s no API key in this run. Everything below executed against Pydantic AI’s own offline models: FunctionModel, where a Python function plays the LLM, and TestModel, which generates schema-valid tool calls automatically. That’s a limitation, since I can’t tell you how Claude or GPT-6 behave inside it. But it isolates the part a framework review should judge: what the framework does around the model call.

Setup: Python 3.12.3 on a 2-vCPU Linux sandbox, pydantic-ai-slim 2.68.0 with pydantic 2.14.3 and pydantic-core 2.50.4, plus the Anthropic SDK 2.8.0 for the one example that names a real model. I unpacked the wheels from PyPI rather than pip-installing them, which is why the import-time numbers below are from a plain sys.path, not a virtualenv. That shouldn’t change them.

Structured output: the validation loop does the work

This is the feature people pick Pydantic AI for, so I tested the failure path first. The script below defines an Invoice model with constraints, then plays a model that gets the first answer wrong: a string where a number belongs and a 190% VAT rate.

from pydantic import BaseModel, Field
from pydantic_ai import Agent, ModelResponse, ToolCallPart, ToolReturnPart, UnexpectedModelBehavior
from pydantic_ai.models.function import FunctionModel, AgentInfo


class Invoice(BaseModel):
    vendor: str
    total_eur: float = Field(gt=0)
    vat_rate: float = Field(ge=0, le=0.27)


BAD = {"vendor": "Hetzner", "total_eur": "about forty", "vat_rate": 1.9}
GOOD = {"vendor": "Hetzner", "total_eur": 41.65, "vat_rate": 0.19}


def scripted(*answers):
    """A fake LLM that replays canned tool calls for the output tool."""
    calls = []
    def fn(messages, info: AgentInfo) -> ModelResponse:
        args = answers[min(len(calls), len(answers) - 1)]
        calls.append(args)
        return ModelResponse(parts=[ToolCallPart(info.output_tools[0].name, args)])
    return fn, calls


# 1. bad answer, then a good one
fn, calls = scripted(BAD, GOOD)
agent = Agent(FunctionModel(fn), output_type=Invoice)
result = agent.run_sync("Extract the invoice fields from: ...")
print("output:     ", result.output)
print("model calls:", len(calls), "| usage:", result.usage)
for msg in result.all_messages():
    for part in msg.parts:
        if isinstance(part, ToolReturnPart) and part.outcome == "retried":
            print("fed back:   ", part.model_response_str())
            print("retry info: ", part.retry)

# 2. the model never gets it right
fn, calls = scripted(BAD)
try:
    Agent(FunctionModel(fn), output_type=Invoice).run_sync("...")
except UnexpectedModelBehavior as e:
    print("gave up after", len(calls), "calls:", e)

Running it prints:

output:      vendor='Hetzner' total_eur=41.65 vat_rate=0.19
model calls: 2 | usage: RunUsage(input_tokens=160, output_tokens=30, requests=2)
fed back:    {"error":[{"type":"float_parsing","loc":["total_eur"],"msg":"Input should be a valid number, unable to parse string as a number","input":"about forty"},{"type":"less_than_equal","loc":["vat_rate"],"msg":"Input should be less than or equal to 0.27","input":1.9}]}
retry info:  RetryInfo(cause='validation_error', attempt=1, max_retries=1)
gave up after 2 calls: Exceeded maximum output retries (1)

Three details are worth knowing before you build on this. The output is delivered as a tool call (final_result), so the model fills in a JSON schema generated from your class rather than free text you parse afterwards. Both validation errors went back in one message, with loc and the offending input, which is the most useful thing you can show a model on its second try. And the default retry budget is one: a model that fails twice raises UnexpectedModelBehavior. For flaky extraction work you’ll want retries= set higher on the agent, and if the failure is a provider outage, handle it with a transport-level retry like the ones in my tenacity tutorial.

The token counts in that output (160 in, 30 out) are estimates the fake model makes up, so ignore them.

Tools and dependency injection: docstrings become the schema

The second test covers tools. RunContext[Deps] gives a tool typed access to whatever you pass as deps= at run time (a database pool, an HTTP client, a config object) without globals. I also wanted to see the exact schema the model receives.

import json, os
os.environ.setdefault("ANTHROPIC_API_KEY", "not-a-real-key")
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext, capture_run_messages
from pydantic_ai import models
from pydantic_ai.models.test import TestModel

models.ALLOW_MODEL_REQUESTS = False  # any real LLM call in this process now raises


@dataclass
class Deps:
    fx_rates: dict[str, float]


agent = Agent("anthropic:claude-sonnet-5-5", deps_type=Deps,
              instructions="Answer pricing questions in euros.")


@agent.tool
def convert(ctx: RunContext[Deps], amount: float, currency: str = "USD") -> float:
    """Convert an amount into euros.

    Args:
        amount: The amount in the source currency.
        currency: ISO 4217 code of the source currency.
    """
    return round(amount * ctx.deps.fx_rates[currency], 2)


deps = Deps(fx_rates={"USD": 0.86, "GBP": 1.15})

# no API key, no network: the string model above is never contacted
test_model = TestModel()
with agent.override(model=test_model), capture_run_messages() as messages:
    result = agent.run_sync("What is $200 in EUR?", deps=deps)

tool_def = test_model.last_model_request_parameters.function_tools[0]
print("tool sent to the model:")
print(json.dumps({"name": tool_def.name, "description": tool_def.description,
                  "parameters": tool_def.parameters_json_schema}, indent=2))
print("output:", result.output)
print("parts:", [type(p).__name__ for m in messages for p in m.parts])

try:
    agent.run_sync("What is $200 in EUR?", deps=deps)
except RuntimeError as e:
    print("without override:", e)

Output:

tool sent to the model:
{
  "name": "convert",
  "description": "Convert an amount into euros.",
  "parameters": {
    "additionalProperties": false,
    "properties": {
      "amount": {
        "description": "The amount in the source currency.",
        "type": "number"
      },
      "currency": {
        "default": "USD",
        "description": "ISO 4217 code of the source currency.",
        "type": "string"
      }
    },
    "required": [
      "amount"
    ],
    "type": "object"
  }
}
output: {"convert":0.0}
parts: ['UserPromptPart', 'ToolCallPart', 'ToolReturnPart', 'TextPart']
without override: Model requests are not allowed, since ALLOW_MODEL_REQUESTS is False

The Google-style Args: section became per-parameter description fields (Pydantic AI parses docstrings with griffe), the default carried through, ctx stayed out of the schema, and additionalProperties: false is set, which strict tool-schema modes expect. That’s the boilerplate you’d otherwise hand-write for every tool.

The testing pieces worked as documented. agent.override(model=...) swapped the Anthropic model for TestModel without touching the agent definition, and ALLOW_MODEL_REQUESTS = False turned the un-overridden call into a hard error. Set it in conftest.py and a forgotten override fails the test suite before it can run up a bill.

TestModel has a catch, though. It called convert with amount=0.0, because it generates arguments that merely satisfy the schema. That confirms the wiring and says nothing about whether your agent answers “$200 in EUR” correctly. For assertions about behavior, script the model with FunctionModel as in the invoice example, or use the pydantic-evals package against a real model.

Capabilities and hooks: policy outside the tool

V2’s capabilities are where the framework has changed most, so the third test uses the Hooks capability for two jobs that usually leak into tool code: clamping an argument the model sets too high, and keeping an audit trail. The fake model here is stuck in a loop, asking for 500 tickets on every turn and never answering, which is a realistic failure for a weak model on a vague prompt.

import time
from pydantic_ai import Agent, ModelResponse, ToolCallPart, UsageLimits, UsageLimitExceeded
from pydantic_ai.capabilities import Hooks
from pydantic_ai.models.function import FunctionModel, AgentInfo

hooks = Hooks()
audit = []


@hooks.on.before_tool_execute
async def clamp_and_log(ctx, *, call, tool_def, args):
    # policy lives outside the tool: cap page size no matter what the model asks for
    if tool_def.name == "search_tickets" and args.get("limit", 0) > 20:
        args = {**args, "limit": 20}
    audit.append((ctx.run_step, call.tool_name, dict(args)))
    return args


@hooks.on.after_model_request
async def stamp(ctx, *, request_context, response):
    audit.append((ctx.run_step, "model", f"{len(response.parts)} part(s)"))
    return response


def looping_llm(messages, info: AgentInfo) -> ModelResponse:
    # a confused model that keeps asking for more tickets and never answers
    return ModelResponse(parts=[ToolCallPart("search_tickets", {"query": "refund", "limit": 500})])


agent = Agent(FunctionModel(looping_llm), capabilities=[hooks])


@agent.tool_plain
def search_tickets(query: str, limit: int = 10) -> list[str]:
    """Search support tickets."""
    return [f"TICKET-{i}" for i in range(limit)]


t0 = time.perf_counter()
try:
    agent.run_sync("Summarise refund complaints", usage_limits=UsageLimits(request_limit=3))
except UsageLimitExceeded as e:
    print("stopped:", e)
print(f"elapsed: {(time.perf_counter() - t0) * 1000:.1f} ms")
for row in audit:
    print(row)
stopped: The next request would exceed the request_limit of 3. Consider raising the limit, or see the docs on usage limits for budget-aware patterns: https://pydantic.dev/docs/ai/core-concepts/agent/#usage-limits
elapsed: 38.6 ms
(1, 'model', '1 part(s)')
(1, 'search_tickets', {'query': 'refund', 'limit': 20})
(2, 'model', '1 part(s)')
(2, 'search_tickets', {'query': 'refund', 'limit': 20})
(3, 'model', '1 part(s)')
(3, 'search_tickets', {'query': 'refund', 'limit': 20})

The hook rewrote limit from 500 to 20 before the tool ever ran, and the tool itself contains no policy. The usage limit cut the loop off at three model requests with a clear error. Without it, the default request_limit is 50, which on a frontier model with a long context is a real amount of money for a run that produces nothing. UsageLimits also takes token caps and a cost_limit, priced through the bundled genai-prices data. Three full model-tool round trips took about 39 ms of framework time in total, which is small next to a single real model call.

Hooks cover more than tools: there are before_/after_ pairs for runs, graph nodes, model requests, tool validation and output validation, plus wrap_ variants. That’s the extension point the agent guardrails piece was asking for, and here it ships inside the framework itself.

The costs: import time, size and churn

Import time first. I timed cold imports in fresh subprocesses, median of seven runs, with bytecode already cached:

1,120 ms
import pydantic_ai (median)
3,009 ms
import + Agent("anthropic:…")
203,410
lines of Python in pydantic_ai
862
modules loaded by the import

For scale, import pydantic took 60 ms on the same machine and the Anthropic SDK alone took 1,889 ms, so roughly two-thirds of the 3-second figure is the provider SDK. The framework’s own 1.1 s is still the largest fixed cost before your code runs. python -X importtime puts 754 ms of it under pydantic_ai.agent and 421 ms under pydantic_ai.capabilities, which loads every built-in capability eagerly. On a 2-vCPU box like this one, a long-lived FastAPI or worker process pays it once and forgets it. A Lambda or Cloud Run function that scales from zero pays it on every cold start.

Size follows the same pattern. The pydantic_ai package is 10.4 MB of source across 451 files, and the slim install pulled 17 other distributions, including the Pydantic fork httpx2 (the same fork the OpenAI and Anthropic SDKs moved to, covered in the httpx vs aiohttp benchmarks), OpenTelemetry API, logfire-api and griffelib. “Slim” here only means no provider SDKs.

Release pace is the third cost. The GitHub releases API shows 24 releases in July, 24 in August, 18 in September and 15 in October 2026, about three a week, a handful of them v1 backports. Most are additive minors, and the project is careful about deprecation warnings: calling result.usage() the v1 way printed a PydanticAIDeprecationWarning telling me it’s a property now, and the old call still worked. But a fast-moving surface means tutorials and LLM-generated code go stale quickly, and the coding assistant writing your agent may well have learned the v1 API.

The last cost is cosmetic, though it annoys people. The first agent run in a process prints a multi-line Pydantic AI logo to stderr with an advert for Logfire, Pydantic’s paid observability product. It appeared in my sandbox even with stderr piped; the Logfire integration docs say it targets terminals and processes launched by coding agents, and it never shows under pytest, when CI is set, or once instrumentation is configured. Set PYDANTIC_AI_NO_BANNER=1 or pydantic_ai.BANNER_ENABLED = False. Several downstream projects have added code just to turn it off; Apache Airflow’s PR, merged in October, sets the flag at import.

Pros and cons

What I found
Structured outputValidation errors fed back to the model in one structured message; output schema generated from your class
ToolsDocstrings and type hints become a strict JSON schema; typed dependency injection via RunContext
TestingTestModel, FunctionModel, agent.override() and ALLOW_MODEL_REQUESTS all work offline
ExtensibilityHooks and capabilities keep policy, limits and logging out of tool code
Import time1.1 s framework import, ~3 s with the Anthropic SDK, a cold-start problem
Churn~3 releases a week; V2 renamed and moved a lot; three-month quiet window before the next major
DefaultsOne output retry; a 50-request limit; Logfire banner on by default

Who should use Pydantic AI, and who should skip it

Use it if your agent’s output feeds other code. Extraction, classification, routing, form filling, and tool-calling backends where a wrong type is a bug all fit. The validation loop and typed dependencies remove a class of glue code, and the offline test models mean you can put agents under the same CI discipline as the rest of the service. It’s also the natural pick for teams already on FastAPI and Pydantic, since the mental model is identical. Provider coverage is wide (OpenAI, Anthropic, Google, Mistral, Groq, Bedrock, Ollama, vLLM, OpenRouter and many more per the models overview), so you aren’t locked to one lab.

Look elsewhere if your workflow is a long-running, branching state machine that has to survive restarts and human interrupts. Pydantic AI does have pydantic-graph and durable-execution integrations (Temporal, DBOS and Prefect among the nine engines the docs list), but LangGraph’s checkpointed graph is the more established answer there, as the LangGraph vs CrewAI comparison lays out. Also skip it for cold-start-bound serverless functions where 1–3 seconds of imports is the whole latency budget, and for teams that pin a framework version for a year and expect tutorials to keep working.

If you’re mostly wiring an agent to MCP servers, either framework works: Pydantic AI ships an MCP capability and MCPToolset, and the AI agent protocols guide covers where MCP, A2A and AG-UI fit. AG-UI is supported through AGUIAdapter; A2A support moved out of the core package in V2.

Getting started

The library is free and MIT-licensed. Install the slim package with the provider extra you need, so you don’t pull every SDK:

pip install "pydantic-ai-slim[anthropic]"   # or [openai], [google], [mistral], ...
export ANTHROPIC_API_KEY=...
export PYDANTIC_AI_NO_BANNER=1              # optional: silence the first-run banner

You pay for model calls directly, for example through the Anthropic API. Logfire, the observability tool the banner advertises, is optional; per Pydantic’s pricing page its free Personal tier covers 10 million records a month, and Team starts at $49/month. Any OpenTelemetry backend works instead.

FAQ

Is Pydantic AI free?

Yes. The library is MIT-licensed with no paid tier. The costs are your model provider’s API and, optionally, Logfire, which is a separate commercial product with a free tier.

What is Pydantic AI used for?

Building LLM agents in Python whose inputs, tool calls and outputs are validated by Pydantic: structured data extraction, tool-calling assistants, routing and classification services, and multi-step agents that call your own functions with typed dependencies.

Is Pydantic AI better than LangChain or LangGraph?

For typed, single-agent or tool-calling work, I’d pick Pydantic AI: validated output, typed dependencies, and offline test models built into the library. For complex, checkpointed multi-step graphs with human-in-the-loop interrupts, LangGraph is the more mature tool. Pydantic keeps its own comparison page, which is worth reading with its authorship in mind.

Is Pydantic AI production ready?

Within a major version, mostly yes. Minor releases are meant to keep the API compatible, the one deprecated call I hit (result.usage()) warned and kept working, and Thoughtworks placed it in the Trial ring of its Radar in November 2025 (it hasn’t reappeared in the current edition). The production risks are operational: import time on cold starts and the pace of change across majors.

How do I disable the Pydantic AI banner?

Set the environment variable PYDANTIC_AI_NO_BANNER to any value, or set pydantic_ai.BANNER_ENABLED = False in code before the first run. It’s also suppressed automatically under pytest, when CI is set, and once Logfire or another instrumentation is configured.

Sources

Bottom line

Validated output with useful feedback, tool schemas you don’t hand-write, and test models that work without a key are the unglamorous parts of an agent service, and in these offline runs of v2.68 all three behaved as documented. The 1.1-second import, the 200,000 lines and the three-releases-a-week pace are what you pay for them. If your agent runs inside a long-lived Python service and its answers end up in a typed object, I’d start here and revisit only if you need LangGraph-style durable graphs. If it runs in a function that boots from zero on every request, measure the cold start before you commit.