Skip to content

PydanticAI:新一代 Python Agent 框架

官方文档https://ai.pydantic.dev/GitHub 仓库https://github.com/pydantic/pydantic-ai版本:v0.1.x(2025年最新) 许可证:MIT 主要语言:Python

PydanticAI 官网首页图:PydanticAI 官方网站首页

本章概览

本章将介绍 PydanticAI 的背景、核心价值和设计哲学,帮助你理解:

  • PydanticAI 解决什么问题
  • 为什么 Pydantic 团队要开发这个框架
  • 与现有 Agent 框架(特别是 LangGraph)的定位差异
  • 项目的核心特性和优势

1. 什么是 PydanticAI?

1.1 一句话定义

PydanticAI 是一个 Python Agent 框架,专为快速、自信且轻松地构建生产级生成式 AI 应用而设计。

通俗比喻

如果说 Pydantic 是 Python 数据验证的"瑞士军刀",那么 PydanticAI 就是为 AI Agent 开发打造的同款工具——它继承了 Pydantic 的类型安全、验证严谨的基因,但专门针对 LLM 交互场景进行了优化。

1.2 核心设计理念

PydanticAI 的设计深受 FastAPI 启发,追求相同的开发者体验:

┌─────────────────────────────────────────────────────────────────┐
│                    FastAPI 设计哲学                               │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐  │
│  │  类型提示    │  │  自动验证    │  │  开发者体验优先         │  │
│  │  Type Hints │  │  Validation │  │  Developer Experience  │  │
│  └─────────────┘  └─────────────┘  └─────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘

                    继承并演进到 AI 领域

┌─────────────────────────────────────────────────────────────────┐
│                    PydanticAI 设计哲学                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐  │
│  │  类型安全    │  │  输出验证    │  │  AI 原生开发体验        │  │
│  │  Type-Safe  │  │  Output Val │  │  AI-Native DX          │  │
│  └─────────────┘  └─────────────┘  └─────────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘

1.3 Hello World 示例

最简单的 PydanticAI 程序只需几行代码:

python
from pydantic_ai import Agent

# 创建 Agent,指定模型
agent = Agent(
    'anthropic:claude-sonnet-4-0',
    instructions='Be concise, reply with one sentence.'
)

# 同步运行
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
# 输出: The phrase "Hello, World!" originated from Brian Kernighan's
#       1972 book "A Tutorial Introduction to the Language B."

2. 项目背景

2.1 Pydantic 团队

PydanticAI 由 Pydantic 核心团队开发。Pydantic 是 Python 生态中最广泛使用的数据验证库:

使用场景知名项目
Web 框架FastAPI、Django Ninja
AI 框架LangChain、LlamaIndex、Anthropic SDK
API 服务OpenAI SDK、Google Generative AI
数据处理Pandas、Great Expectations

关键数据

  • 每月下载量:5 亿+
  • GitHub Stars:22,000+
  • 被 OpenAI、Anthropic、Google 等 AI 公司的 SDK 采用

2.2 为什么开发 PydanticAI?

在开发 Pydantic Logfire(他们的可观测性平台)时,团队开始使用 LLM。他们发现:

"当我们在 Pydantic Logfire 中开始使用 LLM 时,我们找不到任何能给我们带来相同感觉的工具——那种 FastAPI 带给 Web 开发的感觉。"

现有框架的痛点

痛点描述
类型安全缺失难以在 IDE 中获得自动补全和类型检查
过度复杂简单任务需要大量样板代码
模型锁定难以在不同 LLM 提供商之间切换
测试困难缺乏系统化的测试和评估框架
可观测性差难以追踪和调试 Agent 行为

PydanticAI 的解决思路

┌──────────────────────────────────────────────────────────────────┐
│                     PydanticAI 核心价值                            │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│  1. 类型安全 ─────────────► IDE 智能提示 + 静态类型检查            │
│                                                                   │
│  2. 模型无关 ─────────────► 支持 20+ 提供商,轻松切换              │
│                                                                   │
│  3. 输出验证 ─────────────► Pydantic 模型保证结构化输出            │
│                                                                   │
│  4. 依赖注入 ─────────────► 类似 FastAPI 的优雅依赖管理            │
│                                                                   │
│  5. 原生可观测 ────────────► Logfire 深度集成                      │
│                                                                   │
│  6. 测试友好 ─────────────► 内置测试模型和评估框架                 │
│                                                                   │
└──────────────────────────────────────────────────────────────────┘

3. 核心特性

3.1 模型无关(Model-Agnostic)

PydanticAI 原生支持 20+ 模型提供商

┌─────────────────────────────────────────────────────────────────┐
│                      PydanticAI Agent                            │
└────────────────────────────┬────────────────────────────────────┘

       ┌─────────────────────┼─────────────────────┐
       ▼                     ▼                     ▼
┌─────────────┐      ┌─────────────┐       ┌─────────────┐
│   OpenAI    │      │  Anthropic  │       │   Gemini    │
│  GPT-4/5    │      │   Claude    │       │   1.5/2.0   │
└─────────────┘      └─────────────┘       └─────────────┘
       ▲                     ▲                     ▲
       │                     │                     │
┌─────────────┐      ┌─────────────┐       ┌─────────────┐
│    Groq     │      │   Mistral   │       │   Cohere    │
└─────────────┘      └─────────────┘       └─────────────┘
       ▲                     ▲                     ▲
       │                     │                     │
┌─────────────┐      ┌─────────────┐       ┌─────────────┐
│   Bedrock   │      │  Ollama     │       │ OpenRouter  │
│   (AWS)     │      │  (本地)      │       │             │
└─────────────┘      └─────────────┘       └─────────────┘

使用方式

python
# 使用 OpenAI
agent = Agent('openai:gpt-4o')

# 使用 Anthropic
agent = Agent('anthropic:claude-sonnet-4-0')

# 使用 Google Gemini
agent = Agent('google-gla:gemini-1.5-pro')

# 使用本地 Ollama
agent = Agent('ollama:llama3.2')

# 使用 AWS Bedrock
agent = Agent('bedrock:us.anthropic.claude-3-5-sonnet-20241022-v2:0')

3.2 类型安全(Type-Safe)

PydanticAI 提供完整的类型提示支持,IDE 可以提供:

  • 自动补全:输入时实时提示可用方法
  • 类型检查:静态分析捕获运行前错误
  • 文档提示:悬停显示参数说明
python
from pydantic import BaseModel
from pydantic_ai import Agent

# 定义结构化输出类型
class CityInfo(BaseModel):
    name: str
    country: str
    population: int
    famous_for: list[str]

# Agent 泛型参数:Agent[DependencyType, OutputType]
agent = Agent(
    'openai:gpt-4o',
    output_type=CityInfo,  # 强制输出必须符合此类型
)

result = agent.run_sync('Tell me about Paris')
# result.output 的类型是 CityInfo,IDE 完全识别
print(result.output.name)        # IDE 知道这是 str
print(result.output.population)  # IDE 知道这是 int

3.3 结构化输出验证

PydanticAI 确保 LLM 输出符合预期的数据结构:

┌─────────────────────────────────────────────────────────────────┐
│                      输出验证流程                                 │
│                                                                  │
│  LLM 响应 ──► JSON 解析 ──► Pydantic 验证 ──► 类型安全的输出      │
│                                │                                 │
│                                ▼                                 │
│                          验证失败?                               │
│                                │                                 │
│                    ┌───────────┴───────────┐                    │
│                    ▼                       ▼                    │
│               自动重试               返回详细错误                │
│          (ModelRetry 机制)        (供调试使用)                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

3.4 依赖注入

类似 FastAPI 的依赖注入系统,让代码更加模块化:

python
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext

# 定义依赖
@dataclass
class SupportDependencies:
    customer_id: int
    db_connection: DatabaseConn

# 创建 Agent 时指定依赖类型
agent = Agent(
    'openai:gpt-4o',
    deps_type=SupportDependencies,
)

# 工具中通过 ctx.deps 访问依赖
@agent.tool
async def get_customer_info(ctx: RunContext[SupportDependencies]) -> str:
    """获取客户信息"""
    customer = await ctx.deps.db_connection.get_customer(
        ctx.deps.customer_id
    )
    return f"Customer: {customer.name}, Balance: {customer.balance}"

3.5 可观测性集成

Pydantic Logfire 深度集成,提供:

python
import logfire
from pydantic_ai import Agent

# 配置 Logfire
logfire.configure()
logfire.instrument_pydantic_ai()

# 正常使用 Agent
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello!')

# 自动追踪:
# - Agent 执行轨迹
# - 每次模型请求详情
# - 工具调用记录
# - Token 使用统计
# - 错误和重试

3.6 评估框架

内置系统化的测试和评估能力:

python
import pytest
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel

# 使用 TestModel 避免真实 API 调用
@pytest.fixture
def test_agent():
    return Agent(
        TestModel(),  # 测试模型,自动生成符合 schema 的响应
        output_type=MyOutput,
    )

def test_agent_response(test_agent):
    result = test_agent.run_sync('test prompt')
    assert isinstance(result.output, MyOutput)

4. 十大核心能力

PydanticAI 官方强调的十大核心能力:

#能力描述
1Pydantic 基因继承 Pydantic 的类型安全和验证能力
2模型无关支持 20+ 提供商,统一 API 接口
3可观测性Logfire 原生集成,OpenTelemetry 标准
4类型安全完整的 IDE 支持和静态类型检查
5评估框架内置测试和性能监控工具
6MCP 支持Model Context Protocol 集成
7Human-in-the-Loop工具审批和条件逻辑支持
8持久执行处理 API 故障和长时间运行的工作流
9流式输出持续生成结构化数据并验证
10图支持基于类型提示的复杂工作流定义

5. 定位与生态

5.1 与 LangChain/LangGraph 的定位差异

作为 LangChain 首席科学家,我认为 PydanticAI 与 LangGraph 有着不同的定位:

┌─────────────────────────────────────────────────────────────────┐
│                       框架定位对比                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   PydanticAI                          LangGraph                  │
│   ─────────                           ─────────                  │
│   "FastAPI for AI"                    "State Machine for AI"     │
│                                                                  │
│   ┌─────────────────┐                ┌─────────────────┐        │
│   │ 简洁优雅        │                │ 精确控制         │        │
│   │ 类型安全优先    │                │ 状态管理优先     │        │
│   │ 快速开发        │                │ 复杂编排         │        │
│   │ 验证驱动        │                │ 图驱动           │        │
│   └─────────────────┘                └─────────────────┘        │
│                                                                  │
│   适用场景:                          适用场景:                  │
│   • 快速原型                          • 复杂多 Agent 系统        │
│   • 类型敏感应用                      • 需要精确状态控制         │
│   • 结构化输出                        • 高度自定义流程           │
│   • API 服务集成                      • 企业级编排               │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

5.2 有趣的事实

一个有趣的事实是:LangChain 本身就使用 Pydantic 作为核心依赖

LangChain 技术栈

       ├── Pydantic(数据验证)  ◄─── PydanticAI 的基础
       ├── LangGraph(编排)
       └── LangSmith(可观测)

这意味着 PydanticAI 和 LangGraph 并不是竞争关系,而是可以互补的工具。


6. 安装与快速开始

6.1 安装

bash
# 标准安装
pip install pydantic-ai

# 或使用 uv(更快)
uv add pydantic-ai

# 精简安装(仅特定模型)
pip install "pydantic-ai-slim[openai]"

# 带可观测性
pip install "pydantic-ai-slim[openai,logfire]"

要求:Python 3.10+

6.2 配置 API 密钥

bash
# OpenAI
export OPENAI_API_KEY="sk-..."

# Anthropic
export ANTHROPIC_API_KEY="sk-ant-..."

# Google
export GOOGLE_API_KEY="..."

6.3 第一个 Agent

python
from pydantic_ai import Agent

# 创建最简单的 Agent
agent = Agent('openai:gpt-4o')

# 运行
result = agent.run_sync('What is the capital of France?')
print(result.output)  # Paris

7. 阅读指南

为了更好地理解 PydanticAI,建议按以下顺序阅读本章:

顺序章节内容
1architecture.md架构设计与核心组件
2core-concepts.mdAgent、Tools、Dependencies 详解
3comparison.md与 LangGraph 深度对比
4integration.md两个框架的协同集成
5practice.md实战案例与最佳实践
6conclusion.md总结、选型建议与展望

8. 小结

PydanticAI 是一个令人兴奋的新框架,它将 Pydantic 的类型安全和验证能力带入了 AI Agent 开发领域。虽然它还很年轻,但其设计理念和开发体验都非常出色。

核心优势

  • 继承 Pydantic 的成熟验证体系
  • FastAPI 风格的开发者体验
  • 强大的类型安全支持
  • 优雅的依赖注入
  • 原生可观测性集成

需要关注

  • 相比 LangGraph,复杂编排能力还在发展中
  • 社区和生态还在建设
  • 文档和示例相对较少

在接下来的章节中,我们将深入探讨 PydanticAI 的架构设计、核心概念,并与 LangGraph 进行详细对比。


下一章:架构设计

基于 MIT 许可证发布。内容版权归作者所有。