pydantic-ai核心组件解析:打造智能代理的五大核心模块
引言:从痛点到解决方案
你是否曾在构建AI代理时面临这些挑战:模型调用与类型安全难以兼顾?工具集成繁琐且扩展性差?复杂工作流管理陷入"回调地狱"?pydantic-ai作为Pydantic团队官方推出的智能代理框架,通过五大核心组件为这些问题提供了优雅解决方案。本文将深入解析Agent、模型集成、工具系统、结构化输出和图执行引擎,带你掌握构建生产级智能代理的关键技术。
读完本文你将获得:
- 掌握pydantic-ai五大核心组件的设计原理与使用方法
- 学会通过依赖注入实现工具与代理的解耦
- 理解如何构建类型安全的多模型智能系统
- 能够设计复杂的代理工作流并进行可视化调试
- 获取10+可直接运行的生产级代码示例
核心组件一:Agent(智能代理)—— 智能交互的核心枢纽
Agent是pydantic-ai的核心抽象,封装了与LLM交互的完整生命周期。它通过类型安全的方式整合指令、工具和输出验证,实现了"像FastAPI一样直观"的开发体验。
核心构成
| 组件 | 作用 | 示例 |
|---|---|---|
| 指令系统 | 提供静态/动态指令 | @agent.instructions装饰器 |
| 工具集 | 注册外部函数调用 | @agent.tool装饰器 |
| 输出类型 | 定义返回数据结构 | output_type=SupportOutput |
| 依赖注入 | 管理运行时依赖 | deps_type=DatabaseConn |
| 模型配置 | 指定默认LLM及参数 | model='openai:gpt-4o' |
基础用法
from pydantic_ai import Agent
# 1. 定义输出结构
class WeatherReport(BaseModel):
temperature: float
conditions: str
# 2. 创建代理
weather_agent = Agent(
'openai:gpt-4o',
output_type=WeatherReport,
system_prompt='你是天气查询助手,返回结构化天气数据'
)
# 3. 运行代理
result = weather_agent.run_sync('查询北京今天天气')
print(f"温度: {result.output.temperature}°C, 状况: {result.output.conditions}")
高级特性:动态指令与依赖注入
@dataclass
class BankDeps:
db: DatabaseConn
user_id: int
agent = Agent(
'anthropic:claude-3-5-sonnet',
deps_type=BankDeps,
output_type=AccountBalance
)
@agent.instructions
async def dynamic_instructions(ctx: RunContext[BankDeps]) -> str:
user_name = await ctx.deps.db.get_username(ctx.deps.user_id)
return f"用户{user_name}的账户查询,使用中文口语化表达"
@agent.tool
async def check_balance(ctx: RunContext[BankDeps]) -> float:
return await ctx.deps.db.get_balance(ctx.deps.user_id)
执行流程
核心组件二:模型集成——多模型生态的统一接口
pydantic-ai采用"模型无关"设计理念,通过统一接口支持20+主流LLM提供商,同时提供故障转移、流式处理等企业级特性。
模型支持矩阵
| 提供商 | 支持模型类型 | 特殊特性 | 示例配置 |
|---|---|---|---|
| OpenAI | GPT-4/3.5, DALL-E | 函数调用, 图像生成 | openai:gpt-4o |
| Anthropic | Claude 3/2系列 | 长上下文(200K) | anthropic:claude-3-5-sonnet |
| Gemini系列 | 多模态, 免费额度 | google-gla:gemini-1.5-flash | |
| 国产模型 | 通义千问, 文心一言 | 国内网络优化 | deepseek:deepseek-chat |
| 开源模型 | Llama3, Mistral | 本地部署支持 | ollama:llama3 |
模型切换与故障转移
from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.models.anthropic import AnthropicModel
# 1. 配置主备模型
primary_model = OpenAIChatModel('gpt-4o', temperature=0.7)
backup_model = AnthropicModel('claude-3-5-sonnet', temperature=0.7)
# 2. 创建故障转移模型
fallback_model = FallbackModel(primary_model, backup_model)
# 3. 应用到代理
agent = Agent(fallback_model)
result = agent.run_sync('解释量子计算的基本原理')
print(f"使用模型: {result.model_name}") # 自动选择可用模型
模型配置精细化控制
from pydantic_ai import ModelSettings
agent = Agent(
'openai:gpt-4o',
settings=ModelSettings(
temperature=0.3, # 控制随机性
max_tokens=2048, # 输出长度限制
timeout=30, # 请求超时
top_p=0.95, # 采样参数
frequency_penalty=0.1 # 重复惩罚
)
)
核心组件三:工具系统——连接LLM与外部世界的桥梁
工具系统是pydantic-ai最强大的特性之一,它通过类型安全的函数调用,让LLM能够与外部API、数据库和业务逻辑交互,同时支持复杂的工具组合与权限控制。
工具定义三范式
# 范式1: 基础工具(无上下文)
@agent.tool_plain
def get_current_time() -> str:
"""获取当前时间"""
return datetime.now().isoformat()
# 范式2: 上下文工具(依赖注入)
@agent.tool
async def fetch_user_data(ctx: RunContext[AppDeps], user_id: int) -> dict:
"""获取用户详细信息"""
return await ctx.deps.db.fetch_user(user_id)
# 范式3: 高级工具(带验证与重试)
@agent.tool(retries=3, retry_delay=1.0)
async def call_payment_gateway(
ctx: RunContext[PaymentDeps],
amount: Annotated[float, Field(gt=0, description="支付金额")],
order_id: str
) -> str:
"""调用支付网关处理交易"""
try:
return await ctx.deps.gateway.charge(amount, order_id)
except InsufficientFundsError as e:
raise ModelRetry(f"余额不足: {e}, 请重新输入金额")
工具集管理
# 1. 创建工具集
weather_toolset = FunctionToolset()
@weather_toolset.tool
def get_temperature(city: str) -> float:
"""获取指定城市温度"""
return 25.0 # 实际调用天气API
@weather_toolset.tool
def get_conditions(city: str) -> str:
"""获取指定城市天气状况"""
return "晴朗"
# 2. 组合工具集
combined_toolset = CombinedToolset([
weather_toolset.prefixed("weather"),
datetime_toolset.prefixed("datetime")
])
# 3. 过滤工具集
filtered_toolset = combined_toolset.filtered(
lambda ctx, tool: "fahrenheit" not in tool.name
)
# 4. 应用到代理
agent = Agent(toolsets=[filtered_toolset])
人类审批工作流
# 1. 配置需要审批的工具集
sensitive_toolset = financial_toolset.approval_required(
lambda ctx, tool, args: args.get("amount", 0) > 1000
)
# 2. 处理审批请求
agent = Agent(
toolsets=[sensitive_toolset],
output_type=[TransactionResult, DeferredToolRequests]
)
result = agent.run_sync("转账2000元给张三")
if isinstance(result.output, DeferredToolRequests):
# 发送审批请求给管理员
approval = await get_manager_approval(result.output.calls)
# 提交审批结果
final_result = await agent.run(
message_history=result.all_messages(),
deferred_tool_results=approval
)
核心组件四:结构化输出——从自由文本到类型安全
pydantic-ai将Pydantic的类型验证能力与LLM输出完美结合,提供三种输出模式和实时流式验证,解决了"JSON解析地狱"问题。
输出模式对比
| 模式 | 适用场景 | 优点 | 示例 |
|---|---|---|---|
| 工具输出 | 复杂结构, 多选项 | 兼容性好, 错误重试 | ToolOutput(Order) |
| 原生输出 | 简单对象, 特定模型 | 性能优, 官方支持 | NativeOutput(User) |
| 提示输出 | 旧模型, 特殊格式 | 兼容性最佳 | PromptedOutput(Log) |
基础结构化输出
from pydantic import BaseModel, Field
class Product(BaseModel):
"""电商产品信息"""
id: int = Field(description="产品ID")
name: str = Field(description="产品名称")
price: float = Field(gt=0, description="产品价格")
tags: list[str] = Field(default_factory=list, description="产品标签")
agent = Agent(
'openai:gpt-4o',
output_type=Product,
system_prompt="解析用户提供的产品信息"
)
result = agent.run_sync("帮我解析这个产品: ID是123, 名称为'无线耳机', 价格99.99元, 标签有'电子','音频'")
print(result.output)
#> Product(id=123, name='无线耳机', price=99.99, tags=['电子', '音频'])
流式输出处理
async def stream_product_info():
agent = Agent(
'openai:gpt-4o',
output_type=Product,
system_prompt="生成3个电子产品信息, 流式输出"
)
async with agent.run_stream("生成产品") as stream:
async for partial_output in stream.stream_output():
print(f"部分结果: {partial_output}")
# 实时处理部分结果
final_output = await stream.final_output()
print(f"最终结果: {final_output}")
多类型输出与验证
class SuccessOutput(BaseModel):
transaction_id: str
status: str = "success"
class ErrorOutput(BaseModel):
error_code: int
message: str
agent = Agent(
'anthropic:claude-3-5-sonnet',
output_type=SuccessOutput | ErrorOutput
)
@agent.output_validator
async def validate_transaction(ctx, output):
if isinstance(output, SuccessOutput) and len(output.transaction_id) != 16:
raise ModelRetry("交易ID必须是16位字符")
return output
result = agent.run_sync("处理用户转账请求: 从6222账户转出500元")
核心组件五:图执行引擎——复杂工作流的可视化编排
基于pydantic-graph构建的图执行引擎,将代理逻辑抽象为节点和边,支持持久化、错误恢复和复杂分支控制,解决了传统代理"线性思维"的局限。
核心概念
问答流程图示例
@dataclass
class QAState:
question: str | None = None
answer: str | None = None
retry_count: int = 0
@dataclass
class AskQuestion(Node[QAState]):
async def run(self, ctx) -> GenerateAnswer:
ctx.state.question = await question_agent.run("生成一个数学问题")
return GenerateAnswer()
@dataclass
class GenerateAnswer(Node[QAState]):
async def run(self, ctx) -> EvaluateAnswer:
ctx.state.answer = input(f"请回答: {ctx.state.question}")
return EvaluateAnswer()
@dataclass
class EvaluateAnswer(Node[QAState]):
async def run(self, ctx) -> End|AskQuestion:
result = await evaluator_agent.run(
f"问题: {ctx.state.question}, 答案: {ctx.state.answer}"
)
if result.output.correct:
return End(result.output.explanation)
else:
ctx.state.retry_count += 1
if ctx.state.retry_count < 3:
return AskQuestion()
else:
return End("达到最大重试次数")
# 创建并运行图
qa_graph = Graph(nodes=(AskQuestion, GenerateAnswer, EvaluateAnswer))
result = await qa_graph.run(AskQuestion(), state=QAState())
持久化与断点续跑
# 1. 配置持久化存储
persistence = FileStatePersistence(Path("workflow_state.json"))
# 2. 从上次中断处恢复
if snapshot := await persistence.load_next():
# 恢复状态和节点
state = snapshot.state
current_node = snapshot.node
else:
# 全新开始
state = OrderState()
current_node = CreateOrder()
# 3. 运行工作流
async with order_graph.iter(
current_node,
state=state,
persistence=persistence
) as run:
async for node in run:
if isinstance(node, End):
print(f"工作流完成: {node.data}")
break
综合案例:智能银行客服代理
下面通过一个完整案例展示五大组件如何协同工作:
# 1. 定义数据模型
class SupportRequest(BaseModel):
user_query: str
account_id: str
class SupportResponse(BaseModel):
answer: str
risk_level: int = Field(ge=0, le=10)
suggested_action: str
# 2. 配置依赖
@dataclass
class BankDeps:
db: DatabaseClient
notification_service: NotificationService
auth: AuthClient
# 3. 创建工具集
class BankingToolset(FunctionToolset):
@tool
async def get_balance(self, ctx: RunContext, account_id: str) -> float:
return await ctx.deps.db.get_balance(account_id)
@tool
async def block_card(self, ctx: RunContext, account_id: str) -> str:
return await ctx.deps.db.block_card(account_id)
# 4. 构建代理
support_agent = Agent(
'openai:gpt-4o',
deps_type=BankDeps,
output_type=SupportResponse,
toolsets=[BankingToolset()],
system_prompt="""你是银行客服代理,需要:
1. 分析用户查询
2. 调用适当工具获取信息
3. 评估风险等级
4. 提供建议操作"""
)
# 5. 添加动态指令
@support_agent.instructions
async def get_customer_info(ctx: RunContext[BankDeps]) -> str:
user = await ctx.deps.auth.get_current_user()
return f"当前用户: {user.name}, 账户: {user.account_id}"
# 6. 运行代理
async def handle_support_request(request: SupportRequest):
deps = BankDeps(
db=DatabaseClient(),
notification_service=NotificationService(),
auth=AuthClient()
)
result = await support_agent.run(
request.user_query,
deps=deps,
extra={"account_id": request.account_id}
)
if result.output.risk_level > 7:
await deps.notification_service.alert_manager(
f"高风险请求: {result.output}"
)
return result.output
总结与展望
pydantic-ai通过五大核心组件构建了一个类型安全、灵活可扩展的智能代理框架:
- Agent作为中枢协调指令、工具和输出
- 模型集成提供多提供商支持和故障转移
- 工具系统实现外部功能调用与权限控制
- 结构化输出确保LLM响应的可靠性
- 图执行引擎支持复杂工作流与持久化
随着GenAI应用复杂度提升,pydantic-ai的"工程化优先"设计理念将帮助开发者构建更可靠、可维护的智能系统。未来版本计划加入多智能体协作、强化学习集成等高级特性,进一步拓展应用边界。
立即通过pip install pydantic-ai开始体验,访问官方文档获取更多示例和最佳实践。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



