ScriptsMar 28, 2026·2 min read

PydanticAI — Type-Safe AI Agent Framework

Build production-grade AI agents with type safety, structured outputs, and multi-model support. By the creators of Pydantic and FastAPI.

TL;DR
Type-safe AI agent framework by the Pydantic team. Structured outputs, dependency injection, and multi-model support.
§01

What it is

PydanticAI is an agent framework built by the creators of Pydantic and FastAPI. It brings type safety, structured outputs, and dependency injection to AI agent development. Agents return validated Pydantic models instead of raw strings, and the framework handles tool definitions, system prompts, and conversation flow with the same type-driven approach that made Pydantic popular in the Python ecosystem.

The framework targets Python developers building production AI applications who want compile-time guarantees on their agent outputs. It supports multiple LLM providers including Anthropic, OpenAI, and Google.

§02

How it saves time or tokens

PydanticAI's structured outputs eliminate post-processing parsing. When an agent returns a Pydantic model, the output is validated automatically. Failed validations trigger automatic retries with error context, so the LLM corrects its output format without manual intervention. This reduces the token overhead of format correction loops and removes the need for brittle regex parsing of LLM responses.

§03

How to use

  1. Install PydanticAI:
pip install pydantic-ai
  1. Create a simple agent:
from pydantic_ai import Agent

agent = Agent(
    'anthropic:claude-sonnet-4-6',
    instructions='Be concise, reply with one sentence.',
)
result = agent.run_sync('Where does hello world come from?')
print(result.output)
  1. Add structured outputs and tools for production use cases.
§04

Example

Agent with structured output and tool use:

from pydantic import BaseModel
from pydantic_ai import Agent, tool

class CityInfo(BaseModel):
    name: str
    country: str
    population: int
    notable_fact: str

@tool
def search_database(city: str) -> str:
    'Look up city information from the database.'
    return f'{city}: population 8.3M, known for finance'

agent = Agent(
    'anthropic:claude-sonnet-4-6',
    output_type=CityInfo,
    tools=[search_database],
)
result = agent.run_sync('Tell me about New York')
print(result.output.population)  # 8300000 - typed int

The output is a validated Pydantic model with typed fields.

§05

Related on TokRepo

§06

Common pitfalls

  • Structured outputs add token overhead because the model must generate valid JSON. For simple text responses, use string output type instead of Pydantic models.
  • Tool functions must have type annotations and docstrings. PydanticAI uses these to generate the tool schema sent to the LLM.
  • Retry logic for failed validations consumes additional tokens. Set a max_retries limit to prevent runaway costs on consistently malformed outputs.
  • Always check the official documentation for the latest version-specific changes and migration guides before upgrading in production environments.
  • For team deployments, establish clear guidelines on configuration and usage patterns to ensure consistency across developers.

Frequently Asked Questions

What makes PydanticAI different from LangChain?+

PydanticAI focuses on type safety and structured outputs using Pydantic models. LangChain is a broader framework with chains, memory, and retrieval components. PydanticAI is more opinionated about output validation but simpler to use for typed agent responses.

Which LLM providers does PydanticAI support?+

PydanticAI supports Anthropic (Claude), OpenAI (GPT), Google (Gemini), and other providers. You specify the model with a provider prefix like 'anthropic:claude-sonnet-4-6' or 'openai:gpt-4o'.

Can PydanticAI handle streaming responses?+

Yes. PydanticAI supports streaming for both text and structured outputs. For structured outputs, the stream delivers partial results as the model generates the JSON, with final validation on completion.

Is PydanticAI related to FastAPI?+

Yes. PydanticAI is built by the same team behind Pydantic and shares the type-driven philosophy that FastAPI popularized. If you are comfortable with FastAPI's approach to validation and dependency injection, PydanticAI feels familiar.

How does automatic retry work for structured outputs?+

When the LLM returns output that fails Pydantic validation, PydanticAI automatically retries with the validation error message included in the prompt. This gives the model specific feedback about what went wrong, and it usually corrects the format on the next attempt.

Citations (3)
🙏

Source & Thanks

Created by Pydantic. Licensed under MIT. pydantic-ai — ⭐ 15,900+ Docs: ai.pydantic.dev

Thanks to the Pydantic team for bringing type-safe, production-grade tooling to AI agent development.

Discussion

Sign in to join the discussion.
No comments yet. Be the first to share your thoughts.

Related Assets