H繁中版
<!-- Source: https://hermesbible.com/docs/developer-guide/adding-tools -->

在撰寫工具之前,先問自己:這應該是一個技能嗎?

警告——僅限內建核心工具

本頁是用於向儲存庫本身新增內建 Hermes 工具。 如果你想要一個個人的、專案本地的或以其他方式自訂的工具, 而不修改 Hermes 核心,請改用外掛路徑:

對於大多數自訂工具的建構,預設使用外掛。只有在你明確想要在 tools/toolsets.py 中發行新的內建工具時才遵循本頁。

當能力可以表達為指令 + shell 命令 + 現有工具時,製作成技能(arXiv 搜尋、git 工作流程、Docker 管理、PDF 處理)。

當需要端到端整合 API 金鑰、自訂處理邏輯、二進位資料處理或串流時,製作成工具(瀏覽器自動化、TTS、視覺分析)。

概覽

新增工具涉及2 個檔案

  1. tools/your_tool.py — 處理器、schema、check 函數、registry.register() 呼叫
  2. toolsets.py — 將工具名稱加入 _HERMES_CORE_TOOLS(或特定工具集)

任何帶有頂層 registry.register() 呼叫的 tools/*.py 檔案在啟動時會被自動發現——不需要手動匯入清單。

步驟 1:建立內建工具檔案

每個工具檔案遵循相同的結構:

# 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 中加入工具名稱:

# 若它應該在所有平台上可用(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

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,  # 註冊表自動呼叫 _run_async()
)

註冊表透明地處理非同步橋接——你永遠不需要自己呼叫 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,
)

Agent 迴圈攔截的工具

部分工具(todomemorysession_searchdelegate_task)需要存取每會話的 Agent 狀態。它們在到達註冊表之前被 run_agent.py 攔截。註冊表仍持有它們的 schema,但 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,
    },
}

檢查清單

  • 工具檔案已建立,包含處理器、schema、check 函數和註冊
  • 已加入 toolsets.py 中的適當工具集
  • 已確認這確實應該是內建/核心工具而非外掛
  • 處理器回傳 JSON 字串,錯誤以 {"error": "..."} 回傳
  • 選用:API 金鑰已加入 hermes_cli/config.pyOPTIONAL_ENV_VARS
  • 選用:已加入 toolset_distributions.py 用於批次處理
  • 已使用 hermes chat -q "Use the weather tool for London" 測試


新增供應商