Pydantic · Type-Safe Agents · Python 3.10+

Pydantic AI Agent 框架实战

Pydantic 团队为 LLM 时代写的 Agent 框架。用类型当契约——输入结构用 Pydantic、输出结构用 Pydantic、工具签名用 Pydantic、依赖注入像 FastAPI,Agent 不再是魔法黑盒,而是一段能被 IDE 补全、mypy 校验、pytest 断言的 Python 代码。

Agent Structured Output Tool Dependency Injection Graph Logfire Provider-Agnostic
10 章 · 深度讲透 从类型到生产级 Agent Python 原生 · Provider 中立

为什么用 Pydantic AI

LLM Agent 不必是魔法黑盒,它可以是一段能被 IDE 补全、mypy 校验、pytest 断言的 Python 代码

LangChain 把"调用 LLM"写成拼乐高,灵活但难调试;OpenAI Agents SDK 强但只绑一家;LangGraph 强在状态机但上手重。Pydantic AI 走第三条路——用 Pydantic 的类型系统当 Agent 的骨架,provider 无关、结构化输出是一等公民、依赖注入直接像 FastAPI 一样写,再配上可调试的 Graph 和原生的 Logfire 观测。

对已经用 FastAPI 写过后端的 Python 工程师,0 认知负担。这 10 章把它从 Agent("gpt-4o") 一直讲到多 Agent 图 + 生产观测,每章都配代码、坑位和对比。

课程大纲

10 章 · 从 Agent 基础到生产观测

Chapter 01 Pydantic AI 是什么 · 为何是它 Pydantic 团队的 AI 野心 · 类型即契约 · 与 LangChain/OpenAI Agents/LangGraph 的定位差异 · Hello World 与"我到底在写什么"
type-safeagentprovider-agnostic
Chapter 02 Agent 基础 · system prompt 与 provider 切换 Agent 构造参数全解 · system prompt 静态 vs 动态 · 模型字符串约定 · OpenAI/Anthropic/Gemini/Groq/Ollama 一键切换 · 同步/异步/流式三条 API
Agentsystem_promptrun/arun/stream
Chapter 03 Structured Output · 类型即输出契约 output_type 的魔法 · Pydantic BaseModel 作为 Agent 返回值 · Union / TypedDict / dataclass 支持 · 验证失败的自动重试 · 和 function calling 的关系
output_typeBaseModelretry
Chapter 04 Tool · 让 Agent 接入真实世界 @agent.tool 装饰器 · 从 Python 函数签名自动推参数 schema · RunContext 上下文 · 同步工具 vs 异步工具 · 多工具并行 · ModelRetry 主动要求重试
toolRunContextModelRetry
Chapter 05 Dependency Injection · 像 FastAPI 一样写 Agent deps_type 的作用 · 把 DB 连接/API client/配置注入到每个 tool · 测试时替换依赖 · 和 FastAPI Depends 的对比 · 真实订单查询 Agent 示例
DIdeps_typetestable
Chapter 06 流式与消息历史 run_stream 的两种流:文本增量 / 结构化增量 · stream_text / stream_structured · messages 管理历史 · message_history 参数接上次对话 · 多轮对话模式
streammessage_historyconversation
Chapter 07 Graph · 复杂 Agent 的状态机骨架 pydantic_graph 内置 · BaseNode / Edge / End · 节点即类型 · Graph.run 驱动 · 持久化 checkpoint · 和 LangGraph 的同异 · 实战:客服分流 Agent
graphstate-machinecheckpoint
Chapter 08 多 Agent 协作 · Agent 调用 Agent Agent 本身就是工具 · programmatic handoff · 子 Agent 专门化(搜索/写作/校对) · 共享 usage 统计 · delegate pattern · 控制每一跳的成本
multi-agenthandoffdelegate
Chapter 09 测试与 Eval · 把 Agent 当代码测 TestModel / FunctionModel 零 API 调用 mock · Agent.override 替换 · capture_run_messages 断言工具调用顺序 · pytest 集成 · 金标 eval 集 · Logfire 评分
TestModelpytesteval
Chapter 10 Logfire 观测与生产部署 instrument_all 一行接入 · trace/span 自动打点 · 成本/token 追踪 · FastAPI 集成模板 · 超时/限流/错误分类 · Docker 部署 · 上线 checklist
LogfireFastAPIproduction