mcpField
B
building-pydantic-ai-agents

building-pydantic-ai-agents

github.com/clineAgent 工作流391.9k 次安装15 周前更新
代码仓库

关于 building-pydantic-ai-agents

面向使用 Pydantic AI 构建 AI Agent 和大模型应用的开发者,提供模式指导与经过测试的示例,涵盖 Agent 配置、工具、测试和编排。

主要功能

  1. 01Agent 创建与配置
  2. 02工具和可复用能力
  3. 03结构化输出与依赖注入
  4. 04YAML 和 JSON Agent 规格
  5. 05流式处理与多 Agent 工作流
  6. 06测试与生命周期钩子

适用场景

  1. 01使用 Pydantic AI 创建 Agent
  2. 02为 Agent 添加工具或结构化输出
  3. 03测试和调试 Agent 行为

MCP 相关

该 skill 提供将 MCP 服务作为工具添加到 Pydantic AI Agent 的指导。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/cline/skills --skill building-pydantic-ai-agents

安装后在 Claude Code 中输入/building-pydantic-ai-agents确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
AGENTS-CORE.md
ARCHITECTURE.md
CAPABILITIES-AND-HOOKS.md
COMMON-TASKS.md
INPUT-AND-HISTORY.md
NATIVE-TOOLS.md
ON-DEMAND-CAPABILITIES.md
ORCHESTRATION-AND-INTEGRATIONS.md
TESTING-AND-DEBUGGING.md
TOOLS-ADVANCED.md
TOOLS-CORE.md

详细介绍

使用 Pydantic AI 构建 AI Agent

Pydantic AI 是一个 Python Agent 框架,用于构建可用于生产环境的生成式 AI 应用。 本技能提供使用 Pydantic AI 构建应用的模式、架构指导和经过测试的代码示例。

何时使用此技能

在以下情况下调用此技能:

  • 用户要求构建 AI Agent、创建由大模型驱动的应用,或提及 Pydantic AI
  • 用户希望为 Agent 添加工具、能力(思考、网页搜索)或结构化输出
  • 用户要求根据 YAML/JSON 规范定义 Agent,或使用模板字符串
  • 用户希望流式传输 Agent 事件、在 Agent 之间委派任务,或测试 Agent 行为
  • 代码导入 pydantic_ai,或引用 Pydantic AI 类(Agent、RunContext、Tool)
  • 用户询问有关钩子、生命周期拦截或使用 Logfire 进行 Agent 可观测性的问题
  • Agent 设计包含可选指令、专业工作流、长尾工具,或模型在大多数轮次中不需要的任何上下文

请勿在以下情况下使用此技能:

  • 仅使用 Pydantic 验证库(没有 Agent 的 pydantic/BaseModel)
  • 使用其他 AI 框架(LangChain、LlamaIndex、CrewAI、AutoGen)
  • 与 AI Agent 无关的常规 Python 开发

快速入门模式

创建基本 Agent
from pydantic_ai import Agent

agent = Agent(
    'anthropic:claude-sonnet-4-6',
    instructions='Be concise, reply with one sentence.',
)

result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""
为 Agent 添加工具
import random

from pydantic_ai import Agent, RunContext

agent = Agent(
    'google:gemini-3-flash-preview',
    deps_type=str,
    instructions=(
        "You're a dice game, you should roll the die and see if the number "
        "you get back matches the user's guess. If so, tell them they're a winner. "
        "Use the player's name in the response."
    ),
)


@agent.tool_plain
def roll_dice() -> str:
    """Roll a six-sided die and return the result."""
    return str(random.randint(1, 6))


@agent.tool
def get_player_name(ctx: RunContext[str]) -> str:
    """Get the player's name."""
    return ctx.deps


dice_result = agent.run_sync('My guess is 4', deps='Anne')
print(dice_result.output)
#> Congratulations Anne, you guessed correctly! You're a winner!
使用 Pydantic 模型生成结构化输出
from pydantic import BaseModel

from pydantic_ai import Agent


class CityLocation(BaseModel):
    city: str
    country: str


agent = Agent('google:gemini-3-flash-preview', output_type=CityLocation)
result = agent.run_sync('Where were the olympics held in 2012?')
print(result.output)
#> city='London' country='United Kingdom'
print(result.usage)
#> RunUsage(input_tokens=57, output_tokens=8, requests=1)
依赖注入
from datetime import date

from pydantic_ai import Agent, RunContext

agent = Agent(
    'openai:gpt-5.2',
    deps_type=str,
    instructions="Use the customer's name while replying to them.",
)


@agent.instructions
def add_the_users_name(ctx: RunContext[str]) -> str:
    return f"The user's name is {ctx.deps}."


@agent.instructions
def add_the_date() -> str:
    return f'The date is {date.today()}.'


result = agent.run_sync('What is the date?', deps='Frank')
print(result.output)
#> Hello Frank, the date today is 2032-01-02.
使用 TestModel 进行测试
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel

my_agent = Agent('openai:gpt-5.2', instructions='...')


async def test_my_agent():
    """Unit test for my_agent, to be run by pytest."""
    m = TestModel()
    with my_agent.override(model=m):
        result = await my_agent.run('Testing my agent...')
        assert result.output == 'success (no tool calls)'
    assert m.last_model_request_parameters.function_tools == []
使用能力

能力是可复用、可组合的 Agent 行为单元,可将工具、钩子、指令和模型设置打包在一起。

from pydantic_ai import Agent
from pydantic_ai.capabilities import Thinking, WebSearch

agent = Agent(
    'anthropic:claude-opus-4-6',
    instructions='You are a research assistant. Be thorough and cite sources.',
    capabilities=[
        Thinking(effort='high'),
        WebSearch(),
    ],
)
添加生命周期钩子

使用 Hooks 和装饰器拦截模型请求、工具调用和运行过程,无需子类化。

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities.hooks import Hooks
from pydantic_ai.models import ModelRequestContext

hooks = Hooks()


@hooks.on.before_model_request
async def log_request(ctx: RunContext[None], request_context: ModelRequestContext) -> ModelRequestContext:
    print(f'Sending {len(request_context.messages)} messages')
    return request_context


agent = Agent('openai:gpt-5.2', capabilities=[hooks])
根据 YAML 规范定义 Agent

使用 Agent.from_file 从 YAML 或 JSON 加载 Agent,无需编写 Python Agent 构造代码。

from pydantic_ai import Agent

# agent.yaml:
# model: anthropic:claude-opus-4-6
# instructions: You are a helpful research assistant.
# capabilities:
#   - WebSearch
#   - Thinking:
#       effort: high

agent = Agent.from_file('agent.yaml')

任务路由表

首先只加载最相关的参考文档。只有当任务涉及多个领域时,才阅读其他参考文档。

我想要……参考文档
创建/配置 Agent、选择输出类型、使用依赖项、定义规范或选择运行方法Agents Core
打包可复用行为或拦截生命周期事件Capabilities and Hooks
决定哪些内容应提前加载、哪些应按需加载,应用渐进式披露、延迟加载能力,或解释 load_capabilityCapabilities on Demand
添加函数工具、工具集、MCP 服务或显式搜索工具Tools Core
使用提供商原生的网页搜索、网页抓取或代码执行功能Native Tools
使用高级工具功能,例如审批、重试、ToolReturn、验证器、超时或工具搜索Tools Advanced
处理多模态输入、消息历史记录或上下文裁剪Input and History
测试或调试 Agent 行为Testing and Debugging
协调多个 Agent 或构建图工作流Orchestration and Integrations
直接调用模型、公开 A2A、使用持久化执行、嵌入、评估或第三方集成Orchestration and Integrations
比较抽象、输出模式、装饰器或模型字符串模式Architecture and Decision Guide
根据旧链接查阅 COMMON-TASKS.mdTask Reference Map

架构与决策

仅当用户需要在不同抽象之间进行选择,或需要比较表和决策树时,才加载 架构与决策指南:

主题涵盖内容
决策树工具注册、输出模式、多 Agent 模式、能力、测试方法、可扩展性
比较表输出模式、模型提供商前缀、工具装饰器、内置能力、Agent 方法
架构概览执行流程、泛型、构造模式、生命周期钩子、模型字符串格式

快速参考 — 模型字符串格式: "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()

关键实践

  • 必须兼容 Python 3.10+
  • 默认采用渐进式披露:对于每项能力,在选择主动加载之前,都应明确考虑 defer_loading=True 是否有益于 Agent。除非模型在大多数轮次中都需要,否则不要主动加载专业指令、很少使用的工具架构或领域上下文。对于命名的指令与工具组合,优先按需启用能力;对于大型扁平工具目录,则使用工具搜索。
  • 可观测性:Pydantic AI 原生集成了 Logfire,可跟踪 Agent 运行、工具调用和模型请求。使用 logfire.instrument_pydantic_ai() 添加集成。如需更深入地查看 HTTP 层信息,logfire.instrument_httpx(capture_all=True) 可以捕获发送给模型提供商的确切负载。
  • 测试:使用 TestModel 进行确定性测试,使用 FunctionModel 实现自定义逻辑

常见陷阱

以下是 Agent 使用 Pydantic AI 时常犯的错误。犯下这些错误会导致静默故障或令人困惑的报错。

  • @agent.tool 要求将 RunContext 作为第一个参数;@agent.tool_plain 则不能包含该参数。混淆两者会导致运行时错误。不需要 deps、usage 或 messages 时,请使用 tool_plain。
  • 模型字符串必须包含提供商前缀:使用 'openai:gpt-5.2',而不是 'gpt-5.2'。缺少前缀时,Pydantic AI 无法解析提供商。
  • TestModel 必须与 agent.override() 配合使用:不要直接设置 agent.model。务必使用上下文管理器:with agent.override(model=TestModel()):。
  • 在 output_type 中加入 str 允许以纯文本结束运行:如果联合类型包含 str(或未设置 output_type),模型可以返回纯文本,而不是结构化输出。要强制使用基于工具的输出,请从联合类型中省略 str。
  • .on 上的钩子装饰器名称不重复包含 on_:使用 hooks.on.run_error 和 hooks.on.model_request_error,而不是 hooks.on.on_run_error。
  • history_processors 已弃用;请改用 capabilities=[ProcessHistory(p), ...],或直接通过 capabilities=[Hooks(before_model_request=fn)] 挂接 before_model_request。ProcessHistory 是该钩子的轻量封装;钩子本身才是底层原语。该关键字参数在 1.x 中仍然可用,但会发出 PydanticAIDeprecationWarning,并将在 v2 中移除。

任务类别参考

除非任务明确涵盖多个类别,否则只加载以下其中一项:

任务类别参考资料
核心 Agent 设置、输出、依赖项、规范、模型、运行方式Agents Core
功能、钩子和可复用行为Capabilities and Hooks
渐进式披露、延迟加载的功能、按需加载功能和 load_capability 语义Capabilities on Demand
函数工具、工具集、MCP、显式搜索工具Tools Core
提供商原生工具Native Tools
审批、重试、验证器、超时、丰富的工具返回、工具搜索和工具级延迟加载Tools Advanced
多模态输入、消息历史、历史处理器Input and History
测试、请求检查和 Logfire 调试Testing and Debugging
多 Agent 模式、图、直接 API、A2A、持久执行、嵌入、评估、第三方集成Orchestration and Integrations

仅在需要兼容旧链接,或需要根据旧章节名称查找新文件时,使用 Task Reference Map。

评论

支持 Markdown