Menu
CoddyTech

并行工具调用

本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 7 课,共 22 课。

当一个请求包含多个独立的问题时,模型会在一次响应中请求所有的工具调用。每次调用都是一个独立的 tool_use 块,并带有自己的 id:

messages = [{"role": "user", "content": "Look up the opening hours for Luna Cafe and Mango House"}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
calls = [block for block in response.content if block.type == "tool_use"]
for block in calls:
    print(block.name, block.input)

这会打印两行:get_hours {'place': 'Luna Cafe'} 和 get_hours {'place': 'Mango House'}。

运行每次调用,然后将所有结果一起发回:发送一条用户消息,其内容是一个包含每次调用对应一个 tool_result 的列表。API 会检查这一点。如果工具调用之后的消息缺少其中任何 id 的结果,请求就会失败并返回 400 错误,因此为每个结果单独发送一条消息的循环会在出现两次调用时立即报错。将它们一起发送还会告知模型它可以继续一次请求多次调用,从而每次都能节省一次往返。

challenge icon

挑战

中等

起始代码中的天气 agent 在查询两个城市时会出现故障:它会把每个结果放在单独的消息中发送。请修复循环内部的代码。

  1. 收集响应中的 tool_use 块,并打印 Calls: 以及调用的数量。
  2. 对每一个块运行 get_weather,并将每个 tool_result 放在同一个列表中。
  3. 将该列表作为单条 user 消息追加。

保持程序的其他部分不变。例如,对于输入 What is the weather in Oslo and Lima?,程序将输出:

Calls: 2
Answer: Here is what I found:
- Oslo: 4 C and rainy
- Lima: 19 C and misty

亲手试试

import coddy_ai as anthropic  # 在生产环境中:import anthropic

client = anthropic.Anthropic()

WEATHER = {
    "Paris": "18 C and sunny",
    "Tokyo": "22 C and cloudy",
    "Rome": "25 C and sunny",
    "Oslo": "4 C and rainy",
    "Cairo": "31 C and clear",
    "Lima": "19 C and misty",
}


def get_weather(city):
    return f"{city}: {WEATHER.get(city, 'no data')}"


TOOLS = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "The city name"}},
            "required": ["city"],
        },
    }
]

request = input()
messages = [{"role": "user", "content": request}]

response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
while response.stop_reason == "tool_use":
    messages.append({"role": "assistant", "content": response.content})
    # 修复这部分:打印 "Calls: " 和本次响应中的工具调用次数,
    # 然后在一条用户消息中发送所有结果
    for block in response.content:
        if block.type == "tool_use":
            result = {"type": "tool_result", "tool_use_id": block.id, "content": get_weather(**block.input)}
            messages.append({"role": "user", "content": [result]})
    response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)

for block in response.content:
    if block.type == "text":
        print("Answer: " + block.text)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

工具与 Agent中的所有课

自己练习: Python 在线编译器