載入中
當您使用 Claude 的工具呼叫功能時,您可能會注意到 Claude 可以在單一助手訊息中包含多個工具使用區塊。這讓 Claude 能夠平行執行多個工具,而不必為每個工具分別發出請求。然而,在實務上,要讓 Claude 穩定地做到這一點可能頗具挑戰性。
多次工具呼叫的問題
假設您要求 Claude 為同一天設定兩個提醒。理論上,Claude 應該能夠回傳一則包含兩個工具使用區塊的單一回應——每個提醒各一個。但實際上,Claude 通常會改為傳送兩則獨立的回應。

通常發生的情況是,Claude 先進行第一次工具呼叫,等待結果,然後在後續訊息中進行第二次工具呼叫。這會造成不必要的來回通訊,而這些操作其實原本可以同時完成。

批次工具解決方案
解決方案是實作一個「批次工具」——這是一種特殊工具,它接受一份其他工具呼叫的清單,並同時執行它們。這本質上是一種變通方法,誘使 Claude 一次進行多個工具呼叫。

其運作方式如下:
- 您定義一個批次工具架構,告訴 Claude 它可以平行執行多個其他工具
- Claude 不直接呼叫工具,而是呼叫批次工具並附上一份工具調用清單
- 您的程式碼處理此清單並執行每個工具呼叫
- 您將合併後的結果回傳給 Claude
實作批次工具架構
批次工具架構定義了 Claude 想要執行多個工具時應如何建構其請求:
python
batch_tool_schema = {
"name": "batch_tool",
"description": "Invoke multiple other tool calls simultaneously",
"input_schema": {
"type": "object",
"properties": {
"invocations": {
"type": "array",
"description": "The tool calls to invoke",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the tool to invoke"
},
"arguments": {
"type": "object",
"description": "The arguments to pass to the tool"
}
}
}
}
}
}
}處理批次工具呼叫
當 Claude 使用批次工具時,您需要處理調用清單並執行每一項。以下是實作方式:
python
def run_batch(invocations=[]):
batch_output = []
for invocation in invocations:
name = invocation["name"]
args = invocation["arguments"]
tool_output = run_tool(name, args)
batch_output.append({
"tool_name": name,
"output": tool_output
})
return batch_output您還需要更新主要工具路由函式,以處理批次工具呼叫:
python
def run_tool(tool_name, tool_input):
if tool_name == "get_current_datetime":
return get_current_datetime(**tool_input)
elif tool_name == "add_duration_to_datetime":
return add_duration_to_datetime(**tool_input)
elif tool_name == "set_reminder":
return set_reminder(**tool_input)
elif tool_name == "batch_tool":
return run_batch(**tool_input)結果
在實作了批次工具之後,Claude 更有可能將相關操作整合在一起。Claude 不再為每個提醒分別發出請求,而是會使用批次工具同時設定兩個提醒。
對話流程變得更加簡潔——使用者發出一則請求,Claude 回應一則包含批次工具呼叫的訊息,接著再以一則包含所有結果的後續訊息完成。這減少了延遲,並讓您的應用程式更有效率。
雖然這看起來像是一種變通方法(確實如此),但批次工具模式是一種有效的方式,可以促使 Claude 思考哪些操作可以平行化,並更有效率地執行它們。