返回顶部
p

pydantic-ai-tool-systemPydanticAI工具系统

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.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
136
下载量
免费
免费
0
收藏
概述
安装方式
版本历史

pydantic-ai-tool-system

PydanticAI 工具系统

工具注册

根据是否需要上下文,提供两种装饰器:

python
from pydantic_ai import Agent, RunContext

agent = Agent(openai:gpt-4o)

@agent.tool - 第一个参数必须是 RunContext

@agent.tool async def getuserdata(ctx: RunContext[MyDeps], user_id: int) -> str: 从数据库获取用户数据。

参数:
ctx: 包含依赖项的运行上下文。
user_id: 用户ID。

return await ctx.deps.db.getuser(userid)

@agent.tool_plain - 不允许有上下文参数

@agent.tool_plain def calculate_total(prices: list[float]) -> float: 计算总价。

参数:
prices: 需要求和的价目列表。

return sum(prices)

关键规则

  1. 1. @agent.tool:第一个参数必须是 RunContext[DepsType]
  2. @agent.tool_plain:不能包含 RunContext 参数
  3. 文档字符串:LLM 理解工具用途所必需
  4. Google 风格文档字符串:用于参数描述

文档字符串格式

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_info() -> str:
return 一些信息

Pydantic 模型(序列化为 JSON)

@agent.tool_plain def get_user() -> User: return User(name=John, age=30)

字典(序列化为 JSON)

@agent.tool_plain def get_data() -> dict[str, Any]: return {key: value}

自定义内容类型的 ToolReturn

from pydantic_ai import ToolReturn, ImageUrl

@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 = FunctionToolset()

@db_tools.tool
def query_users(name: str) -> list[dict]:
按名称查询用户。
...

@db_tools.tool
def update_user(id: int, data: dict) -> bool:
更新用户数据。
...

在代理中使用

agent = Agent(openai:gpt-4o, toolsets=[db_tools])

组合工具集

alltools = CombinedToolset([dbtools, api_tools])

常见错误

错误:在 tool_plain 中使用上下文

python @agent.tool_plain async def bad_tool(ctx: RunContext[MyDeps]) -> str: # 错误! ...

错误:在 tool 中缺少上下文

python @agent.tool def badtool(userid: int) -> str: # 错误! ...

错误:上下文不是第一个参数

python @agent.tool def badtool(userid: int, ctx: RunContext[MyDeps]) -> str: # 错误! ...

异步与同步

两者都可用,但 I/O 操作推荐使用异步:

python

异步(I/O 操作推荐)


@agent.tool
async def fetch_data(ctx: RunContext[Deps]) -> str:
return await ctx.deps.client.get(/data)

同步(适合 CPU 密集型操作)

@agent.tool_plain def compute(x: int, y: int) -> int: return x * y

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 pydantic-ai-tool-system-1776126314 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 pydantic-ai-tool-system-1776126314 技能

通过命令行安装

skillhub install pydantic-ai-tool-system-1776126314

下载

⬇ 下载 pydantic-ai-tool-system v1.0.0(免费)

文件大小: 2.38 KB | 发布时间: 2026-4-14 09:50

v1.0.0 最新 2026-4-14 09:50
- Initial release of pydantic-ai-tool-system.
- Provides decorators for registering tools with or without context handling.
- Enforces proper type annotations and Google/Sphinx-style docstrings for better LLM integration.
- Supports tool return types including strings, Pydantic models, dicts, and custom content types.
- Introduces prepare functions for dynamic tool modification based on context.
- Adds tools grouping and composition via toolsets.
- Documents best practices and common mistakes for tool implementation.

Archiver·手机版·闲社网·闲社论坛·智能体自动化市场· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2026 闲社网·AI智能体论坛·AI自动化解决方案·http://xianshe.com

p2p_official_large
返回顶部