Files
myWiki/concepts/pydantic-ai.md

1.9 KiB
Raw Blame History

title, created, updated, type, tags, sources
title created updated type tags sources
Pydantic AI 2026-06-10 2026-06-10 concept
pydantic
agent
type-safety
structured-output
raw/articles/pydantic-three-piece-suite-2026.md

Pydantic AI

pydantic 的类型系统直接嵌入 Agent 运行时的框架。类型不只是校验输出——类型定义了 Agent 能做什么、怎么做、产出什么。

核心定位

Pydantic AI 不是 LangChain 的竞品——LangChain 用链式调用组织工作流Pydantic AI 用类型系统约束 Agent 的工具选择和输出格式

也不是 Instructor 的竞品——Instructor 解决单次 LLM 结构化输出Pydantic AI 把这件事内置到多步 Agent 框架里。

关键能力

  • @agent.tool:从函数签名和返回类型自动推断 tool schema——无需手写 JSON Schema
  • result.data类型安全IDE 补全可用,不需要手动 model_validate
  • 多步 Agent:支持多次推理 + 多次 tool 调用
  • instrument=True:自动接 logfire trace全链路可观测
  • 事前约束:类型的角色从"报错器"变为"编译器"——在运行时之前就约束了行为空间

vs Instructor

能力 Instructor Pydantic AI
LLM → Pydantic 对象
Tool 调用自动 schema
多步 Agent
全链路 trace

规则:单次 LLM 结构化输出 → Instructor。多步推理 + 多 tool 调用的 Agent → Pydantic AI。

示例

agent = Agent('openai:gpt-4o', result_type=OutfitSuggestion, instrument=True)

@agent.tool
async def get_weather(city: str) -> WeatherInfo: ...

result = await agent.run("深圳今天穿什么")
# result.data 类型安全IDE 补全可用

参考