大模型应用
用 Pydantic AI 构建生产级 AI…
当需要用 Python 构建 LLM 驱动的 AI Agent(含工具调用、结构化输出、能力组合、流式、测试、多智能体)时,按此做法落地。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 49/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 85/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
用 Pydantic AI 构建生产级 通用
解决思路
- 创建基础 Agent:用 `Agent('provider:model-name', instructions='...')` 构造,调用 `agent.run_sync('...')` 获取结果,读取 `result.output`。
- 添加工具:用 `@agent.tool_plain` 定义无依赖工具(无 `RunContext` 参数),用 `@agent.tool` 定义需要依赖的工具(第一个参数必须是 `RunContext[deps_type]`),通过 `deps_type` 声明依赖类型并在 `run_sync(..., deps=...)` 传入。
- 结构化输出:定义 Pydantic `BaseModel` 作为 `output_type`,例如 `Agent('google:gemini-3-flash-preview', output_type=CityLocation)`,结果从 `result.output` 取,用量从 `result.usage` 取。
- 依赖注入与动态指令:用 `@agent.instructions` 装饰函数,通过 `RunContext` 读取 `ctx.deps` 动态生成指令(如注入用户名、当前日期)。
- 测试:用 `pydantic_ai.models.test.TestModel` 配合 `with my_agent.override(model=m):` 上下文管理器做确定性单测,断言 `result.output` 与 `m.last_model_request_parameters.function_tools`;自定义逻辑用 `FunctionModel`。
- 使用能力(Capabilities):在 `Agent(..., capabilities=[...])` 中组合可复用行为,如 `Thinking(effort='high')`、`WebSearch()`,能力可打包工具、钩子、指令与模型设置。
- 添加生命周期钩子:用 `Hooks()` 并通过 `@hooks.on.before_model_request` 等装饰器拦截模型请求、工具调用与运行,无需继承子类;将 `hooks` 放入 `capabilities`。
- 从 YAML/JSON 定义 Agent:用 `Agent.from_file('agent.yaml')` 加载,YAML 中可声明 `model`、`instructions`、`capabilities`(如 `WebSearch`、`Thinking: {effort: high}`),无需写 Python 构造代码。
- 按任务路由加载参考文档:先只加载最相关的一个 reference(如 Agents Core、Capabilities and Hooks、On-Demand Capabilities、Tools Core、Native Tools、Tools Advanced、Input and History、Testing and Debugging、Orchestration and Integrations),任务跨多领域时再读其他。
- 架构与选型:在需要比较抽象、输出模式、装饰器、模型字符串格式或决策树时,加载 Architecture and Decision Guide。
- 模型字符串格式:使用 `"provider:model-name"`,例如 `"openai:gpt-5.2"`、`"anthropic:claude-sonnet-4-6"`、`"google:gemini-3-pro-preview"`。
- 关键 Agent 方法:`run()`、`run_sync()`、`run_stream()`、`run_stream_sync()`、`run_stream_events()`、`iter()`。
- 默认渐进式披露:对每个能力先显式评估 `defer_loading=True` 是否更优,不要急切加载专家指令、罕用工具 schema 或领域上下文;命名指令+工具包用按需能力,大型扁平工具目录用工具搜索。
- 可观测性:用 `logfire.instrument_pydantic_ai()` 追踪 Agent 运行、工具调用与模型请求;需要 HTTP 级细节时用 `logfire.instrument_httpx(capture_all=True)` 捕获发给模型提供方的完整载荷。
- 避免常见错误:`@agent.tool` 必须有 `RunContext` 首参而 `@agent.tool_plain` 必须没有;模型字符串必须带 provider 前缀;`TestModel` 必须用 `agent.override()` 而非直接改 `agent.model`;`output_type` 联合类型中不要包含 `str`(否则模型可返回纯文本结束运行);`.on` 上的钩子装饰器名不重复 `on_`(用 `hooks.on.run_error`、`hooks.on.model_request_error`);`history_processors` 已弃用,改用 `capabilities=[ProcessHistory(p), ...]` 或 `capabilities=[Hooks(before_model_request=fn)]`。
适用边界 · 注意事项
- 仅使用 Pydantic 校验库(`pydantic`/`BaseModel`)而不涉及 Agent 时。
- 使用其他 AI 框架(LangChain、LlamaIndex、CrewAI、AutoGen)时。
- 与 AI Agent 无关的通用 Python 开发。