主要内容
Pydantic AI 由 Pydantic 核心团队出品,目标是把 Pydantic 在数据验证领域的严谨性带到 agent 世界。工具定义、参数、返回值、agent 输出全部 Pydantic 模型化。RunContext 是核心抽象,用依赖注入传递 per-request 的用户 ID、数据库连接、API client,避免全局状态污染。和 FastAPI 的心智模型几乎一致,如果你团队已经在用 Pydantic 和 FastAPI,学习成本接近零。Logfire 集成内置,tracing 和 observability 开箱即用。
核心关注点
别让 LLM 的不确定性污染你的 Python 类型系统。output_type 是契约,违反契约即报错。
安装与 hello world
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
class Invoice(BaseModel):
vendor: str
total: float = Field(gt=0)
currency: str = Field(pattern=r"^[A-Z]{3}$")
line_items: list[str]
@dataclass
class Deps:
db_session: object
user_id: str
agent = Agent(
"openai:gpt-4o",
deps_type=Deps,
output_type=Invoice,
system_prompt="从发票文本中提取结构化信息。",
)
@agent.tool
def lookup_vendor(ctx: RunContext[Deps], name: str) -> dict:
return ctx.deps.db_session.query(name)
result = agent.run_sync(
"从这张发票里提取字段: ...",
deps=Deps(db_session=session, user_id="u1"),
)
print(result.output.total)关键 API / 概念
Agent(model, output_type=, deps_type=)output_type 是 Pydantic 模型,agent 强制产出该类型;deps_type 启用依赖注入。
RunContext[Deps]tool 函数第一参数,通过 ctx.deps 拿到 per-request 依赖。
@agent.tool / @agent.tool_plain前者可拿 ctx,后者无 ctx。工具定义即 Pydantic 校验参数。
Logfire 集成import logfire; logfire.configure() 一行接入生产级 observability。
适用场景
结构化数据抽取
发票、合同、医疗报告、科研论文,输出是严格的 Pydantic 模型,直接塞进数据库。
企业 Python 应用
Python 技术栈成熟、team 已经在用 Pydantic / FastAPI / SQLModel 的项目,无缝集成。
合规 / 审计敏感场景
金融风控、医疗诊断前置、法律文档分析,每一步输出可验证、可追溯。
什么时候别用
- 多 agent 复杂编排:Pydantic AI 是 agent 层,不是 orchestration 层
- 非 Python 项目:只有 Python 版本
vs 相邻选项
vs LangGraph
Pydantic AI 是单 agent 层,LangGraph 是 orchestration 层,可以组合使用。
vs OpenAI Agents SDK
Pydantic AI 强调结构化输出契约,OpenAI SDK 更关注 handoff 拓扑。