字
字节笔记本
2026年6月21日
hermes教程-标题:添加工具
API中转
¥120
概述
添加一个工具涉及 2 个文件:
tools/your_tool.py— 处理函数、schema、检查函数、registry.register()调用toolsets.py— 将工具名称添加到_HERMES_CORE_TOOLS(或特定的工具集)
任何包含顶层 registry.register() 调用的 tools/*.py 文件都会在启动时自动发现——无需手动导入列表。
步骤 1:创建内置工具文件
每个工具文件都遵循相同的结构:
python
## 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 的工具调用参数
步骤 2:将内置工具添加到工具集
在 toolsets.py 中,添加工具名称:
python
## 如果它应该在所有平台(CLI + 消息)上可用:
_HERMES_CORE_TOOLS = [
...
"weather", # <-- 在此处添加
]
## 或者创建一个新的独立工具集:
"weather": {
"description": "Weather lookup tools",
"tools": ["weather"],
"includes": []
},步骤 3:添加发现导入(不再需要)
带有顶层 registry.register() 调用的工具模块会被 tools/registry.py 中的 discover_builtin_tools() 自动发现。无需维护手动导入列表——只需在 tools/ 中创建文件,启动时就会被自动识别。
异步处理函数
如果你的处理函数需要异步代码,请使用 is_async=True 标记:
python
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 会自动调用 _run_async()
)注册表会透明地处理异步桥接——你无需自己调用 asyncio.run()。
需要 task_id 的处理函数
管理每个会话状态的工具通过 **kwargs 接收 task_id:
python
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,
)代理循环拦截的工具
某些工具(todo、memory、session_search、delegate_task)需要访问每个会话的代理状态。这些工具在到达注册表之前会被 run_agent.py 拦截。注册表仍然保存它们的 schema,但如果绕过拦截,dispatch() 会返回一个回退错误。
可选:设置向导集成
如果你的工具需要 API 密钥,请将其添加到 hermes_cli/config.py:
python
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,
},
}检查清单
- 创建了工具文件,包含处理函数、schema、检查函数和注册
- 已添加到
toolsets.py中的相应工具集 - 确认这确实应该是一个内置/核心工具,而不是插件
- 处理函数返回 JSON 字符串,错误以
{"error": "..."}形式返回 - 可选:在
hermes_cli/config.py的OPTIONAL_ENV_VARS中添加了 API 密钥 - 可选:已添加到
toolset_distributions.py以支持批处理 - 使用
hermes chat -q "Use the weather tool for London"进行了测试
分享: