返回工具结果
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 3 课,共 22 课。
在你运行工具后,模型仍需要看到结果才能做出回答。向对话中添加两个轮次并再次调用:包含模型完整 content(包含其工具调用)的 assistant 轮次,以及包含 tool_result 块的 user 轮次。该块的 tool_use_id 是调用的 id,其 content 是你的函数返回的内容。
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": call.id, "content": "Lima: 14:05"}],
})
final = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=tools, messages=messages)再次发送相同的 tools:模型可能需要另一次调用。API 会检查配对:下一条消息中没有 tool_result 的 tool_use,或者结果的 id 无法匹配任何调用,都会被拒绝并抛出 BadRequestError。替身随后会根据结果使用 Here is what I found: ... 进行回答;而真实模型则会围绕它写出自己的句子。
挑战
中等完成这个完整流程:运行工具,将其结果发送回去,并打印模型的回答。初始代码发送了问题,并将工具调用保存在 call 中。
- 使用调用的输入中的
day调用get_opening_hours,并打印Result:和它的返回值。 - 追加包含
response.content的助手轮次,然后追加包含一个针对call.id的tool_result块(内容为该结果)的用户轮次。 - 使用相同的模型、
max_tokens、工具和消息再次调用模型。 - 打印
Answer:和文本块的文本。
例如,对于输入 When are you open on Saturday?,程序会输出:
Result: Saturday: 10 am to 4 pm
Answer: Here is what I found: Saturday: 10 am to 4 pm亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
HOURS = {"monday": "9 am to 6 pm", "friday": "9 am to 8 pm", "saturday": "10 am to 4 pm", "sunday": "closed"}
def get_opening_hours(day):
return f"{day}: {HOURS.get(day.lower(), '9 am to 6 pm')}"
hours_tool = {
"name": "get_opening_hours",
"description": "Get the shop's opening hours for a day of the week",
"input_schema": {
"type": "object",
"properties": {"day": {"type": "string", "description": "A day of the week"}},
"required": ["day"],
},
}
question = input()
messages = [{"role": "user", "content": question}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=[hours_tool], messages=messages)
call = next(block for block in response.content if block.type == "tool_use")
# 1. 运行工具并打印 "Result: " 以及它的返回值。
# 2. 添加 assistant 轮次,然后添加包含 tool_result 的 user 轮次。
# 3. 使用相同的工具再次询问,并打印 "Answer: " 以及回复的文本。
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
工具与 Agent中的所有课
自己练习: Python 在线编译器