课程大纲 第 117 课,共 250 课 · 调用真正的 LLM
调用真正的 LLM

工具调用的往返

工具调用是一支两步的舞。你把用户的消息连同工具 schema 一起发出去;模型用一个 tool_use 块回答,说"用 {city: 'Paris'} 调用 get_weather";你的代码运行那个函数,并把答案作为 tool_result 送回去;然后模型用它写出最终的回复。这一课构建中间那一步:模型的请求变成一次真正的 Python 调用,结果被打包好准备送回去。

下面是真实的循环(仅作示意,我们不访问网络):

resp = client.messages.create(model="claude-opus-5-5", max_tokens=1024,
                              tools=TOOLS, messages=history)
# resp.stop_reason == "tool_use". The model may ask for SEVERAL tools at once:
# append its turn once, run every tool_use block, and send ALL the results
# back together in ONE user message.
history.append({"role": "assistant", "content": resp.content})
results = []
for block in resp.content:
    if block.type == "tool_use":
        result = TOOLS_BY_NAME[block.name](**block.input)
        results.append({"type": "tool_result", "tool_use_id": block.id,
                        "content": str(result)})
history.append({"role": "user", "content": results})
final = client.messages.create(model="claude-opus-5-5", max_tokens=1024,
                               tools=TOOLS, messages=history)

不容商量的细节:你用模型给出的参数调用模型指名的那个函数;你在 tool_result 里回传它的 tool_use_id,让模型能把每个答案和它的请求对上;当一轮要求好几个工具时,你在同一条用户消息里返回所有结果(把它们拆到多条消息里,会教模型不再并行地请求)。在这一课里你处理最简单的情况,一次工具调用;第 4 课处理多次。我们把响应建模成一个普通字典,这样它可以离线运行:

{"content": [{"type": "tool_use", "id": "toolu_1",
              "name": "get_weather", "input": {"city": "Paris"}}],
 "stop_reason": "tool_use"}

你要构建 run_tool_call(resp, tools),其中 tools 把工具名映射到 Python 函数。它必须:

  • 在 resp["content"] 里找到第一个 type 为 "tool_use" 的块。
  • 查找 tools[name],并以这个块的 input 作为关键字参数调用它:tools[name](**block["input"])。如果名字不在 tools 里,就抛出异常(KeyError 或 ValueError):永远不要运行一个模型幻想出来的工具。
  • 返回把结果带回去的后续用户消息:
{"role": "user",
 "content": [{"type": "tool_result",
              "tool_use_id": <the block's id>,
              "content": str(result)}]}

用 str(result) 把结果转成字符串:tool_result 的内容以文本形式传输。把它构建成这样:两次不同的工具调用(不同的名字和输入)产生两条不同的 tool_result 消息,原来的 tool_use_id 被回传,而未知的工具名会抛出异常。

轮到你了

写 run_tool_call(resp, tools)。在 resp["content"] 里找到第一个 {"type": "tool_use", "id", "name", "input"} 块,调用 tools[name](**input),并返回后续消息 {"role": "user", "content": [{"type": "tool_result", "tool_use_id": <id>, "content": str(result)}]}。工具名不在 tools 里时抛出异常。

发现这节课有问题?报告它 · 就这节课提问

这个练习即将开放

完成它前面的那一课,这一课就会解锁。整门课程免费,无需账号,而且你现在就可以阅读这节课。