pydantic-ai-agent-creation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCreating PydanticAI Agents
创建PydanticAI Agent
Quick Start
快速开始
python
from pydantic_ai import Agentpython
from pydantic_ai import AgentMinimal agent (text output)
Minimal agent (text output)
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello!')
print(result.output) # str
undefinedagent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello!')
print(result.output) # str
undefinedModel Selection
模型选择
Model strings follow format:
provider:model-namepython
undefined模型字符串遵循格式:
provider:model-namepython
undefinedOpenAI
OpenAI
agent = Agent('openai:gpt-4o')
agent = Agent('openai:gpt-4o-mini')
agent = Agent('openai:gpt-4o')
agent = Agent('openai:gpt-4o-mini')
Anthropic
Anthropic
agent = Agent('anthropic:claude-sonnet-4-5')
agent = Agent('anthropic:claude-haiku-4-5')
agent = Agent('anthropic:claude-sonnet-4-5')
agent = Agent('anthropic:claude-haiku-4-5')
agent = Agent('google-gla:gemini-2.0-flash')
agent = Agent('google-vertex:gemini-2.0-flash')
agent = Agent('google-gla:gemini-2.0-flash')
agent = Agent('google-vertex:gemini-2.0-flash')
Others: groq:, mistral:, cohere:, bedrock:, etc.
Others: groq:, mistral:, cohere:, bedrock:, etc.
undefinedundefinedStructured Outputs
结构化输出
Use Pydantic models for validated, typed responses:
python
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使用Pydantic模型获取经过验证的类型化响应:
python
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, validatedAgent Configuration
Agent配置
python
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
)python
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
)Running Agents
运行Agent
Three execution methods:
python
undefined三种执行方式:
python
undefinedAsync (preferred)
Async (preferred)
result = await agent.run('prompt', deps=my_deps)
result = await agent.run('prompt', deps=my_deps)
Sync (convenience)
Sync (convenience)
result = agent.run_sync('prompt', deps=my_deps)
result = agent.run_sync('prompt', deps=my_deps)
Streaming
Streaming
async with agent.run_stream('prompt') as response:
async for chunk in response.stream_output():
print(chunk, end='')
undefinedasync with agent.run_stream('prompt') as response:
async for chunk in response.stream_output():
print(chunk, end='')
undefinedInstructions vs System Prompts
指令与系统提示词
python
undefinedpython
undefinedInstructions: Concatenated, for agent behavior
Instructions: Concatenated, for agent behavior
agent = Agent(
'openai:gpt-4o',
instructions='You are a helpful assistant. Be concise.'
)
agent = Agent(
'openai:gpt-4o',
instructions='You are a helpful assistant. Be concise.'
)
Dynamic instructions via decorator
Dynamic instructions via decorator
@agent.instructions
def add_context(ctx: RunContext[MyDeps]) -> str:
return f"User ID: {ctx.deps.user_id}"
@agent.instructions
def add_context(ctx: RunContext[MyDeps]) -> str:
return f"User ID: {ctx.deps.user_id}"
System prompts: Static, for model context
System prompts: Static, for model context
agent = Agent(
'openai:gpt-4o',
system_prompt=['You are an expert.', 'Always cite sources.']
)
undefinedagent = Agent(
'openai:gpt-4o',
system_prompt=['You are an expert.', 'Always cite sources.']
)
undefinedCommon Patterns
常见模式
Parameterized Agent (Type-Safe)
参数化Agent(类型安全)
python
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,
)python
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
deps is now required and type-checked
result = agent.run_sync('Hello', deps=Deps(api_key='...', user_id=123))
undefinedresult = agent.run_sync('Hello', deps=Deps(api_key='...', user_id=123))
undefinedNo Dependencies (Satisfy Type Checker)
无依赖项(满足类型检查器要求)
python
undefinedpython
undefinedOption 1: Explicit type annotation
Option 1: Explicit type annotation
agent: Agent[None, str] = Agent('openai:gpt-4o')
agent: Agent[None, str] = Agent('openai:gpt-4o')
Option 2: Pass deps=None
Option 2: Pass deps=None
result = agent.run_sync('Hello', deps=None)
undefinedresult = agent.run_sync('Hello', deps=None)
undefinedDecision Framework
决策框架
| Scenario | Configuration |
|---|---|
| Simple text responses | |
| Structured data extraction | |
| Need external services | Add |
| Validation retries needed | Increase |
| Debugging/monitoring | Set |
| 场景 | 配置 |
|---|---|
| 简单文本响应 | |
| 结构化数据提取 | |
| 需要外部服务 | 添加 |
| 需要验证重试 | 增加 |
| 调试/监控 | 设置 |