Register and implement PydanticAI tools with proper context handling, type annotations, and docstrings. Use when adding tool capabilities to agents, implementing function calling, or creating agent actions.
根据是否需要上下文,提供两种装饰器:
python
from pydantic_ai import Agent, RunContext
agent = Agent(openai:gpt-4o)
参数:
ctx: 包含依赖项的运行上下文。
user_id: 用户ID。
return await ctx.deps.db.getuser(userid)
参数:
prices: 需要求和的价目列表。
return sum(prices)
Google 风格(默认):
python
@agent.tool_plain
async def search(query: str, limit: int = 10) -> list[str]:
搜索项目。
参数:
query: 搜索查询。
limit: 最大返回结果数。
Sphinx 风格:
python
@agent.toolplain(docstringformat=sphinx)
async def search(query: str) -> list[str]:
搜索项目。
:param query: 搜索查询。
工具可以返回多种类型:
python
@agent.tool_plain
def get_image() -> ToolReturn:
return ToolReturn(content=[ImageUrl(url=https://...)])
RunContext 提供:
python
@agent.tool
async def my_tool(ctx: RunContext[MyDeps]) -> str:
# 依赖项
db = ctx.deps.db
api = ctx.deps.api_client
# 模型信息
modelname = ctx.model.modelname
# 使用量追踪
tokensused = ctx.usage.totaltokens
# 重试信息
attempt = ctx.retry # 当前重试次数(从0开始)
maxretries = ctx.maxretries
# 消息历史
messages = ctx.messages
return 结果
动态修改每个请求的工具:
python
from pydantic_ai.tools import ToolDefinition
async def prepare_tools(
ctx: RunContext[MyDeps],
tool_defs: list[ToolDefinition]
) -> list[ToolDefinition]:
根据上下文过滤或修改工具。
if ctx.deps.user_role != admin:
# 对非管理员隐藏管理工具
return [t for t in tooldefs if not t.name.startswith(admin)]
return tool_defs
agent = Agent(openai:gpt-4o, preparetools=preparetools)
分组和组合工具:
python
from pydantic_ai import FunctionToolset, CombinedToolset
@db_tools.tool
def query_users(name: str) -> list[dict]:
按名称查询用户。
...
@db_tools.tool
def update_user(id: int, data: dict) -> bool:
更新用户数据。
...
两者都可用,但 I/O 操作推荐使用异步:
python
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 pydantic-ai-tool-system-1776126314 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 pydantic-ai-tool-system-1776126314 技能
skillhub install pydantic-ai-tool-system-1776126314
文件大小: 2.38 KB | 发布时间: 2026-4-14 09:50