使用Pydantic AI在Python中构建AI代理
学习如何使用Pydantic AI框架在Python中构建生产级的AI代理,涵盖结构化输出、自定义工具和依赖注入,以及Web搜索和扩展推理等内置功能。
本教程将指导你如何使用Pydantic AI在Python中构建生产级的AI代理。Pydantic AI是一个框架,通过强类型、验证和清晰结构来简化代理开发,使代理更加可靠且易于维护。
为什么选择Pydantic AI?
直接调用LLM时,响应是字符串,可能需要解析为结构化对象,这容易出错。Pydantic AI通过以下方式解决:类型安全的结构化输出(定义BaseModel,框架自动验证并重试);函数工具(注册Python函数,LLM通过类型提示和docstring决定何时调用);依赖注入(通过RunContext注入运行时依赖,无需全局状态)。
前提条件
需要Python 3.9+,熟悉Pydantic BaseModel和类型提示,了解LLM提示的基本原理,以及支持提供商的API密钥(本教程使用openai:gpt-4o-mini,但模式适用于Anthropic Claude、Google Gemini等)。
安装Pydantic AI
创建虚拟环境并安装:
python -m venv venv
source venv/bin/activate
pip install pydantic-ai然后设置API密钥(如export OPENAI_API_KEY=...)。
构建第一个代理
只需几行代码:
from pydantic_ai import Agent
agent = Agent(
"openai:gpt-4o-mini",
instructions="You are a concise assistant. Answer in one or two sentences."
)
result = agent.run_sync("What is a large language model?")
print(result.output)模型字符串格式为"provider:model-name",切换提供商只需更改前缀。
获取结构化验证输出
定义输出模型:
from pydantic import BaseModel, Field
class JobPosting(BaseModel):
job_title: str
company_name: str
required_skills: list[str]
seniority_level: str
is_remote: bool创建代理时设置output_type:
agent = Agent(
"openai:gpt-4o-mini",
output_type=JobPosting,
instructions="Extract structured job posting information. Only include what is explicitly stated."
)
result = agent.run_sync("...")
posting = result.output框架自动验证字段,缺失或类型错误时会重试。
为代理添加工具
工具让代理访问外部数据。例如,营养数据库查询:
NUTRITION_DB = {"chicken breast": {...}, ...}
class MealSummary(BaseModel):
total_calories: int
total_protein_g: float
# ...
@agent.tool_plain
def get_ingredient_nutrition(ingredient: str) -> str:
"""查询每100克食材的营养信息"""
data = NUTRITION_DB.get(ingredient.lower().strip())
if data:
return json.dumps({"ingredient": ingredient, **data})
return f"Not found. Available: {', '.join(NUTRITION_DB)}"代理调用工具后返回结构化MealSummary。
依赖注入实践
将数据源包装为服务类:
@dataclass
class NutritionService:
database: dict
def lookup(self, ingredient: str) -> dict | None:
return self.database.get(ingredient.lower().strip())声明代理的deps_type,工具函数使用RunContext:
agent = Agent(
"openai:gpt-4o-mini",
output_type=MealSummary,
deps_type=NutritionService,
instructions="Use tools to compute meal totals and provide a verdict."
)
@agent.tool
def get_ingredient_nutrition(ctx: RunContext[NutritionService], ingredient: str) -> str:
data = ctx.deps.lookup(ingredient)
return json.dumps({"ingredient": ingredient, **data}) if data else "Not found."运行时传递NutritionService实例,测试时可轻松替换为mock。
内置功能
Pydantic AI还支持Web搜索和扩展推理,可通过配置启用。本教程让你掌握构建实用代理的基础,完整Colab笔记本见GitHub。