Implement dependency injection in PydanticAI agents using RunContext and deps_type. Use when agents need database connections, API clients, user context, or any external resources.
依赖通过 RunContext 流转:
python
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
@dataclass
class Deps:
db: DatabaseConn
api_client: HttpClient
user_id: int
agent = Agent(
openai:gpt-4o,
deps_type=Deps, # 用于静态分析的类型
)
@agent.tool
async def getuserbalance(ctx: RunContext[Deps]) -> float:
获取当前用户的账户余额。
return await ctx.deps.db.getbalance(ctx.deps.userid)
使用数据类或 Pydantic 模型:
python
from dataclasses import dataclass
from pydantic import BaseModel
在工具和指令中:
python
@agent.tool
async def query_database(ctx: RunContext[Deps], query: str) -> list[dict]:
运行数据库查询。
return await ctx.deps.db.execute(query)
@agent.instructions
async def addusercontext(ctx: RunContext[Deps]) -> str:
user = await ctx.deps.db.getuser(ctx.deps.userid)
return f用户名:{user.name},角色:{user.role}
@agent.system_prompt
def add_permissions(ctx: RunContext[Deps]) -> str:
return f用户拥有权限:{ctx.deps.permissions}
使用泛型实现完整类型检查:
python
当不需要依赖时:
python
python
from dataclasses import dataclass
from httpx import AsyncClient
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext
@dataclass
class WeatherDeps:
client: AsyncClient
api_key: str
class WeatherReport(BaseModel):
location: str
temperature: float
conditions: str
agent: Agent[WeatherDeps, WeatherReport] = Agent(
openai:gpt-4o,
deps_type=WeatherDeps,
output_type=WeatherReport,
instructions=你是一个天气助手。,
)
@agent.tool
async def get_weather(
ctx: RunContext[WeatherDeps],
city: str
) -> dict:
获取指定城市的天气数据。
response = await ctx.deps.client.get(
fhttps://api.weather.com/{city},
headers={Authorization: ctx.deps.api_key}
)
return response.json()
async def main():
async with AsyncClient() as client:
deps = WeatherDeps(client=client, api_key=secret)
result = await agent.run(伦敦的天气怎么样?, deps=deps)
print(result.output.temperature)
python
from pydantic_ai.models.test import TestModel
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 pydantic-ai-dependency-injection-1776060480 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 pydantic-ai-dependency-injection-1776060480 技能
skillhub install pydantic-ai-dependency-injection-1776060480
文件大小: 2.42 KB | 发布时间: 2026-4-17 15:51