关于 pydantic-ai-agent-creation
面向开发者的 PydanticAI Agent 构建参考,涵盖模型选择、结构化输出、依赖注入和运行方式,并提供上线前检查步骤。
主要功能
- 01配置模型与 Agent 行为
- 02验证带类型的结构化输出
- 03注入带类型的依赖
- 04以同步、异步或流式方式运行 Agent
- 05通过上线前验证检查 Agent
适用场景
- 01构建返回经过验证的 Pydantic 数据的 Agent
- 02通过带类型的依赖传入应用服务
- 03为 Agent 选择运行方式
- 04上线前检查 Agent
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ existential-birds/ beagle --skill pydantic-ai-agent-creation安装后在 Claude Code 中输入/pydantic-ai-agent-creation确认已加载。
详细介绍
创建 PydanticAI Agent
快速开始
from pydantic_ai import Agent
# Minimal agent (text output)
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello!')
print(result.output) # str
模型选择
模型字符串遵循 provider:model-name 格式:
# OpenAI
agent = Agent('openai:gpt-4o')
agent = Agent('openai:gpt-4o-mini')
# Anthropic
agent = Agent('anthropic:claude-sonnet-4-5')
agent = Agent('anthropic:claude-haiku-4-5')
# Google
agent = Agent('google-gla:gemini-2.0-flash')
agent = Agent('google-vertex:gemini-2.0-flash')
# Others: groq:, mistral:, cohere:, bedrock:, etc.
结构化输出
使用 Pydantic 模型获取经过验证且类型明确的响应:
from pydantic import BaseModel
from pydantic_ai import Agent
class CityInfo(BaseModel):
city: str
country: str
population: int
agent = Agent('openai:gpt-4o', output_type=CityInfo)
result = agent.run_sync('Tell me about Paris')
print(result.output.city) # "Paris"
print(result.output.population) # int, validated
Agent 配置
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
agent = Agent(
'openai:gpt-4o',
output_type=MyOutput, # Structured output type
deps_type=MyDeps, # Dependency injection type
instructions='You are helpful.', # Static instructions
retries=2, # Retry attempts for validation
name='my-agent', # For logging/tracing
model_settings=ModelSettings( # Provider settings
temperature=0.7,
max_tokens=1000
),
end_strategy='early', # How to handle tool calls with results
)
运行 Agent
三种执行方式:
# Async (preferred)
result = await agent.run('prompt', deps=my_deps)
# Sync (convenience)
result = agent.run_sync('prompt', deps=my_deps)
# Streaming
async with agent.run_stream('prompt') as response:
async for chunk in response.stream_output():
print(chunk, end='')
指令与系统提示词
# Instructions: Concatenated, for agent behavior
agent = Agent(
'openai:gpt-4o',
instructions='You are a helpful assistant. Be concise.'
)
# Dynamic instructions via decorator
@agent.instructions
def add_context(ctx: RunContext[MyDeps]) -> str:
return f"User ID: {ctx.deps.user_id}"
# System prompts: Static, for model context
agent = Agent(
'openai:gpt-4o',
system_prompt=['You are an expert.', 'Always cite sources.']
)
常见模式
参数化 Agent(类型安全)
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
@dataclass
class Deps:
api_key: str
user_id: int
agent: Agent[Deps, str] = Agent(
'openai:gpt-4o',
deps_type=Deps,
)
# deps is now required and type-checked
result = agent.run_sync('Hello', deps=Deps(api_key='...', user_id=123))
无依赖项(满足类型检查器要求)
# Option 1: Explicit type annotation
agent: Agent[None, str] = Agent('openai:gpt-4o')
# Option 2: Pass deps=None
result = agent.run_sync('Hello', deps=None)
验证关卡
在生产代码中使用 Agent 前,请按顺序执行以下步骤:
- 冒烟测试 — 执行
agent.run_sync('Reply with OK.')(在异步代码中执行await agent.run(...))。**通过条件:**调用顺利完成且存在result.output。 - 结构化输出 — 如果设置了
output_type,请提示模型生成符合架构的响应。通过条件:result.output是你的 Pydantic 模型的实例;如果反复验证失败,应收紧指令或调整retries,而不是立即添加功能。 - 依赖项 — 如果设置了
deps_type,请使用该类型的deps=调用run/run_sync。**通过条件:**调用通过类型检查并顺利完成(或仅因模型/API 原因失败,而不是因为缺少或错误的deps值)。
决策框架
| 场景 | 配置 |
|---|---|
| 简单文本响应 | Agent(model) |
| 结构化数据提取 | Agent(model, output_type=MyModel) |
| 需要外部服务 | 添加 deps_type=MyDeps |
| 需要验证重试 | 增加 retries=3 |
| 调试/监控 | 设置 instrument=True |
评论
支持 Markdown