Open SourcePython

PydanticAI

by PydanticUpdated Jun 15, 2025

Type-safe agent framework built by the creators of Pydantic. PydanticAI leverages Python's type system for structured agent outputs, dependency injection, and model-agnostic design. It brings the reliability and developer experience of Pydantic validation to the world of AI agents, ensuring outputs conform to defined schemas.

Architecture Overview

PydanticAI centers around an Agent class parameterized by a dependency type and a result type. The agent uses a system prompt (which can be dynamic via decorators), tools (registered via decorators with dependency injection), and a model. When run, it enters a loop where the model generates responses validated against the result type using Pydantic. Dependencies are injected into tools at runtime via a RunContext, enabling clean separation of concerns and testability.

When to Use PydanticAI

  • Type-safe agent outputs with guaranteed schema compliance
  • Structured data extraction from unstructured text
  • API-driven agents that need validated responses
  • Applications requiring dependency injection and testability
  • Production agents where output reliability is critical

Strengths & Weaknesses

Strengths

  • Pydantic-powered validation ensures type-safe outputs
  • Clean dependency injection via RunContext
  • Model-agnostic: supports OpenAI, Anthropic, Gemini, and more
  • Excellent developer experience with IDE autocomplete
  • Lightweight with minimal dependencies

Weaknesses

  • Newer framework with a smaller ecosystem
  • No built-in multi-agent orchestration
  • Focused on single-agent patterns (use LangGraph for complex workflows)

Quick Start

python
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext

# Define dependencies (injected at runtime)
@dataclass
class WeatherDeps:
    api_key: str
    units: str = "celsius"

agent = Agent(
    "openai:gpt-4o",
    deps_type=WeatherDeps,
    system_prompt="You are a helpful weather assistant.",
)

@agent.tool
def get_weather(ctx: RunContext[WeatherDeps], city: str) -> str:
    """Get the current weather for a city."""
    # ctx.deps gives access to injected dependencies
    return f"72°F in {city} (using key: {ctx.deps.api_key[:8]}...)"

# Run with injected dependencies
result = agent.run_sync(
    "What's the weather in Tokyo?",
    deps=WeatherDeps(api_key="wk-abc123def456"),
)
print(result.data)

Features at a Glance

DeveloperPydantic
LanguagePython
LicenseMIT
GitHub Stars6k+
MCP SupportYes
Multi-AgentNo

Notable Users

PydanticFastAPI communityLogfireRobusta

Resources

Explore Related Content