跳至主要內容

指南

自訂工具

由你的客戶端執行的工具,這一輪等你提交結果。

自訂工具在建立會話時定義,由你的客戶端執行。Agent 調用自訂工具時,平台記錄一條 agent.custom_tool_use 事件並暫停本輪;客戶端提交結果後,本輪繼續執行。

自訂工具與 MCP 伺服器的選用:

場景選用
工具可以部署為公網可存取的服務MCP 伺服器。由平台直接調用,本輪不暫停
工具依賴客戶端本機的狀態、內網資源、終端用戶的裝置或人工確認自訂工具

定義

建立會話時在 custom_tools 中定義:

curl -s "$AXON_API/sessions" \
  -H "Authorization: Bearer $AXON_KEY" -H "Content-Type: application/json" \
  -d '{
        "model_id": "deepseek-v4-flash",
        "custom_tools": [{
          "name": "get_cart",
          "description": "查詢當前用戶購物車裡的商品和數量。",
          "input_schema": {"type": "object", "properties": {"user_id": {"type": "string"}}, "required": ["user_id"]}
        }]
      }'
  • name:須符合 ^[A-Za-z0-9_-]{1,64}$,在會話內唯一。不能與 Agent 自帶工具同名(bash、deliver_file、edit_file、glob、grep、read_file、read_image、todo_write、use_skill、web_fetch、web_search、write_file),也不能以 mcp__ 或 mcp_resource__ 開頭。
  • description:1–4000 字元。Agent 根據名稱、描述和參數決定何時調用以及如何填寫參數,請寫明用途、參數含義和返回內容。
  • input_schema:參數的 JSON Schema(draft 2020-12),須為合法的 "type": "object" schema,序列化為 JSON 後不超過 32 KiB。
  • 每個會話最多 64 個自訂工具,建立後不可修改。不符合以上規則時返回 422 validation_error。

調用流程

agent.custom_tool_use → turn.requires_action → 提交 user.custom_tool_result → 本輪繼續 → … → turn.completed
  1. Agent 調用自訂工具時,事件串流推送 agent.custom_tool_use,其中 name 為工具名,input 為參數,事件的 id(evt_…)標識這次調用。Agent 可以一次調用多個工具。
  2. 隨後本輪以 turn.requires_action 暫停,required_actions 列出等待結果的調用,會話和輪次的 status 變為 requires_action。turn.requires_action 不是終止事件。
  3. 客戶端執行 required_actions 中的每個調用,透過發送事件提交 user.custom_tool_result。須在收到 turn.requires_action 之後提交,之前提交返回 409 turn_not_waiting。
  4. 所有調用都有結果後,本輪重新排隊並繼續執行。一輪在終止前可以多次暫停。
{"id": "evt_3c8a…", "seq": 3, "type": "agent.custom_tool_use", "turn_id": "turn_3f2a…", "created_at": "…",
 "name": "get_cart", "input": {"user_id": "u_42"}}

{"id": "evt_51d0…", "seq": 4, "type": "turn.requires_action", "turn_id": "turn_3f2a…", "created_at": "…",
 "required_actions": [{"type": "custom_tool_result", "tool_use_id": "evt_3c8a…"}]}

提交結果:

curl -s "$AXON_API/sessions/$SESSION/events" \
  -H "Authorization: Bearer $AXON_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"events": [{"type": "user.custom_tool_result", "tool_use_id": "evt_3c8a…",
                   "content": "A1 × 2,B7 × 1", "is_error": false}]}'

在客戶端執行

以下範例可直接執行。它實現一個網店客服 Agent,帶兩個在本機執行的自訂工具:get_order_status 從本機數據中查詢訂單,代表你自己的系統;request_refund 在終端機請求人工批准,批准前本輪保持等待。

custom_tools.py網店客服範例:查詢訂單,退款需人工批准。依賴 httpx。下載
pip install httpx
export AXON_API="https://agent.hkgai.net/open/api/v1"
export AXON_KEY="sk-axon-..."                    # 你的 API Key
python custom_tools.py                            # 互動對話,空行結束

執行後可以輸入「訂單 A1001 到哪了?」或「訂單 A1002 買錯了,幫我退款」。

腳本的核心邏輯如下:收到 agent.custom_tool_use 時記錄調用,收到 turn.requires_action 時執行並提交結果。API、TERMINAL 和 follow() 的定義見客戶端範例。

import uuid

TOOLS = {"get_cart": lambda args: f"A1 × 2,B7 × 1(用戶 {args['user_id']})"}   # 你自己的實現


def ask_with_tools(client, session_id, content):
    """發送一條訊息,在本機執行 Agent 調用的自訂工具並提交結果。返回終止事件。"""
    response = client.post(f"{API}/sessions/{session_id}/messages", json={"content": content})
    response.raise_for_status()
    sent = response.json()
    calls = {}                                         # tool_use_id → 調用
    for event, data in follow(client, session_id, since=sent["seq"]):
        if data["turn_id"] != sent["turn_id"]:
            continue
        if event == "agent.message.delta":
            print(data["content"], end="", flush=True)
        elif event == "agent.custom_tool_use":
            calls[data["id"]] = data
        elif event == "turn.requires_action":         # 不是終止事件:提交結果後本輪繼續
            results = [run_tool(calls[action["tool_use_id"]]) for action in data["required_actions"]]
            client.post(f"{API}/sessions/{session_id}/events", json={"events": results},
                        headers={"Idempotency-Key": str(uuid.uuid4())}).raise_for_status()
        elif event in TERMINAL:
            return data


def run_tool(call):
    """執行一次調用,返回對應的 user.custom_tool_result。"""
    try:
        text, is_error = TOOLS[call["name"]](call["input"]), False
    except Exception as exc:                           # 執行失敗也提交結果,Agent 據此調整
        text, is_error = f"執行失敗:{exc}", True
    return {"type": "user.custom_tool_result", "tool_use_id": call["id"],
            "content": text, "is_error": is_error}

規則

  • 每個 agent.custom_tool_use 至多對應一個結果,提交時 tool_use_id 填該事件的 id。只需為 turn.requires_action 列出的調用提交結果。參數不合法、同一批調用中先執行的工具出錯,或本輪在暫停前被取消時,平台會為該調用寫入 agent.tool_result,無須提交。
  • 提交結果時可能返回的錯誤:tool_use_id 不是本會話中未結束輪次的自訂工具調用時,返回 422 unknown_tool_use(格式不合法時返回 422 validation_error);該調用已有結果時,返回 409 tool_use_answered;本輪尚未暫停時,返回 409 turn_not_waiting。網絡錯誤後重試時,使用相同的 Idempotency-Key,將返回首次請求的回應。
  • content 為字串,可省略,預設為 "",最長 100,000 字元。執行失敗時將 is_error 設為 true,並在 content 中說明原因,Agent 會據此調整參數重試或告知用戶。
  • 等待期間本輪不佔用執行資源,沒有時限,也不計入項目同時排隊和執行的輪次上限。
  • 等待期間發送的 user.message 排在本輪之後;user.interrupt 或取消執行會立即取消本輪,並記錄 turn.cancelled。
  • 本輪被取消後,尚未提交結果的調用作廢。平台不會為其寫入 user.custom_tool_result,後續輪次中的 Agent 將其視為未獲得結果的失敗調用。