加载中
加载中

在使用 Claude 的工具调用能力时,您可能会注意到 Claude 可以在单条助手消息中包含多个工具使用代码块。这使 Claude 能够并行运行多个工具,而不必为每个工具分别发起请求。然而,在实践中要让 Claude 稳定地做到这一点可能颇具挑战性。

多次工具调用的问题

假设您让 Claude 为同一日期设置两个提醒事项。理论上,Claude 应该能够返回一条包含两个工具使用代码块的单一响应——每个提醒事项对应一个。但实际上,Claude 往往会改为发送多个单独的响应。

理想的交互方式:一条助手消息中包含两个针对 1 月 1 日的 set_reminder 工具使用,分别是"Taxes due"和"Doctors appointment"。

通常发生的情况是,Claude 先发起第一个工具调用,等待结果返回后,再在后续消息中发起第二个工具调用。这会造成不必要的来回通信,而这些操作本可以同时完成。

Claude 用一次 batch_tool 调用回应我们服务器发来的双提醒请求:为"Dr appt"和"Taxes due"设置 set_reminder。

批处理工具方案

解决方案是实现一个"批处理工具"——一种特殊的工具,它接受一个由其他工具调用组成的列表,以便同时执行。这本质上是一种巧妙的变通方法,促使 Claude 一次性发起多个工具调用。

Claude 用一次 batch_tool 调用回应我们服务器发来的双提醒请求:为"Dr appt"和"Taxes due"设置 set_reminder。

它的工作方式如下:

  • 您定义一个批处理工具模式(schema),告诉 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 思考哪些操作可以并行化,并更高效地执行它们。