跳到主要内容

添加工具

在编写工具之前,请问自己:这应该是一个 技能 吗?

当某个功能可以表示为指令 + shell 命令 + 现有工具(如 arXiv 搜索、git 工作流、Docker 管理、PDF 处理)时,请将其作为 技能

当需要与 API 密钥进行端到端集成、自定义处理逻辑、二进制数据处理或流式处理(如浏览器自动化、TTS、视觉分析)时,请将其作为 工具

概述

添加一个工具需要修改 3 个文件

  1. tools/your_tool.py — 处理函数、模式、检查函数、registry.register() 调用
  2. toolsets.py — 将工具名称添加到 _HERMES_CORE_TOOLS(或特定工具集)
  3. model_tools.py — 将 "tools.your_tool" 添加到 _discover_tools() 列表中

第一步:创建工具文件

每个工具文件都遵循相同的结构:

# tools/weather_tool.py
"""Weather Tool -- look up current weather for a location."""

import json
import os
import logging

logger = logging.getLogger(__name__)


# --- Availability check ---

def check_weather_requirements() -> bool:
"""Return True if the tool's dependencies are available."""
return bool(os.getenv("WEATHER_API_KEY"))


# --- Handler ---

def weather_tool(location: str, units: str = "metric") -> str:
"""Fetch weather for a location. Returns JSON string."""
api_key = os.getenv("WEATHER_API_KEY")
if not api_key:
return json.dumps({"error": "WEATHER_API_KEY not configured"})
try:
# ... call weather API ...
return json.dumps({"location": location, "temp": 22, "units": units})
except Exception as e:
return json.dumps({"error": str(e)})


# --- Schema ---

WEATHER_SCHEMA = {
"name": "weather",
"description": "Get current weather for a location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name or coordinates (e.g. 'London' or '51.5,-0.1')"
},
"units": {
"type": "string",
"enum": ["metric", "imperial"],
"description": "Temperature units (default: metric)",
"default": "metric"
}
},
"required": ["location"]
}
}


# --- Registration ---

from tools.registry import registry

registry.register(
name="weather",
toolset="weather",
schema=WEATHER_SCHEMA,
handler=lambda args, **kw: weather_tool(
location=args.get("location", ""),
units=args.get("units", "metric")),
check_fn=check_weather_requirements,
requires_env=["WEATHER_API_KEY"],
)

关键规则

重要
  • 处理函数 必须 返回 JSON 字符串(通过 json.dumps()),不能返回原始字典
  • 错误 必须{"error": "message"} 形式返回,不能抛出异常
  • check_fn 在构建工具定义时被调用 —— 如果返回 False,该工具将被静默排除
  • handler 接收 (args: dict, **kwargs),其中 args 是 LLM 工具调用的参数

第二步:添加到工具集

toolsets.py 中添加工具名称:

# If it should be available on all platforms (CLI + messaging):
_HERMES_CORE_TOOLS = [
...
"weather", # <-- add here
]

# Or create a new standalone toolset:
"weather": {
"description": "Weather lookup tools",
"tools": ["weather"],
"includes": []
},

第三步:添加发现导入

model_tools.py 中将模块添加到 _discover_tools() 列表中:

def _discover_tools():
_modules = [
...
"tools.weather_tool", # <-- add here
]

此导入会触发工具文件末尾的 registry.register() 调用。

异步处理函数

如果处理函数需要异步代码,请使用 is_async=True 标记:

async def weather_tool_async(location: str) -> str:
async with aiohttp.ClientSession() as session:
...
return json.dumps(result)

registry.register(
name="weather",
toolset="weather",
schema=WEATHER_SCHEMA,
handler=lambda args, **kw: weather_tool_async(args.get("location", "")),
check_fn=check_weather_requirements,
is_async=True, # registry calls _run_async() automatically
)

注册表会透明地处理异步桥接 —— 你无需自行调用 asyncio.run()

需要 task_id 的处理函数

管理会话级状态的工具会通过 **kwargs 接收 task_id

def _handle_weather(args, **kw):
task_id = kw.get("task_id")
return weather_tool(args.get("location", ""), task_id=task_id)

registry.register(
name="weather",
...
handler=_handle_weather,
)

被代理循环拦截的工具

某些工具(如 todomemorysession_searchdelegate_task)需要访问会话级代理状态。这些工具在到达注册表之前会被 run_agent.py 拦截。注册表仍然保存它们的模式,但如果拦截被绕过,dispatch() 将返回一个回退错误。

可选:设置向导集成

如果工具需要 API 密钥,请将其添加到 hermes_cli/config.py

OPTIONAL_ENV_VARS = {
...
"WEATHER_API_KEY": {
"description": "Weather API key for weather lookup",
"prompt": "Weather API key",
"url": "https://weatherapi.com/",
"tools": ["weather"],
"password": True,
},
}

检查清单

  • 已创建工具文件,包含处理函数、模式、检查函数和注册调用
  • 已在 toolsets.py 中添加到适当的工具集中
  • 已在 model_tools.py 中添加发现导入
  • 处理函数返回 JSON 字符串,错误以 {"error": "..."} 形式返回
  • 可选:已将 API 密钥添加到 hermes_cli/config.py 中的 OPTIONAL_ENV_VARS
  • 可选:已添加到 toolset_distributions.py 以支持批量处理
  • 已使用 hermes chat -q "Use the weather tool for London" 测试