Claude 提出工具调用之后,谁来执行?
查看完整题解
参考回答
直接回答
客户端工具由应用声明名称、用途和输入结构。Claude 返回 tool_use 后,由服务端核对参数与权限,运行允许的工具。随后用带同一个 tool_use_id 的 tool_result 把结果交回 Claude,让它继续回答。
讲清原理
客户端工具的结果消息紧跟返回工具调用的助手消息,结果块放在 user 内容的前面。出错时可在结果块标 is_error。服务端托管工具有另外的执行方式。对自己的应用,工具输入依然是外部数据,需要严格验证。
例子与易错点
下面用一个只读订单查询演示如何根据调用 ID 回传结果。测试也检查同一个用户不能读取别人的订单。
from copy import deepcopy
orders = {"O1": ("customer-A", "已发货"), "O2": ("customer-B", "处理中")}
def answer_tool(tool_use, customer):
order_id = tool_use["input"].get("order_id")
row = orders.get(order_id) if isinstance(order_id, str) else None
allowed = tool_use["name"] == "lookup_order" and row and row[0] == customer
return {"role": "user", "content": [{
"type": "tool_result", "tool_use_id": tool_use["id"],
"content": row[1] if allowed else "订单不可读", "is_error": not allowed,
}]}
call = {"type": "tool_use", "id": "toolu_demo", "name": "lookup_order",
"input": {"order_id": "O1"}}
other = deepcopy(call)
other["id"], other["input"]["order_id"] = "toolu_other", "O2"
result = answer_tool(call, "customer-A")["content"][0]
assert (result["tool_use_id"], result["content"], result["is_error"]) == ("toolu_demo", "已发货", False)
assert answer_tool(other, "customer-A")["content"][0]["is_error"]
print("本人订单可读,其他订单拒绝")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。