Doramagic 项目包 · 项目说明书

pydantic-ai 项目

生成时间:2026-05-28 14:07:00 UTC

PydanticAI 概述

PydanticAI 是一个开源的提供商无关(Provider-agnostic)GenAI 智能体框架,同时也是一个通用的 LLM 库,专为 Python 设计。该项目由 Pydantic Validation 和 Pydantic Logfire 背后的团队维护 资料来源:[README.md:1]()。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 强原语与强大抽象

继续阅读本节完整说明和来源证据。

章节 类型安全优先

继续阅读本节完整说明和来源证据。

章节 pydantic-ai-slim 架构

继续阅读本节完整说明和来源证据。

项目简介

PydanticAI 是一个开源的提供商无关(Provider-agnostic)GenAI 智能体框架,同时也是一个通用的 LLM 库,专为 Python 设计。该项目由 Pydantic ValidationPydantic Logfire 背后的团队维护 资料来源:README.md:1

PydanticAI 的设计理念是成为一个轻量级库,任何想要使用 LLM 和智能体(无论简单还是复杂)的 Python 开发者都应该毫不犹豫地将其引入项目。它不是要成为一个面面俱到的框架,而是要赋能开发者构建几乎任何应用 资料来源:CLAUDE.md:47-49

核心设计哲学

强原语与强大抽象

PydanticAI 倾向于使用强大的原语、强大的抽象和通用解决方案,这些方案提供了扩展点,使人们能够构建我们甚至未曾想到的东西。这比以下方案更为可取:

  • 针对特定用例的窄化解决方案
  • 推动未经时间验证的智能体设计方法的固执己见的解决方案
  • "包含所有电池"式的解决方案,使库变得不必要地臃肿

资料来源:CLAUDE.md:49-55

类型安全优先

所有代码变更都需要:

  • 完全类型安全(内部和公共 API),避免不必要的 castAny
  • 向后兼容,遵循版本策略
  • 现代、地道的 Python 代码风格

资料来源:CLAUDE.md:58-63

仓库结构

PydanticAI 仓库使用 uv 工作空间定义了多个 Python 包:

包名路径说明
pydantic-ai-slimpydantic_ai_slim/核心智能体框架,包含 Agent 类和各模型提供商的 Model
pydantic-graphpydantic_graph/基于类型提示的图库,为智能体循环提供动力
pydantic-evalspydantic_evals/评估框架,用于评估包括 LLM 和智能体在内的任意随机函数
claiclai/CLI 工具(带有可选的 Web UI)

资料来源:CLAUDE.md:73-79

pydantic-ai-slim 架构

pydantic-ai-slim 是一个精简包,具有最小依赖项,为每个模型提供商提供可选依赖组:

graph TD
    subgraph "pydantic-ai-slim 可选依赖组"
        OpenAI["openai"]
        Anthropic["anthropic"]
        Google["google"]
        Logfire["logfire"]
        MCP["mcp"]
        Temporal["temporal"]
    end
    
    subgraph "核心模块"
        Agent["Agent 类"]
        Model["Model 类"]
        Tools["Tools 工具"]
        Output["Output 输出"]
    end
    
    Agent --> Model
    Agent --> Tools
    Agent --> Output

这种模块化设计确保用户只需安装其实际使用的提供商依赖。

核心概念与组件

Agent(智能体)

Agent 是 PydanticAI 的核心类,负责管理 LLM 对话循环。开发者通过定义 Agent 并配置其使用的模型、工具和提示来构建 AI 应用。

Agent 支持的关键功能包括:

  • 工具调用(Tools):允许 LLM 调用自定义函数
  • 结构化输出(Structured Output):基于 Pydantic 模型生成类型安全的输出
  • 依赖注入(Dependency Injection):在运行时动态注入依赖
  • 消息历史(Message History):管理对话上下文

Model(模型)

PydanticAI 提供对多种 LLM 提供商的支持,包括:

  • OpenAI 系列模型
  • Anthropic Claude 系列模型
  • Google Gemini 系列模型
  • 其他提供商(可通过自定义 URL 和 API 密钥配置)

资料来源:pydantic_ai_slim/pydantic_ai/profiles/anthropic.py:1-30

每个模型都有对应的模型配置(Model Profile),定义了该模型支持的功能特性:

配置项说明支持的模型示例
supports_thinking是否支持思维链Claude Haiku, Sonnet, Opus
supports_tool_search是否支持工具搜索Claude 3.5+ 系列
supports_json_schema_output是否支持 JSON Schema 输出部分 Claude 模型
supports_effort是否支持 effort 参数Claude 3.7+
supports_code_execution是否支持代码执行Claude 3.5+

资料来源:pydantic_ai_slim/pydantic_ai/profiles/anthropic.py:80-100

Tools(工具)

Tools 允许 LLM 调用预定义的函数来执行特定任务。PydanticAI 支持两种主要工具类型:

  1. FunctionToolset:函数工具集,用于封装业务逻辑
  2. MCP Server:Model Context Protocol 服务器支持,用于访问外部资源
社区热点:工具集、OpenAPI 和 MCP 支持是社区高度关注的功能(#110 issue,18 个评论) 资料来源:CONTRIBUTING.md:community_context

结构化输出

PydanticAI 利用 Pydantic 模型的强类型特性,实现结构化输出。开发者可以定义 Pydantic 模型作为输出模式,系统会自动处理验证和类型转换。

社区热点:结构化输出作为工具调用的替代方案是热门话题(#582 issue,29 个评论) 资料来源:CONTRIBUTING.md:community_context

依赖管理

安装方式

PydanticAI 提供多种安装方式以满足不同需求:

# 基础安装
pip install pydantic-ai

# 仅安装核心框架(不含提供商依赖)
pip install pydantic-ai-slim

# 按需安装特定提供商
pip install 'pydantic-ai-slim[openai]'
pip install 'pydantic-ai-slim[anthropic]'
pip install 'pydantic-ai-slim[google]'

资料来源:CONTRIBUTING.md:install.md#slim-install

新模型添加规则

项目对添加新模型有明确的规范:

  • 带额外依赖的模型:该依赖需要在 PyPI 上每月下载量 > 500k,持续 3 个月以上
  • 内部使用其他模型逻辑且无额外依赖的模型:该模型的 GitHub 组织需要总计 > 20k stars
  • 仅需自定义 URL 和 API key 的模型:可添加一 paragraph 描述和链接
  • 需要更多逻辑的其他模型:推荐发布独立的 Python 包 pydantic-ai-xxx

资料来源:CONTRIBUTING.md:22-32

扩展与集成

MCP 支持

Model Context Protocol(MCP)支持允许智能体访问外部资源。MCP 通过"工具集(Toolsets)"机制实现,使 LLM 能够动态发现和调用工具。

扩展模块(ext)

PydanticAI 通过 pydantic_ai.ext 模块提供扩展功能:

  • pydantic_ai.ext.aci:ACI.dev 工具集成(已标记废弃,将在 2.0 版本移除)
# 已废弃的用法
from pydantic_ai.ext.aci import tool_from_aci

# 推荐用法:使用原生方式包装
from pydantic_ai.tools import Tool

资料来源:pydantic_ai_slim/pydantic_ai/ext/aci.py:1-45

Logfire 集成

作为 Pydantic 生态的一部分,PydanticAI 原生支持与 Logfire 集成,提供开箱即用的可观测性支持。

示例与用例

PydanticAI 仓库包含丰富的示例代码,涵盖各种用例:

示例说明
RAG检索增强生成示例
工具调用自定义工具使用
结构化输出基于 Pydantic 模型的输出
依赖注入运行时依赖管理

所有示例的完整文档和运行说明请参阅 ai.pydantic.dev/examples/

资料来源:examples/README.md:1-15

社区与贡献

贡献流程

  1. 发现问题? 创建 issue,包含清晰的描述和最小可复现示例。建议附上 Logfire trace 链接以加速调试。
  2. 想要功能或 API 变更? 创建 issue 描述你要解决的问题。不要直接写代码。
  3. 想要帮助构建功能? 在 issue 下评论,说明你的需求和背景(成为"Champion")。
  4. 有修复或代码要分享? 确保维护者已在 issue 上同意方案并分配给你,然后再创建 PR。

资料来源:CONTRIBUTING.md:6-16

能力(Capabilities)优先

大多数新的智能体行为应该放入 Pydantic AI Harness,而非核心仓库。核心仓库专注于:

  • 智能体循环
  • 模型提供商
  • 需要模型特定支持或对智能体体验至关重要的能力

独立的能力(如防护栏、记忆、上下文管理、文件系统访问等)应该放入 harness。

资料来源:CONTRIBUTING.md:40-50

常见问题与路线图

社区热点问题

Issue评论数说明
#58229结构化输出作为工具调用的替代方案
#197819交接/子智能体委托(Handoffs)
#11018工具集、OpenAPI 和 MCP 支持
#5817向量搜索和 Embeddings API

功能路线图

当前重点领域包括:

  • Capabilities/Hooks API:能力扩展机制
  • Provider-adaptive Tools:提供商自适应的工具
  • Pydantic AI Harness:能力库建设

资料来源:CONTRIBUTING.md:55-60

版本信息

最新版本

v1.103.0(2026-05-26)包含以下更新:

  • McpServer 添加 list_promptsget_prompt 功能
  • 通过 VercelAIAdapterUIMessage.metadata 实现消息时间戳往返

资料来源:community_context:release_notes

版本策略

PydanticAI 遵循严格的版本策略,确保用户能够自信地升级。所有变更必须向后兼容。

相关文档

参见

资料来源:CLAUDE.md:49-55

安装与快速入门

本页面介绍 Pydantic AI 的完整安装流程、环境配置以及快速上手指南。Pydantic AI 是一个轻量级的 Python 库,旨在让任何希望使用 LLM 和 Agent 的 Python 开发者都能轻松集成到项目中。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 Python 版本支持

继续阅读本节完整说明和来源证据。

章节 核心依赖

继续阅读本节完整说明和来源证据。

章节 标准安装

继续阅读本节完整说明和来源证据。

系统要求

在开始安装 Pydantic AI 之前,请确保您的开发环境满足以下基本要求。

Python 版本支持

Pydantic AI 支持 Python 3.10 及以上版本。推荐使用 Python 3.10、3.11 或 3.12 以获得最佳性能和兼容性。

Python 版本支持状态备注
3.10✅ 完全支持最低要求版本
3.11✅ 完全支持推荐版本
3.12✅ 完全支持最新特性支持
3.13+✅ 完全支持持续兼容

资料来源:pydantic_ai_slim/pyproject.toml

核心依赖

Pydantic AI 的核心功能依赖于以下 Python 包:

依赖包最低版本用途
pydantic≥2.0数据验证和类型定义
anyio≥4.0异步 I/O 支持
httpx≥0.27.0HTTP 客户端

安装方式

Pydantic AI 提供多种安装方式,您可以根据项目需求选择最合适的方案。

标准安装

标准安装包含所有内置功能,适用于大多数使用场景:

pip install pydantic-ai

此命令会安装 Pydantic AI 及其所有核心依赖,包括对多种模型提供者的支持。

Slim 安装

Slim 安装仅包含核心功能,适合只需要基础 Agent 能力的场景,或者希望自行管理模型依赖的项目:

pip install pydantic-ai-slim

Slim 版本排除了特定模型提供者的依赖,如果需要使用特定模型(如 OpenAI、Anthropic 等),需要额外安装相应的依赖包。

资料来源:docs/install.md

从源码安装

如果您希望使用最新开发版本或为项目贡献代码,可以从源码安装:

git clone [email protected]:pydantic/pydantic-ai.git
cd pydantic-ai
pip install -e .

从源码安装需要预先安装 uv(版本 0.4.30 或更高)和 pre-commit 工具。

资料来源:CONTRIBUTING.md

环境配置

环境变量设置

大多数模型提供者需要通过环境变量配置 API 密钥。以下是常用模型提供者的环境变量配置:

模型提供者环境变量获取方式
OpenAIOPENAI_API_KEYOpenAI 平台
AnthropicANTHROPIC_API_KEYAnthropic 控制台
Google GeminiGEMINI_API_KEYGoogle AI Studio
Ollama本地运行无需密钥Ollama 官网

使用 .env 文件管理密钥

推荐使用 .env 文件来管理环境变量,配合 python-dotenv 库加载配置:

pip install python-dotenv

创建 .env 文件(注意不要将其提交到版本控制系统):

OPENAI_API_KEY=sk-your-api-key-here
ANTHROPIC_API_KEY=sk-ant-your-api-key-here

在 Python 代码中加载环境变量:

from dotenv import load_dotenv

load_dotenv()  # 从 .env 文件加载环境变量

快速入门

以下示例展示 Pydantic AI 的基本使用流程。

创建第一个 Agent

from pydantic_ai import Agent

# 创建 Agent 实例,指定使用的模型
agent = Agent('openai:gpt-4o')

# 运行 Agent
result = agent.run_sync('用一句话解释什么是人工智能')
print(result.output)

使用结构化输出

Pydantic AI 的核心优势之一是支持通过 Pydantic 模型定义结构化输出:

from pydantic import BaseModel
from pydantic_ai import Agent

class WeatherResponse(BaseModel):
    city: str
    temperature: float
    condition: str

agent = Agent(
    'openai:gpt-4o',
    result_type=WeatherResponse,
)

result = agent.run_sync('北京今天天气怎么样?')
print(f"城市: {result.output.city}")
print(f"温度: {result.output.temperature}°C")
print(f"天气状况: {result.output.condition}")

资料来源:examples/README.md

使用工具(Tools)

Agent 可以调用自定义工具来扩展能力:

from pydantic_ai import Agent

agent = Agent(
    'openai:gpt-4o',
    tools=[calculate, search_database],  # 定义工具列表
)

result = agent.run_sync('计算 15% 的所得税')

异步运行

对于异步应用场景,Pydantic AI 提供完整的异步支持:

import asyncio
from pydantic_ai import Agent

agent = Agent('openai:gpt-4o')

async def main():
    result = await agent.run('你好,介绍一下你自己')
    print(result.output)

asyncio.run(main())

工作流程概览

graph TD
    A[安装 Pydantic AI] --> B[配置环境变量]
    B --> C[创建 Agent 实例]
    C --> D[定义工具和输出模型]
    D --> E[运行 Agent]
    E --> F[处理结果]
    F --> G[集成到应用]
    
    H[Slim 安装] --> C
    I[标准安装] --> C

常见问题与故障排除

导入错误

如果遇到 ImportError 错误,确保已正确安装包:

# 检查安装状态
pip show pydantic-ai

# 重新安装
pip install --upgrade pydantic-ai

模型连接失败

  1. 检查 API 密钥:确认环境变量已正确设置
  2. 验证网络连接:确保能够访问模型提供者的 API 端点
  3. 检查 API 配额:部分模型提供者有调用频率限制

异步问题

在使用异步模式时,确保使用 await 关键字等待异步操作完成:

# 错误示例
result = agent.run('问题')

# 正确示例
result = await agent.run('问题')

依赖注入

Pydantic AI 支持依赖注入模式,可以在运行时向 Agent 传递上下文和资源:

from pydantic import BaseModel
from pydantic_ai import Agent, RunContext

class DatabaseConn(BaseModel):
    url: str

agent = Agent(
    'openai:gpt-4o',
    deps_type=DatabaseConn,
)

@agent.tool
async def query_db(ctx: RunContext[DatabaseConn], sql: str):
    conn = ctx.deps
    # 使用 conn.url 执行数据库查询
    pass

下一步

安装完成后,建议进一步了解以下主题:

主题说明相关资源
Agent 核心概念深入理解 Agent 的架构和运行机制docs/agent.md
工具系统学习如何定义和使用工具docs/tools.md
结构化输出掌握如何获取类型安全的输出docs/output.md
依赖注入使用依赖注入管理应用上下文docs/dependencies.md
消息历史管理对话上下文和历史记录docs/message-history.md

参见

资料来源:pydantic_ai_slim/pyproject.toml

系统架构

Pydantic AI 是一个开源的提供商无关(provider-agnostic)GenAI Agent 框架,专门为 Python 设计,由 Pydantic 团队维护。该框架的核心设计理念是轻量级、可扩展,让任何 Python 开发者都能轻松地将 LLM(大语言模型)和 Agent 能力集成到自己的项目中。

章节 相关页面

继续阅读本节完整说明和来源证据。

概述

Pydantic AI 是一个开源的提供商无关(provider-agnostic)GenAI Agent 框架,专门为 Python 设计,由 Pydantic 团队维护。该框架的核心设计理念是轻量级、可扩展,让任何 Python 开发者都能轻松地将 LLM(大语言模型)和 Agent 能力集成到自己的项目中。

资料来源:CLAUDE.md

该框架强调以下核心原则:

  • 强基元(Strong Primitives):提供强大而简洁的抽象
  • 通用解决方案:支持构建开发者尚未想到的各类应用
  • 轻量级设计:避免"电池已包含"的臃肿方案
  • 端到端类型安全:充分利用 Python 类型系统

资料来源:CLAUDE.md

代理系统详解

PydanticAI 的代理(Agent)系统是框架的核心抽象,它封装了与大语言模型(LLM)交互的完整逻辑,包括消息管理、工具调用、依赖注入、输出校验等功能。代理系统设计遵循"轻量级但功能强大"的原则,通过强原语和通用扩展点,让开发者能够构建各类复杂的 AI 应用。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 核心设计理念

继续阅读本节完整说明和来源证据。

概述

PydanticAI 的代理(Agent)系统是框架的核心抽象,它封装了与大语言模型(LLM)交互的完整逻辑,包括消息管理、工具调用、依赖注入、输出校验等功能。代理系统设计遵循"轻量级但功能强大"的原则,通过强原语和通用扩展点,让开发者能够构建各类复杂的 AI 应用。

资料来源:docs/agent.md

核心设计理念

根据项目哲学文档,代理系统强调:

  • 现代、惯用的简洁 Python 代码
  • 端到端类型安全,无需不必要的 castAny
  • 周到、一致的 API 设计
  • 愉悦的开发者体验

资料来源:CLAUDE.md

资料来源:docs/agent.md

工具系统

Pydantic AI 的工具系统(Tool System)是框架的核心组件之一,它使 AI 代理能够调用外部函数、执行特定操作并获取结构化数据。工具系统提供了一种类型安全、声明式的方式来定义和注册可被语言模型调用的函数,从而扩展代理的能力范围。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 工具类型体系

继续阅读本节完整说明和来源证据。

章节 工具的组成部分

继续阅读本节完整说明和来源证据。

章节 使用 Tool.fromfn() 创建函数工具

继续阅读本节完整说明和来源证据。

概述

Pydantic AI 的工具系统(Tool System)是框架的核心组件之一,它使 AI 代理能够调用外部函数、执行特定操作并获取结构化数据。工具系统提供了一种类型安全、声明式的方式来定义和注册可被语言模型调用的函数,从而扩展代理的能力范围。

工具系统在 Pydantic AI 架构中扮演着桥梁角色,连接语言模型的推理能力与外部系统的实际功能。通过工具,代理可以执行数据库查询、API 调用、文件操作等任务,实现真正的交互式 AI 应用。

相关社区讨论:工具系统是 Pydantic AI 中最受关注的特性之一。Issue #582 讨论了结构化输出作为工具调用的替代方案,而 Issue #110 则涉及对 MCP(Model Context Protocol)的支持计划。

核心概念

工具类型体系

Pydantic AI 的工具系统包含以下核心工具类型:

工具类型说明使用场景
FunctionTool基于 Python 函数的工具,通过 Tool.from_fn() 创建最常用的工具类型,适用于任何 Python 函数
ToolsetTool工具集封装的工具,用于批量管理多个工具需要组织多个相关工具时使用
AgentTool封装另一个代理的工具,用于代理间协作实现子代理委托(handoff)模式
MCPToolMCP 协议工具,通过 MCP 服务器调用外部工具连接 MCP 生态系统
FastMCPToolset快速 MCP 工具集,提供优化的 MCP 集成高性能 MCP 集成场景

工具的组成部分

graph TD
    A[Tool 工具] --> B[ToolDefinition 工具定义]
    A --> C[ToolFunc 工具函数]
    A --> D[ToolParams 工具参数]
    
    B --> B1[name 名称]
    B --> B2[description 描述]
    B --> B3[parameters 模式]
    B --> B4[openapi 规范]
    
    C --> C1[同步函数]
    C --> C2[异步函数]
    
    D --> D1[deps_type 依赖类型]
    D --> D2[retry_policy 重试策略]
    D --> D3[takes_context 是否接受上下文]

工具定义与创建

使用 `Tool.from_fn()` 创建函数工具

最常用的工具创建方式是通过 Tool.from_fn() 装饰器或工厂方法:

from pydantic_ai import Tool

def get_weather(city: str) -> str:
    """获取指定城市的天气信息"""
    return f"{city}今天的天气是晴天,25°C"

weather_tool = Tool.from_fn(
    get_weather,
    name='get_weather',
    description='查询城市的当前天气'
)

资料来源:pydantic_ai_slim/pydantic_ai/tools.py:1-50

使用 `Tool.from_schema()` 从 Pydantic 模型创建

对于需要复杂输入参数的工具,可以使用 Pydantic 模型定义工具参数:

from pydantic import BaseModel
from pydantic_ai import Tool

class SearchParams(BaseModel):
    query: str
    max_results: int = 10
    include_similar: bool = False

search_tool = Tool.from_schema(
    SearchParams,
    name='web_search',
    description='执行网络搜索'
)

资料来源:pydantic_ai_slim/pydantic_ai/_function_schema.py:1-100

工具参数配置

参数名类型说明是否必需
namestr工具的唯一标识名称
descriptionstr工具功能描述,用于模型理解何时调用
parametersJsonSchemaJSON Schema 格式的参数定义
deps_typetype[BaseModel]依赖注入类型
retryRetryStrategy重试策略配置
takes_contextbool是否接收执行上下文

工具注册与使用

向 Agent 注册工具

from pydantic_ai import Agent

agent = Agent(
    'openai:gpt-4',
    tools=[weather_tool, search_tool]  # 注册工具列表
)

资料来源:docs/tools.md:1-50

工具执行流程

sequenceDiagram
    participant U as 用户
    participant A as Agent
    participant T as Tool
    participant M as Model
    
    U->>A: run/user_query
    A->>M: generate(messages)
    M-->>A: ToolCall(tool_name, args)
    A->>T: execute(tool_call)
    T->>T: validate_args
    T->>T: inject_dependencies
    T->>T: call_function
    T-->>A: ToolResult
    A->>M: continue_with(tool_result)
    M-->>A: final_response
    A-->>U: 返回结果

依赖注入

工具系统支持通过依赖注入向工具函数提供运行时依赖:

from pydantic_ai import Agent, RunContext
from pydantic_ai.agents import AgentDeps

class DatabaseConn:
    def __init__(self, connection_string: str):
        self.conn = connection_string

class AppDeps(BaseModel):
    db: DatabaseConn
    user_id: str

async def query_database(ctx: RunContext[AppDeps], sql: str) -> str:
    """使用数据库连接执行 SQL 查询"""
    conn = ctx.deps.db
    # 执行查询逻辑
    return f"查询结果: {sql}"

db_tool = Tool.from_fn(
    query_database,
    deps_type=AppDeps
)

agent = Agent(
    'openai:gpt-4',
    tools=[db_tool],
    deps_type=AppDeps
)

原生工具(Native Tools)

Pydantic AI 提供了内置的原生工具集,扩展了模型的核心能力:

计算机工具(ComputerTool)

用于模拟用户在计算机上的操作:

from pydantic_ai import Agent
from pydantic_ai.tools import ComputerTool, ComputerToolView

agent = Agent(
    'openai:gpt-4o',
    tools=[
        ComputerTool(
            tool_version='v2',
            display=ComputerToolView()
        )
    ]
)

Bash 工具(BashTool)

用于在本地系统执行命令:

from pydantic_ai.tools import BashTool

bash_tool = BashTool()

代码执行工具

支持在沙箱环境中执行代码的原生工具:

工具名称说明用途
CodeExecutionTool代码执行工具安全地运行 Python/JS 代码
ComputerTool计算机操作工具模拟鼠标和键盘操作
BashToolBash 执行工具运行系统命令

资料来源:docs/native-tools.md:1-80

MCP 工具集成

MCP 协议支持

Pydantic AI 通过 MCPToolset 提供对 Model Context Protocol 的支持:

from pydantic_ai.toolsets import MCPToolset

mcp_toolset = MCPToolset(
    server='my-mcp-server',
    env_vars={'API_KEY': 'secret'}
)

MCP 服务器工具

使用 McpServer 创建和管理 MCP 服务器连接:

from pydantic_ai.toolsets.mcp import McpServer

server = McpServer(
    command=['npx', '-y', '@anthropic/mcp-server'],
    env={'ANTHROPIC_API_KEY': api_key}
)
社区讨论:Issue #110 详细描述了 Toolsets、OpenAPI 和 MCP 的集成计划,这是 Pydantic AI 工具系统演进的重要方向。

FastMCP 工具集

FastMCPToolset 提供了更轻量级的 MCP 集成方式:

from pydantic_ai.toolsets import FastMCPToolset

fast_mcp_toolset = FastMCPToolset(
    url="http://localhost:3000/mcp",
    env_vars={'API_KEY': 'secret'}
)

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/fastmcp.py:1-50

工具集(Toolsets)

工具集是一种批量管理多个工具的抽象,允许将相关工具组织在一起:

创建工具集

from pydantic_ai import FunctionToolset

def search_products(query: str, category: str = None) -> list[dict]:
    """搜索产品"""
    pass

def get_product_detail(product_id: str) -> dict:
    """获取产品详情"""
    pass

product_tools = FunctionToolset(
    tools=[search_products, get_product_detail],
    description="产品目录管理工具集"
)

工具集继承

工具集支持组合和继承,可以构建复杂的工具层次:

graph TD
    A[FunctionToolset] --> B[ProductTools 产品工具集]
    A --> C[UserTools 用户工具集]
    A --> D[OrderTools 订单工具集]
    
    B --> E[CombinedTools 组合工具集]
    C --> E
    D --> E

工具执行上下文

RunContext 详解

RunContext 提供了工具执行时的完整上下文信息:

属性类型说明
depsAgentDepsT依赖注入数据
messageslist[Message]对话历史
modelModel当前使用的模型
tool_call_idstr工具调用 ID
result_tool_call_id`str \None`结果工具调用 ID

上下文参数接收

工具函数可以通过 RunContext 参数访问执行上下文:

async def advanced_search(
    ctx: RunContext[AppDeps],
    query: str,
    filters: dict | None = None
) -> list[dict]:
    user_id = ctx.deps.user_id  # 访问用户信息
    db = ctx.deps.db  # 访问数据库连接
    
    # 执行搜索
    return []

重试与错误处理

重试策略配置

from pydantic_ai.tools import RetryStrategy

custom_retry = RetryStrategy(
    max_attempts=3,
    initial_delay=1.0,
    backoff_multiplier=2.0,
    max_delay=30.0
)

tool = Tool.from_fn(
    api_call,
    retry=custom_retry
)

工具级别错误处理

from pydantic_ai.tools import ToolError

def fragile_operation(ctx: RunContext, input_data: str) -> str:
    try:
        # 执行可能失败的操作
        return process(input_data)
    except NetworkError as e:
        raise ToolError(f"网络错误: {e}") from e

最佳实践

工具设计原则

  1. 清晰的描述:为每个工具提供详细的描述,帮助模型理解何时使用
  2. 类型安全的参数:使用 Pydantic 模型定义复杂参数
  3. 最小化参数:避免不必要的参数,减少模型理解难度
  4. 原子性操作:每个工具执行单一职责的操作

性能优化

优化策略说明
异步工具优先使用 async def 定义工具
依赖复用通过 deps_type 复用数据库连接等资源
批量操作对于批量数据处理,考虑支持批量参数
结果缓存对频繁调用的工具实现缓存机制

安全性考虑

# 使用依赖注入限制访问权限
class SecureDeps(BaseModel):
    user_role: str
    allowed_resources: list[str]

def restricted_operation(ctx: RunContext[SecureDeps], resource: str) -> str:
    if resource not in ctx.deps.allowed_resources:
        raise ToolError("权限不足")
    return access_resource(resource)

常见问题与限制

模型工具调用限制

  • 工具数量限制:不同模型对单次请求可调用的工具数量有限制
  • 参数复杂度:过于复杂的参数模式可能导致模型调用失败
  • 上下文窗口:大量工具定义会占用上下文空间

跨提供商差异

不同模型提供商的工具调用实现存在差异:

提供商工具调用支持特殊限制
OpenAI完整支持
Anthropic完整支持Claude Sonnet 3.5+
Google完整支持Gemini 1.5 Pro+
Cohere完整支持Command R+ 系列

调试技巧

  1. 启用日志记录:使用 Logfire 记录工具调用
  2. 查看模型输出:检查模型的工具选择决策
  3. 简化测试:先使用最少的工具进行测试

相关文档

参见

资料来源:pydantic_ai_slim/pydantic_ai/tools.py:1-50

工具集与 MCP 协议

工具集(Toolsets)是 Pydantic AI 中用于组织和封装一组相关工具的抽象机制。通过工具集,开发者可以将多个工具逻辑地分组在一起,便于管理和传递给 Agent。工具集与 MCP(Model Context Protocol)协议的深度集成,使得 Pydantic AI 能够与外部 MCP 服务器进行无缝通信,让 Agent 能够调用远程工具资源。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 什么是工具集

继续阅读本节完整说明和来源证据。

章节 MCP 协议简介

继续阅读本节完整说明和来源证据。

章节 工具集类型体系

继续阅读本节完整说明和来源证据。

概述

工具集(Toolsets)是 Pydantic AI 中用于组织和封装一组相关工具的抽象机制。通过工具集,开发者可以将多个工具逻辑地分组在一起,便于管理和传递给 Agent。工具集与 MCP(Model Context Protocol)协议的深度集成,使得 Pydantic AI 能够与外部 MCP 服务器进行无缝通信,让 Agent 能够调用远程工具资源。

根据社区讨论 Issue #110,工具集的引入是为了解决"为 Agent 构建访问资源的工具会非常耗费资源"这一痛点。通过统一的工具集抽象,开发者可以更轻松地集成 MCP 协议、OpenAPI 规范以及其他外部工具源。

资料来源:docs/toolsets.md:1-15

核心概念

什么是工具集

工具集是一种将多个工具封装为单一可复用单元的模式。在 Pydantic AI 中,工具集实现了 Toolset 接口,可以包含:

  • 本地定义的函数工具
  • 外部 MCP 服务器提供的远程工具
  • 延迟加载的工具集合

工具集的主要优势在于:

  1. 代码组织:将相关工具逻辑分组
  2. 延迟加载:支持在需要时才初始化工具,提高启动性能
  3. 统一接口:提供一致的 API 访问不同来源的工具

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/__init__.py:1-50

MCP 协议简介

MCP(Model Context Protocol)是一种开放协议,用于在 AI 模型和外部数据源/工具之间建立标准化通信。MCP 服务器托管工具和资源,客户端(如 Pydantic AI)通过 MCP 协议与服务器交互。

graph LR
    A[Agent] -->|调用工具| B[工具集]
    B -->|MCP 协议| C[MCP 服务器]
    C -->|工具定义| B
    C -->|执行结果| B
    B -->|结构化结果| A
    
    D[本地工具] -->|直接调用| B
    E[延迟加载工具] -->|按需加载| B

资料来源:docs/mcp/overview.md:1-30

架构设计

工具集类型体系

Pydantic AI 提供多种工具集实现,以满足不同的使用场景:

工具集类型描述使用场景
FunctionToolset封装本地 Python 函数将现有函数暴露给 Agent
FastMCPToolset集成 FastMCP 工具连接 FastMCP 服务器
MCPToolset标准 MCP 服务器集成连接通用 MCP 服务器
ExternalToolset外部工具包装器封装第三方工具
DeferredToolset延迟加载工具集延迟初始化直到首次使用

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/__init__.py:50-150

核心接口定义

工具集的核心接口包含以下关键方法:

class Toolset(Protocol):
    """工具集标准接口"""
    
    @abstractmethod
    def name(self) -> str:
        """工具集唯一名称"""
        ...
    
    @abstractmethod
    async def get_tools(self) -> Sequence[Tool]:
        """获取工具列表"""
        ...

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/__init__.py:30-45

MCP 服务器集成架构

classDiagram
    class AbstractMCPServer {
        <<abstract>>
        +name: str
        +server_info: ServerInfo
        +protocol_version: str
        +connect() None
        +disconnect() None
        +list_tools() List[ToolDefinition]
        +call_tool(name, args) Any
    }
    
    class McpServer {
        +process: subprocess.Popen
        +command: list[str]
        +transport: str
    }
    
    class FastMCPServer {
        +app: FastAPI
        +host: str
        +port: int
    }
    
    AbstractMCPServer <|-- McpServer
    AbstractMCPServer <|-- FastMCPServer
    
    class MCPToolset {
        +mcp_server: AbstractMCPServer
        +get_tools() List[Tool]
    }
    
    MCPToolset o-- AbstractMCPServer

资料来源:pydantic_ai_slim/pydantic_ai/mcp.py:1-100

使用指南

创建基础工具集

使用 FunctionToolset 可以将本地 Python 函数封装为工具集:

from pydantic_ai import Agent, FunctionToolset
import asyncio

async def get_weather(city: str) -> str:
    """获取城市天气信息"""
    return f"{city} 今天天气晴朗,温度 25°C"

weather_toolset = FunctionToolset(tools=[get_weather])

agent = Agent(
    model='openai:gpt-4o',
    tools=[weather_toolset],
)

result = agent.run_sync("北京今天天气怎么样?")
print(result.output)

资料来源:docs/toolsets.md:50-80

连接 MCP 服务器

通过 McpServer 类可以连接到外部 MCP 服务器:

from pydantic_ai import Agent
from pydantic_ai.mcp import McpServer

# 创建 MCP 服务器连接
mcp_server = McpServer(
    command=['npx', 'y', '-y', '@modelcontextprotocol/server-filesystem'],
    args=['/path/to/directory'],
    transport='stdio',
)

agent = Agent(
    model='anthropic:claude-3-5-sonnet',
    tools=[mcp_server],
)

result = agent.run_sync("列出 /tmp 目录下的文件")

资料来源:docs/mcp/overview.md:80-120

延迟加载工具集

对于启动时不需要的工具,使用 DeferredToolset 可以实现延迟加载:

from pydantic_ai.toolsets import DeferredToolset, FunctionToolset

async def expensive_tool():
    """需要大量计算的昂贵工具"""
    # 首次调用时才执行初始化
    ...

# 延迟工具集
deferred = DeferredToolset(
    loader=lambda: FunctionToolset(tools=[expensive_tool])
)

# 工具定义在运行时才加载
agent = Agent(model='openai:gpt-4o', tools=[deferred])

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/deferred_loading.py:1-60

在 Agent 间传递工具集

工具集可以在创建 Agent 时直接传入,也可以在运行时不透明地传递给 Agent:

from pydantic_ai import Agent
from pydantic_ai.toolsets import FunctionToolset

def get_timestamp() -> str:
    return "2024-01-15T10:30:00Z"

timestamp_toolset = FunctionToolset(tools=[get_timestamp])

# 直接在工具列表中传入
agent = Agent(
    model='openai:gpt-4o',
    tools=[timestamp_toolset],  # 工具集作为工具列表元素
)

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/external.py:1-50

配置选项

McpServer 配置参数

参数类型必需默认值描述
commandlist[str]-启动 MCP 服务器的命令
argslist[str][]命令行参数
envdict[str, str]None环境变量
transportLiteral["stdio", "sse"]"stdio"传输协议
timeoutfloat60.0超时时间(秒)

资料来源:pydantic_ai_slim/pydantic_ai/mcp.py:100-150

工具集名称配置

每个工具集都有一个名称,用于日志和调试目的:

from pydantic_ai.toolsets import FunctionToolset

async def my_tool(query: str) -> str:
    return f"处理查询: {query}"

# 自定义工具集名称
toolset = FunctionToolset(
    tools=[my_tool],
    name="my_custom_toolset"  # 可选,默认使用类名
)

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/__init__.py:80-120

进阶用法

外部工具包装

使用 ExternalToolset 可以将任何外部工具源包装为统一接口:

from pydantic_ai.toolsets import ExternalToolset

# 包装外部 API 工具
external_tools = ExternalToolset(
    source="custom-api",
    tools_loader=my_custom_loader,
)

资料来源:pydantic_ai_slim/pydantic_ai/toolsets/external.py:40-80

与 Temporal 工作流集成

Pydantic AI 支持在 Temporal 持久化工作流中使用 MCP 工具集:

from pydantic_ai.durable_exec.temporal import TemporalFastMCPToolset

# 在 Temporal 工作流中使用 FastMCP 工具集
workflow_toolset = TemporalFastMCPToolset(
    toolset=fast_mcp_toolset,
    activity_name_prefix="my_prefix",
    activity_config={},
    tool_activity_config={},
    deps_type=MyDeps,
)

资料来源:pydantic_ai_slim/pydantic_ai/durable_exec/temporal/_fastmcp_toolset.py:1-60

MCP 服务器生命周期管理

sequenceDiagram
    participant Client as Pydantic AI
    participant Server as MCP 服务器
    participant Tools as 工具集
    
    Note over Client: 初始化阶段
    Client->>Server: 启动进程
    Client->>Server: 初始化握手
    Server-->>Client: 服务器信息 + 协议版本
    
    Note over Client: 工具发现阶段
    Client->>Server: list_tools
    Server-->>Client: 工具定义列表
    
    Note over Client: 运行时
    Client->>Tools: 获取可用工具
    Tools-->>Client: 工具列表
    
    loop 每次 Agent 调用
        Client->>Server: call_tool(name, args)
        Server-->>Client: 执行结果
    end
    
    Note over Client: 清理阶段
    Client->>Server: 关闭连接
    Server-->>Client: 确认关闭

资料来源:pydantic_ai_slim/pydantic_ai/mcp.py:150-200

最佳实践

工具集命名规范

  • 使用描述性名称,便于日志追踪
  • 避免名称冲突,特别是在多工具集场景下
  • 建议格式:{source}_{category}_toolset(如 filesystem_read_toolset

性能优化

  1. 延迟加载:对于非必要工具使用 DeferredToolset
  2. 批量获取:避免频繁调用 get_tools()
  3. 连接复用:保持 MCP 服务器连接活跃

错误处理

MCP 服务器连接失败时的处理策略:

from pydantic_ai.mcp import McpServer

mcp_server = McpServer(
    command=['npx', '-y', '@server/path'],
    timeout=30.0,  # 设置合理的超时时间
)

try:
    agent = Agent(model='openai:gpt-4o', tools=[mcp_server])
    result = agent.run_sync("使用工具完成任务")
except Exception as e:
    # 处理连接错误
    print(f"MCP 服务器连接失败: {e}")

资料来源:docs/api/mcp.md:50-100

与社区功能的关系

与 Handoffs/子代理委托的关系

根据 Issue #1978,工具和输出函数可以用于实现 Agent 间的交接(handoff)。工具集在这一场景中可以提供结构化的工具传递机制:

# 工具集支持子代理委托
sub_agent = Agent(
    model='openai:gpt-4o',
    tools=[specialized_toolset],  # 子代理专用工具集
)

@agent.tool_plain
async def delegate_to_specialist(task: str):
    """将任务委托给专业代理"""
    result = await sub_agent.run(task)
    return result.output

与向量搜索/嵌入的关系

社区 Issue #58 讨论了向量搜索和嵌入 API 的需求。工具集可以作为扩展机制,通过 MCP 协议集成外部向量数据库工具:

# 通过 MCP 集成向量搜索工具
vector_search_server = McpServer(
    command=['python', '-m', 'vector_search_mcp_server'],
)

常见问题

Q: 工具集和普通工具列表有什么区别?

A: 工具集是一种组织单元,提供了更好的封装性和可复用性。普通工具列表只是扁平的工具集合,而工具集可以包含元数据、延迟加载逻辑,并支持统一的工具发现接口。

Q: MCP 服务器启动失败怎么办?

A: 检查以下几点:

  1. 命令路径是否正确
  2. 依赖是否已安装(如 npxnode
  3. 环境变量是否正确设置
  4. 超时设置是否合理

Q: 如何调试 MCP 工具调用?

A: 使用日志追踪工具调用:

  • 启用 Pydantic AI 调试日志
  • 检查 MCP 服务器日志输出
  • 使用 Logfire 进行分布式追踪

参考链接

资料来源:docs/toolsets.md:1-15

结构化输出

结构化输出(Structured Output)是 PydanticAI 框架的核心功能之一,旨在让大语言模型(LLM)返回的结果能够严格遵循预定义的 Pydantic 数据模型。通过将 Pydantic 模型与 LLM 输出相结合,开发者可以获得类型安全、可验证的响应数据,无需手动解析和验证 JSON 或文本内容。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 核心技术架构

继续阅读本节完整说明和来源证据。

章节 输出类型选择

继续阅读本节完整说明和来源证据。

章节 基本用法

继续阅读本节完整说明和来源证据。

概述

结构化输出(Structured Output)是 PydanticAI 框架的核心功能之一,旨在让大语言模型(LLM)返回的结果能够严格遵循预定义的 Pydantic 数据模型。通过将 Pydantic 模型与 LLM 输出相结合,开发者可以获得类型安全、可验证的响应数据,无需手动解析和验证 JSON 或文本内容。

PydanticAI 的结构化输出主要通过工具调用(Tool Calling)机制实现,同时也支持输出函数(Output Functions)作为补充方案。资料来源:docs/output.md

工作原理

核心技术架构

当使用结构化输出时,PydanticAI 会将目标 Pydantic 模型转换为模型提供商的工具定义格式。模型根据这个定义生成符合 schema 的响应,系统随后将响应解析回 Pydantic 实例。

graph TD
    A[用户定义 Pydantic 模型] --> B[Agent 配置 result_type]
    B --> C[框架转换为工具定义]
    C --> D[模型提供商 API]
    D --> E[模型生成结构化响应]
    E --> F[框架解析响应]
    F --> G[返回 Pydantic 实例]

输出类型选择

PydanticAI 提供两种结构化输出的实现方式:

输出类型描述适用场景
工具调用 (Tool Calling)将模型包装为工具,强制使用 JSON Schema需要严格结构化、跨模型兼容
输出函数 (Output Functions)使用模型的原生输出格式功能模型原生支持、需要更灵活的控制

资料来源:docs/output.md

使用方法

基本用法

通过 result_type 参数指定期望的输出类型:

from pydantic import BaseModel
from pydantic_ai import Agent

class UserInfo(BaseModel):
    name: str
    age: int
    email: str | None = None

agent = Agent(
    'openai:gpt-4o',
    result_type=UserInfo
)

result = agent.run_sync('提取用户信息: 张三,25岁')
user: UserInfo = result.data
print(user.name)  # 输出: 张三

带验证的模型

可以使用 Pydantic 的丰富验证功能:

from pydantic import BaseModel, Field, field_validator
from typing import Literal

class Order(BaseModel):
    product: str
    quantity: int = Field(gt=0, description='数量必须大于0')
    status: Literal['pending', 'shipped', 'delivered']
    
    @field_validator('product')
    @classmethod
    def product_must_be_valid(cls, v: str) -> str:
        if len(v) < 2:
            raise ValueError('产品名称至少需要2个字符')
        return v.title()

异步使用

async def main():
    result = await agent.run('提取订单信息')
    order: Order = result.data

配置选项

Agent 结果配置

参数类型说明
result_typetype[Model]期望的输出 Pydantic 模型类型
result_validationbool是否在解析后进行额外验证,默认 True
output_retriesint输出验证失败时的最大重试次数,默认 3

模型级配置

不同的模型提供商对结构化输出的支持程度不同:

模型JSON Schema 支持原生结构化输出备注
OpenAI (GPT-4o+)使用 tool_calls 或 response_format
Anthropic⚠️通过工具调用实现,存在 schema 限制
Google Gemini支持 JSON Schema
Cohere通过工具调用支持

资料来源:pydantic_ai_slim/pydantic_ai/models/cohere.py

消息历史与结构化输出

结构化输出可以与消息历史功能无缝配合,实现多轮对话中的状态管理:

from pydantic_ai import Agent
from pydantic_ai.memory import Memory

class ConversationSummary(BaseModel):
    topic: str
    key_points: list[str]
    conclusion: str | None = None

agent = Agent('openai:gpt-4o', result_type=ConversationSummary)
memory = Memory()

async def chat(message: str):
    result = await agent.run(message, message_history=memory.get())
    memory.add(result.new_messages())
    return result.data

常见失败模式与处理

1. Schema 不兼容

某些 Pydantic 特性在不同模型提供商间可能表现不一致:

  • 嵌套模型:深层嵌套可能导致部分提供商截断
  • 联合类型:不同模型对 Literal 类型的支持程度不同
  • 自定义验证器:验证器在模型生成后执行,不影响模型本身生成
⚠️ 社区讨论:Issue #582 指出当前 PydanticAI 主要通过工具调用 API 实现结构化输出,但某些 Pydantic schema 在不同模型提供商间存在行为不一致。资料来源:github.com/pydantic/pydantic-ai/issues/582

2. 重试机制

当模型生成的输出无法通过 Pydantic 验证时,系统会自动重试:

agent = Agent(
    'openai:gpt-4o',
    result_type=UserInfo,
    output_retries=5  # 增加重试次数处理复杂 schema
)

3. 错误处理

from pydantic_ai.exceptions import ModelRetry

class SafeAgent:
    async def run_safe(self, prompt: str) -> UserInfo | None:
        try:
            result = await agent.run(prompt)
            return result.data
        except ModelRetry as e:
            # 处理模型需要更多指导的情况
            return None

输出函数(Output Functions)

输出函数是结构化输出的补充方式,通过装饰器定义:

from pydantic_ai import agent

@agent.output_cell
def process_result(result: UserInfo) -> str:
    """后处理函数,可用于格式化或额外逻辑"""
    return f"已提取用户: {result.name} ({result.age}岁)"

资料来源:docs/output.md

与工具调用的关系

结构化输出与工具调用共享底层实现机制,但在使用模式上有区别:

graph LR
    A[结构化输出] -->|强制模式| B[JSON Schema 约束]
    A -->|灵活性| C[直接返回结构化数据]
    D[工具调用] -->|交互模式| E[多轮工具使用]
    D -->|工具定义| F[Function Calling]
    
    B -.->|共享| G[底层转换逻辑]
    E -.->|共享| G

选择建议

场景推荐方式
单次结构化响应结构化输出 (result_type)
需要模型使用多个工具工具调用
需要模型决定是否调用工具工具调用
固定格式响应结构化输出
复杂多步骤任务工具调用配合 Handoffs

与 AG-UI 的集成

在 Agentic Generative UI 场景中,结构化输出可用于生成状态更新事件:

from pydantic_ai import Agent

class Plan(BaseModel):
    steps: list[Step]

agent = Agent(
    'openai:gpt-4o',
    instructions='使用工具规划任务步骤'
)

@agent.tool_plain
async def create_plan(steps: list[str]) -> StateSnapshotEvent:
    """创建计划工具"""
    plan = Plan(steps=[Step(description=s) for s in steps])
    return StateSnapshotEvent(
        type=EventType.STATE_SNAPSHOT,
        snapshot=plan
    )

资料来源:examples/pydantic_ai_examples/ag_ui/api/agentic_generative_ui.py

最佳实践

1. Schema 设计

  • 优先使用简单的扁平时结构
  • 避免过深的嵌套(建议不超过 3 层)
  • 使用 Literal 类型约束可选值
  • 为所有字段提供清晰的 description
class OptimizedModel(BaseModel):
    name: str = Field(description='用户全名')
    age: int = Field(ge=0, le=150, description='用户年龄')
    tags: list[str] = Field(default_factory=list, description='相关标签')

2. 错误恢复

  • 设置合理的 output_retries
  • 提供清晰的错误消息帮助模型修正输出
  • 使用 SystemPrompt 指导输出格式

3. 模型选择

  • 优先选择明确支持结构化输出的模型
  • 测试不同模型对复杂 schema 的支持程度
  • 考虑降级方案(如回退到纯文本解析)

相关功能

功能说明关联文档
工具调用与结构化输出共享底层机制tools.md
依赖注入在结构化输出中使用依赖dependencies.md
消息历史支持多轮结构化对话message-history.md
Handoffs子代理委托agents.md

参见

资料来源:docs/output.md

多代理应用

本文档介绍如何在 PydanticAI 中构建多代理应用系统。多代理应用通过协调多个专业化的 AI 代理来协作完成复杂任务,每个代理专注于特定领域的职责。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 代理层级结构

继续阅读本节完整说明和来源证据。

章节 状态管理

继续阅读本节完整说明和来源证据。

章节 核心概念

继续阅读本节完整说明和来源证据。

概述

多代理应用(Multi-Agent Applications)是指由多个独立但相互协作的 AI 代理组成的系统。在这种架构中:

  • 专业化分工:每个代理专注于特定任务域
  • 信息传递:代理之间通过消息传递进行通信
  • 层级协调:顶层代理负责任务分配和结果聚合
  • 可扩展性:可以动态添加或移除代理以适应需求变化

资料来源:docs/multi-agent-applications.md:1-10

核心架构

代理层级结构

graph TD
    A[用户请求] --> B[顶层协调代理]
    B --> C[专业代理 A]
    B --> D[专业代理 B]
    B --> E[专业代理 C]
    C --> B
    D --> B
    E --> B
    B --> F[聚合结果]

资料来源:docs/graph.md:1-20

状态管理

多代理应用中的状态管理采用以下模式:

状态类型描述持久化方式
代理状态单个代理的上下文内存或数据库
会话状态整个对话的状态数据库
共享状态代理间共享的数据依赖注入
图状态PydanticGraph 的状态图节点属性

资料来源:pydantic_graph/pydantic_graph/graph.py:50-100

PydanticGraph 框架

PydanticAI 提供了 pydantic_graph 模块来构建基于图的多代理应用。

核心概念

概念说明
Graph有向图结构,定义节点和边的关系
Node图中的节点,代表一个状态或操作
Edge节点之间的边,定义转移条件
State在图执行过程中传递的共享状态

资料来源:pydantic_graph/pydantic_graph/step.py:1-30

图的构建

from pydantic_graph import Graph, GraphRunContext
from pydantic import BaseModel

class AgentState(BaseModel):
    messages: list[str] = []
    current_agent: str | None = None

class MultiAgentGraph(Graph[AgentState]):
    async def run(
        self, 
        node: str, 
        state: AgentState,
        ctx: GraphRunContext
    ) -> str | None:
        # 根据当前节点执行相应的代理逻辑
        pass

资料来源:docs/graph/builder/index.md:1-50

代理间通信模式

1. 直接工具调用模式

代理通过工具调用委派任务给其他代理:

@agent.tool_plain
async def delegate_to_specialist(
    specialist_name: str,
    task: str
) -> str:
    """将任务委托给专业代理"""
    specialist = get_specialist(specialist_name)
    result = await specialist.run(user_text=task)
    return result.output

资料来源:examples/pydantic_ai_examples/ag_ui/api/agentic_generative_ui.py:1-80

2. 消息传递模式

代理通过共享消息历史进行通信:

async def agent_handoff(
    from_agent: Agent,
    to_agent: Agent,
    state: AgentState
) -> ModelResponse:
    """代理间的状态转移"""
    # 获取当前代理的响应
    response = await from_agent.run(
        user_text=state.pending_task,
        message_history=state.messages
    )
    
    # 更新状态并切换到目标代理
    state.messages.extend(response.messages())
    return response

3. 共享依赖注入模式

通过依赖注入共享状态和资源:

from pydantic_ai import Agent, RunContext

class SharedDeps(BaseModel):
    memory: AgentMemory
    tools: list[Tool]

async def multi_agent_system(
    prompt: str,
    deps: SharedDeps
) -> str:
    agents = [
        create_agent('planner', deps),
        create_agent('executor', deps),
        create_agent('reviewer', deps)
    ]
    return await orchestrate(agents, prompt, deps)

资料来源:pydantic_ai_slim/pydantic_ai/durable_exec/temporal/_run_context.py:1-50

代理委托(Handoffs)

代理委托是实现多代理协作的核心机制,允许一个代理将控制权转移给另一个代理。

基本用法

from pydantic_ai import Agent, handoff

primary_agent = Agent('openai:gpt-4o')
secondary_agent = Agent('anthropic:claude-3-5-sonnet-20241022')

# 创建委托
primary_agent += handoff(secondary_agent)

委托状态传播

状态组件传播方式说明
消息历史自动传递保留完整对话上下文
依赖项共享传递使用相同的依赖注入
模型设置可配置可以为每个代理单独设置

资料来源:docs/multi-agent-applications.md:50-100

工具集(Toolsets)

工具集是组织和封装多个工具的机制,支持 OpenAPI 和 MCP(Model Context Protocol)集成。

FastMCP 工具集

from pydantic_ai.toolsets.fastmcp import FastMCPToolset

toolset = FastMCPToolset(
    url='http://localhost:8080',
    tools=['search', 'fetch', 'analyze']
)

agent = Agent('openai:gpt-4o', tools=[toolset])

工具集与代理集成

graph LR
    A[代理] --> B[工具集路由器]
    B --> C[FastMCP]
    B --> D[OpenAPI]
    B --> E[自定义工具]
    C --> F[外部服务]
    D --> G[REST API]
    E --> H[内部逻辑]

资料来源:pydantic_ai_slim/pydantic_ai/durable_exec/temporal/_fastmcp_toolset.py:1-50

错误处理与恢复

代理级别错误处理

策略适用场景实现方式
重试临时性失败@agent.tool(retries=3)
后备代理专业代理失败委托给通用代理
状态回滚需要撤销操作使用事务性状态
错误上报顶层处理抛出自定义异常

跨代理错误传播

class AgentError(Exception):
    """代理执行中的错误"""
    def __init__(self, agent_name: str, original: Exception):
        self.agent_name = agent_name
        self.original = original
        super().__init__(f'{agent_name}: {original}')

最佳实践

1. 代理职责划分

原则说明
单一职责每个代理专注于特定任务
清晰边界明确定义代理间的接口
最小依赖减少代理间的耦合

2. 状态管理

class MultiAgentState(BaseModel):
    """多代理共享状态"""
    session_id: str
    current_turn: int = 0
    active_agents: set[str] = set()
    shared_context: dict[str, Any] = {}
    
    def checkpoint(self) -> dict:
        """创建状态快照"""
        return self.model_dump()
    
    def restore(self, snapshot: dict) -> None:
        """恢复状态"""
        for key, value in snapshot.items():
            setattr(self, key, value)

3. 性能优化

  • 并行执行:独立代理可以并行运行
  • 缓存结果:避免重复调用相同代理
  • 流式输出:使用流式响应减少延迟
  • 资源隔离:为每个代理设置资源限制

常见问题与限制

已知的限制

限制类型说明社区讨论
委托复杂性当前需要手动处理输入输出#1978
工具集支持MCP 集成仍在完善中#110
状态一致性分布式环境下需要额外同步-

故障排除

  1. 代理无响应
  • 检查依赖注入配置
  • 验证工具定义正确性
  • 确认模型 API 密钥有效
  1. 状态丢失
  • 检查状态持久化机制
  • 验证消息历史传递
  1. 循环调用
  • 设置最大迭代次数
  • 实现退出条件检测

扩展阅读

相关资源

资料来源:docs/multi-agent-applications.md:1-10

模型提供商

Pydantic AI 的模型提供商(Model Providers)是整个框架的核心抽象层,负责与各种大语言模型(LLM)服务进行交互。作为一个provider-agnostic(提供商无关)的框架,Pydantic AI 通过统一的接口封装了不同模型提供商的 API,使得开发者可以在不修改核心业务逻辑的情况下切换使用不同的 LLM 服务。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 核心抽象类

继续阅读本节完整说明和来源证据。

章节 请求响应流程

继续阅读本节完整说明和来源证据。

章节 提供商特性对比表

继续阅读本节完整说明和来源证据。

概述

Pydantic AI 的模型提供商(Model Providers)是整个框架的核心抽象层,负责与各种大语言模型(LLM)服务进行交互。作为一个provider-agnostic(提供商无关)的框架,Pydantic AI 通过统一的接口封装了不同模型提供商的 API,使得开发者可以在不修改核心业务逻辑的情况下切换使用不同的 LLM 服务。

模型提供商的主要职责包括:

  • API 请求构建:将 Pydantic AI 的标准化请求格式转换为特定提供商的 API 格式
  • 响应解析:将提供商的响应转换为 Pydantic AI 内部统一的 ModelResponse 格式
  • 功能特性映射:处理不同提供商之间的功能差异(如 thinking、tool calling 等)
  • 消息历史管理:维护与提供商的对话上下文

资料来源:pydantic_ai_slim/pydantic_ai/models/base.py

架构设计

核心抽象类

Pydantic AI 采用 Model 抽象类作为所有模型提供商的基类,所有具体的模型实现都继承自这个核心接口。

graph TD
    A[Model 抽象基类] --> B[OpenAI 模型]
    A --> C[Anthropic 模型]
    A --> D[Google Gemini 模型]
    A --> E[Cohere 模型]
    A --> F[其他第三方模型]
    
    G[Agent] --> H[ModelRequest]
    H --> A
    A --> I[ModelResponse]
    I --> G
    
    J[ToolCallPart] --> A
    K[TextPart] --> A
    L[ThinkingPart] --> A

请求响应流程

sequenceDiagram
    participant Agent
    participant Model as Model (ABC)
    participant Provider as 具体 Provider API
    
    Agent->>Model: 发送 ModelRequest
    Model->>Model: 构建提供商特定请求
    Model->>Provider: API 调用
    Provider-->>Model: 返回响应
    Model->>Model: 解析响应
    Model-->>Agent: 返回 ModelResponse

支持的模型提供商

Pydantic AI 支持多种主流的 LLM 服务提供商,以下是各提供商的详细配置。

提供商特性对比表

提供商模型系列原生工具调用Thinking 模式结构化输出多模态支持
OpenAIGPT-4o, GPT-4o-mini, o1, o3✅ (o 系列)
AnthropicClaude 3.5, Claude 4
GoogleGemini 1.5, Gemini 2.0
CohereCommand R+

Anthropic 模型配置

Anthropic 模型支持多种高级特性,包括 thinking 模式和代码执行工具:

from pydantic_ai.models.anthropic import AnthropicModel

model = AnthropicModel(
    'claude-sonnet-4-5',
)

支持的代码执行工具版本:

版本适用模型说明
20250825所有支持模型默认版本
20260120Claude 4.5+最新版本,支持更复杂的执行场景

资料来源:pydantic_ai_slim/pydantic_ai/profiles/anthropic.py:25-45

响应解析机制

响应部分(Parts)

模型响应由多个「部分」(Parts)组成,每种部分类型代表不同类型的内容:

部分类型说明使用场景
TextPart文本内容普通对话回复
ToolCallPart工具调用请求Function calling
ThinkingPart思考过程支持 thinking 的模型
RetryPart重试标记需要重新生成的响应

Cohere 模型响应处理示例

# 从 Cohere 响应中提取内容
for c in response.message.tool_calls or []:
    if c.function and c.function.name and c.function.arguments:
        parts.append(
            ToolCallPart(
                tool_name=c.function.name,
                args=c.function.arguments,
                tool_call_id=c.id or _generate_tool_call_id(),
            )
        )

资料来源:pydantic_ai_slim/pydantic_ai/models/cohere.py:78-92

Gemini 模型集成

函数调用转换

Gemini 模型使用特殊的函数调用格式,Pydantic AI 提供了专门的转换逻辑:

def _function_call_part_from_call(tool: ToolCallPart) -> _GeminiFunctionCallPart:
    return _GeminiFunctionCallPart(
        function_call=_GeminiFunctionCall(
            name=tool.tool_name, 
            args=tool.args_as_dict()
        )
    )

响应处理流程

graph LR
    A[Gemini API 响应] --> B{Part 类型判断}
    B -->|text| C[TextPart 或 ThinkingPart]
    B -->|function_call| D[ToolCallPart]
    B -->|function_response| E[抛出异常]
    
    C --> F[构建 ModelResponse]
    D --> F

资料来源:pydantic_ai_slim/pydantic_ai/models/gemini.py:58-75

第三方扩展支持

Vercel AI SDK 适配器

Pydantic AI 提供了与 Vercel AI SDK 的集成适配器,支持流式事件处理:

from percat_ai.ui.vercel_ai import VercelAIEventStream

#### 结束原因映射

Pydantic AIVercel AI SDK
stopstop
lengthlength
content_filtercontent-filter
tool_calltool-calls
errorerror

资料来源:pydantic_ai_slim/pydantic_ai/ui/vercel_ai/_event_stream.py:45-58

ACI.dev 扩展

Pydantic AI 提供了对 ACI.dev 工具的集成支持(已标记为废弃):

from pydantic_ai.ext.aci import tool_from_aci

# 已废弃,将在 2.0 版本移除
tool = tool_from_aci(aci_function, linked_account_owner_id)

!!! warning "废弃警告" pydantic_ai.ext.aci 模块已废弃,建议使用 pydantic_ai.tools.Tool.from_schema 或直接使用上游的 aci-sdk 集成。

资料来源:pydantic_ai_slim/pydantic_ai/ext/aci.py:22-30

工具集与 MCP 集成

Temporal MCP 工具集

对于持久化执行场景,Pydantic AI 提供了 Temporal 框架的 MCP 工具集支持:

from pydantic_ai.durable_exec.temporal import TemporalFastMCPToolset

工具集架构设计:

graph TD
    A[TemporalFastMCPToolset] --> B[FastMCPToolset]
    A --> C[TemporalMCPToolsetBase]
    
    C --> D[活动配置]
    C --> E[工具活动映射]
    
    F[ToolDefinition] --> A
    A --> G[ToolsetTool]

资料来源:pydantic_ai_slim/pydantic_ai/durable_exec/temporal/_fastmcp_toolset.py:18-45

常见问题与社区讨论

社区关注的议题

#### Issue #582:结构化输出的替代方案

当前 Pydantic AI 主要通过工具调用 API 实现结构化输出,但不同提供商对 Pydantic schemas 的支持存在差异。社区正在讨论添加结构化输出的替代实现方式。

相关源码:pydantic_ai_slim/pydantic_ai/models/cohere.py

#### Issue #58:向量搜索和嵌入 API

目前 RAG 示例使用 OpenAI 原生 API 生成嵌入,社区期待 Pydantic AI 提供统一的嵌入 API 接口。

故障排除

问题可能原因解决方案
响应解析失败提供商返回格式变更检查日志,提交 issue
工具调用未触发模型不支持确认模型支持 function calling
Thinking 模式异常提供商限制查看具体模型的 capability

最佳实践

1. 选择合适的模型

# 简单任务 - 使用轻量模型
from pydantic_ai.models.openai import OpenAIModel
fast_model = OpenAIModel('gpt-4o-mini')

# 复杂推理 - 使用高端模型
powerful_model = OpenAIModel('o1-preview')

2. 提供商特定配置

# Anthropic 支持 thinking 配置
model = AnthropicModel(
    'claude-sonnet-4-5',
    supports_thinking=True,
)

# Google Gemini 支持 JSON Schema 输出
model = GeminiModel(
    'gemini-1.5-pro',
    supports_json_schema_output=True,
)

3. 错误处理

try:
    result = await agent.run(user_message)
except UnexpectedModelBehavior as e:
    # 提供商返回了意外格式
    logger.error(f"模型响应格式异常: {e}")
except ModelError as e:
    # API 调用错误
    logger.error(f"模型 API 错误: {e}")

相关文档

参见

资料来源:pydantic_ai_slim/pydantic_ai/models/base.py

向量嵌入与 RAG

Pydantic AI 为开发者提供了与大型语言模型(LLM)交互的强大框架。在构建智能问答系统和知识增强应用时,检索增强生成(Retrieval-Augmented Generation,RAG) 是一种核心技术范式,而向量嵌入(Embeddings) 则是实现高效语义检索的基础。

章节 相关页面

继续阅读本节完整说明和来源证据。

概述

Pydantic AI 为开发者提供了与大型语言模型(LLM)交互的强大框架。在构建智能问答系统和知识增强应用时,检索增强生成(Retrieval-Augmented Generation,RAG) 是一种核心技术范式,而向量嵌入(Embeddings) 则是实现高效语义检索的基础。

根据社区 issue #58 的讨论,Pydantic AI 目前通过 OpenAI 等模型提供商的原生 API 来生成嵌入向量,尚未内置专门的向量嵌入 API。但该框架的架构设计使得开发者可以灵活地将向量搜索能力与 Agent 系统结合,构建完整的 RAG 应用。

资料来源:社区讨论 #58: Vector search and embeddings API

资料来源:社区讨论 #58: Vector search and embeddings API

失败模式与踩坑日记

保留 Doramagic 在发现、验证和编译中沉淀的项目专属风险,不把社区讨论只当作装饰信息。

high 来源证据:xAI: update docs and `KnownModelName` for current Grok 4.3 / 4.20 model names

可能增加新用户试用和生产接入成本。

high 来源证据:[roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization

可能增加新用户试用和生产接入成本。

high 来源证据:[streaming-resilience-sweep] Streaming: `stream_output()` doesn't set `is_complete=True` on early break

可能影响升级、迁移或版本选择。

high 来源证据:[aw] No-Op Runs

可能增加新用户试用和生产接入成本。

Pitfall Log / 踩坑日志

项目:pydantic/pydantic-ai

摘要:发现 28 个潜在踩坑项,其中 5 个为 high/blocking;最高优先级:安装坑 - 来源证据:xAI: update docs and KnownModelName for current Grok 4.3 / 4.20 model names。

1. 安装坑 · 来源证据:xAI: update docs and `KnownModelName` for current Grok 4.3 / 4.20 model names

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安装相关的待验证问题:xAI: update docs and KnownModelName for current Grok 4.3 / 4.20 model names
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_fecdaf4224b646929420b15d99f2a933 | https://github.com/pydantic/pydantic-ai/issues/5663 | 来源类型 github_issue 暴露的待验证使用条件。

2. 配置坑 · 来源证据:[roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:[roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_d3718c4d2db24bceabf8d4e935091eec | https://github.com/pydantic/pydantic-ai/issues/5696 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

3. 配置坑 · 来源证据:[streaming-resilience-sweep] Streaming: `stream_output()` doesn't set `is_complete=True` on early break

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:[streaming-resilience-sweep] Streaming: stream_output() doesn't set is_complete=True on early break
  • 对用户的影响:可能影响升级、迁移或版本选择。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_9c38896c20d24789beb9604c4d4f2626 | https://github.com/pydantic/pydantic-ai/issues/5615 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

4. 安全/权限坑 · 来源证据:[aw] No-Op Runs

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[aw] No-Op Runs
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_0ba5cb74938c4ad5aaddfd0fced08630 | https://github.com/pydantic/pydantic-ai/issues/5685 | 来源类型 github_issue 暴露的待验证使用条件。

5. 安全/权限坑 · 来源证据:`MCPToolset(url, http_client=...)` crashes: factory missing `follow_redirects` kwarg passed by `FastMCP`

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:MCPToolset(url, http_client=...) crashes: factory missing follow_redirects kwarg passed by FastMCP
  • 对用户的影响:可能阻塞安装或首次运行。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_30f08a19e50a4708b984022031c55054 | https://github.com/pydantic/pydantic-ai/issues/5688 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

6. 安装坑 · 失败模式:installation: v2.0.0b1 (2026-05-20)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this installation risk before relying on the project: v2.0.0b1 (2026-05-20)
  • 对用户的影响:Upgrade or migration may change expected behavior: v2.0.0b1 (2026-05-20)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v2.0.0b1 (2026-05-20). Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_6565701c26f03fa2f9360df9e9925984 | https://github.com/pydantic/pydantic-ai/releases/tag/v2.0.0b1 | v2.0.0b1 (2026-05-20)

7. 配置坑 · 失败模式:configuration: [aw] No-Op Runs

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: [aw] No-Op Runs
  • 对用户的影响:Developers may misconfigure credentials, environment, or host setup: [aw] No-Op Runs
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: [aw] No-Op Runs. Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_630176c03d70150693f25efc4e776f66 | https://github.com/pydantic/pydantic-ai/issues/5685 | [aw] No-Op Runs

8. 配置坑 · 失败模式:configuration: `MCPToolset(url, http_client=...)` crashes: factory missing `follow_redirects` kwarg passed b...

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: MCPToolset(url, http_client=...) crashes: factory missing follow_redirects kwarg passed by FastMCP
  • 对用户的影响:Developers may misconfigure credentials, environment, or host setup: MCPToolset(url, http_client=...) crashes: factory missing follow_redirects kwarg passed by FastMCP
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: MCPToolset(url, http_client=...) crashes: factory missing follow_redirects kwarg passed by FastMCP. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_1c1bcf0774a223c19b0054f060350857 | https://github.com/pydantic/pydantic-ai/issues/5688 | MCPToolset(url, http_client=...) crashes: factory missing follow_redirects kwarg passed by FastMCP

9. 配置坑 · 失败模式:configuration: v1.100.0 (2026-05-20)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.100.0 (2026-05-20)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.100.0 (2026-05-20)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.100.0 (2026-05-20). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_1118f6639392629ef5022ee4c6f40741 | https://github.com/pydantic/pydantic-ai/releases/tag/v1.100.0 | v1.100.0 (2026-05-20)

10. 配置坑 · 失败模式:configuration: v1.101.0 (2026-05-21)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.101.0 (2026-05-21)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.101.0 (2026-05-21)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.101.0 (2026-05-21). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_e0130422b62adb912b0bfab8a362a2c7 | https://github.com/pydantic/pydantic-ai/releases/tag/v1.101.0 | v1.101.0 (2026-05-21)

11. 配置坑 · 失败模式:configuration: v1.102.0 (2026-05-22)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.102.0 (2026-05-22)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.102.0 (2026-05-22)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.102.0 (2026-05-22). Context: Observed when using docker
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_b0bf5413bd949884bdbfa3f220d92c63 | https://github.com/pydantic/pydantic-ai/releases/tag/v1.102.0 | v1.102.0 (2026-05-22)

12. 配置坑 · 失败模式:configuration: v1.103.0 (2026-05-26)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.103.0 (2026-05-26)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.103.0 (2026-05-26)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.103.0 (2026-05-26). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_456a570a5fe6acd24fe482fbb09c7712 | https://github.com/pydantic/pydantic-ai/releases/tag/v1.103.0 | v1.103.0 (2026-05-26)

13. 配置坑 · 失败模式:configuration: v1.97.0 (2026-05-15)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.97.0 (2026-05-15)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.97.0 (2026-05-15)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.97.0 (2026-05-15). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_bda659bd6f6abef62eebb2e078e947e4 | https://github.com/pydantic/pydantic-ai/releases/tag/v1.97.0 | v1.97.0 (2026-05-15)

14. 配置坑 · 失败模式:configuration: v1.98.0 (2026-05-18)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.98.0 (2026-05-18)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.98.0 (2026-05-18)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.98.0 (2026-05-18). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_9e2147dc09e31b5971fdce0f207206ce | https://github.com/pydantic/pydantic-ai/releases/tag/v1.98.0 | v1.98.0 (2026-05-18)

15. 配置坑 · 失败模式:configuration: v1.99.0 (2026-05-19)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v1.99.0 (2026-05-19)
  • 对用户的影响:Upgrade or migration may change expected behavior: v1.99.0 (2026-05-19)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v1.99.0 (2026-05-19). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_4b34c5a62f3a45510cd8771cdc290541 | https://github.com/pydantic/pydantic-ai/releases/tag/v1.99.0 | v1.99.0 (2026-05-19)

16. 配置坑 · 失败模式:configuration: v2.0.0b2 (2026-05-21)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v2.0.0b2 (2026-05-21)
  • 对用户的影响:Upgrade or migration may change expected behavior: v2.0.0b2 (2026-05-21)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v2.0.0b2 (2026-05-21). Context: Observed during version upgrade or migration.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_6abb491a15959bb1e4d61d65b1fa1fc5 | https://github.com/pydantic/pydantic-ai/releases/tag/v2.0.0b2 | v2.0.0b2 (2026-05-21)

17. 配置坑 · 失败模式:configuration: v2.0.0b3 (2026-05-22)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: v2.0.0b3 (2026-05-22)
  • 对用户的影响:Upgrade or migration may change expected behavior: v2.0.0b3 (2026-05-22)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: v2.0.0b3 (2026-05-22). Context: Observed when using docker
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_fb412a6f85fcf1e09bcb80f252ace91b | https://github.com/pydantic/pydantic-ai/releases/tag/v2.0.0b3 | v2.0.0b3 (2026-05-22)

18. 配置坑 · 来源证据:Bedrock filters the tools array client-side when `tool_choice` forces a specific tool

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:Bedrock filters the tools array client-side when tool_choice forces a specific tool
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源显示可能已有修复、规避或版本变化,说明书中必须标注适用版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_f22814f2cf5c4d8ca2ef9ebb13f90d1a | https://github.com/pydantic/pydantic-ai/issues/5672 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

19. 能力坑 · 能力判断依赖假设

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:README/documentation is current enough for a first validation pass.
  • 对用户的影响:假设不成立时,用户拿不到承诺的能力。
  • 建议检查:将假设转成下游验证清单。
  • 防护动作:假设必须转成验证项;没有验证结果前不能写成事实。
  • 证据:capability.assumptions | github_repo:818331198 | https://github.com/pydantic/pydantic-ai | README/documentation is current enough for a first validation pass.

20. 运行坑 · 失败模式:runtime: Bedrock filters the tools array client-side when `tool_choice` forces a specific tool

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this runtime risk before relying on the project: Bedrock filters the tools array client-side when tool_choice forces a specific tool
  • 对用户的影响:Developers may hit a documented source-backed failure mode: Bedrock filters the tools array client-side when tool_choice forces a specific tool
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: Bedrock filters the tools array client-side when tool_choice forces a specific tool. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_9b1d8efd612da12698cf0bce2b4fe90a | https://github.com/pydantic/pydantic-ai/issues/5672 | Bedrock filters the tools array client-side when tool_choice forces a specific tool

21. 运行坑 · 失败模式:runtime: [roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this runtime risk before relying on the project: [roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization
  • 对用户的影响:Developers may hit a documented source-backed failure mode: [roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: [roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_4de8756ccb3f4c9da999d386da5a424d | https://github.com/pydantic/pydantic-ai/issues/5696 | [roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization

22. 运行坑 · 失败模式:runtime: xAI: update docs and `KnownModelName` for current Grok 4.3 / 4.20 model names

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this runtime risk before relying on the project: xAI: update docs and KnownModelName for current Grok 4.3 / 4.20 model names
  • 对用户的影响:Developers may hit a documented source-backed failure mode: xAI: update docs and KnownModelName for current Grok 4.3 / 4.20 model names
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: xAI: update docs and KnownModelName for current Grok 4.3 / 4.20 model names. Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_d0614ea67add2229d31197804c260ad5 | https://github.com/pydantic/pydantic-ai/issues/5663 | xAI: update docs and KnownModelName for current Grok 4.3 / 4.20 model names

23. 维护坑 · 失败模式:migration: [streaming-resilience-sweep] Streaming: `stream_output()` doesn't set `is_complete=True` on e...

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this migration risk before relying on the project: [streaming-resilience-sweep] Streaming: stream_output() doesn't set is_complete=True on early break
  • 对用户的影响:Developers may hit a documented source-backed failure mode: [streaming-resilience-sweep] Streaming: stream_output() doesn't set is_complete=True on early break
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: [streaming-resilience-sweep] Streaming: stream_output() doesn't set is_complete=True on early break. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_7696a9ea598f5f10b04013bbc7385aa3 | https://github.com/pydantic/pydantic-ai/issues/5615 | [streaming-resilience-sweep] Streaming: stream_output() doesn't set is_complete=True on early break

24. 维护坑 · 维护活跃度未知

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:未记录 last_activity_observed。
  • 对用户的影响:新项目、停更项目和活跃项目会被混在一起,推荐信任度下降。
  • 建议检查:补 GitHub 最近 commit、release、issue/PR 响应信号。
  • 防护动作:维护活跃度未知时,推荐强度不能标为高信任。
  • 证据:evidence.maintainer_signals | github_repo:818331198 | https://github.com/pydantic/pydantic-ai | last_activity_observed missing

25. 安全/权限坑 · 下游验证发现风险项

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:no_demo
  • 对用户的影响:下游已经要求复核,不能在页面中弱化。
  • 建议检查:进入安全/权限治理复核队列。
  • 防护动作:下游风险存在时必须保持 review/recommendation 降级。
  • 证据:downstream_validation.risk_items | github_repo:818331198 | https://github.com/pydantic/pydantic-ai | no_demo; severity=medium

26. 安全/权限坑 · 存在评分风险

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:no_demo
  • 对用户的影响:风险会影响是否适合普通用户安装。
  • 建议检查:把风险写入边界卡,并确认是否需要人工复核。
  • 防护动作:评分风险必须进入边界卡,不能只作为内部分数。
  • 证据:risks.scoring_risks | github_repo:818331198 | https://github.com/pydantic/pydantic-ai | no_demo; severity=medium

27. 维护坑 · issue/PR 响应质量未知

  • 严重度:low
  • 证据强度:source_linked
  • 发现:issue_or_pr_quality=unknown。
  • 对用户的影响:用户无法判断遇到问题后是否有人维护。
  • 建议检查:抽样最近 issue/PR,判断是否长期无人处理。
  • 防护动作:issue/PR 响应未知时,必须提示维护风险。
  • 证据:evidence.maintainer_signals | github_repo:818331198 | https://github.com/pydantic/pydantic-ai | issue_or_pr_quality=unknown

28. 维护坑 · 发布节奏不明确

  • 严重度:low
  • 证据强度:source_linked
  • 发现:release_recency=unknown。
  • 对用户的影响:安装命令和文档可能落后于代码,用户踩坑概率升高。
  • 建议检查:确认最近 release/tag 和 README 安装命令是否一致。
  • 防护动作:发布节奏未知或过期时,安装说明必须标注可能漂移。
  • 证据:evidence.maintainer_signals | github_repo:818331198 | https://github.com/pydantic/pydantic-ai | release_recency=unknown

来源:Doramagic 发现、验证与编译记录