8.Implementing multiple turns
此文档由 学习AI的1000天 翻译制作(抖音,B站,YouTube)
邮箱: szqshan@gmail.com | 微信: szqshan
网址: www.xueai.org
==================================================
构建一个带有工具的对话系统需要实现一个循环,持续调用Claude直到它停止请求使用工具。当Claude不再请求工具时,这表明它已经准备好向用户提供最终回复。
检测工具请求
判断Claude是否想要使用工具的关键在于响应消息的stop_reason字段。当Claude决定需要调用工具时,该字段会被设置为"tool_use"。这为我们提供了一种简洁的方式来检查是否需要继续对话循环:
if response.stop_reason != "tool_use":
break # Claude已完成,不再需要工具
对话循环
主要的对话函数遵循一个简单的模式:
def run_conversation(messages):
while True:
response = chat(messages, tools=[get_current_datetime_schema])
add_assistant_message(messages, response)
print(text_from_message(response))
if response.stop_reason != "tool_use":
break
tool_results = run_tools(response)
add_user_message(messages, tool_results)
return messages
这个循环会持续进行,直到Claude提供最终答案而不再请求任何工具。
处理多个工具调用
Claude可以在单个响应中请求多个工具。消息内容包含一个块列表,我们需要分别处理每个工具使用块:

run_tools函数通过过滤工具使用块并处理每一个来处理这种情况:
def run_tools(message):
tool_requests = [
block for block in message.content if block.type == "tool_use"
]
tool_result_blocks = []
for tool_request in tool_requests:
# Process each tool request...
Tool Result Blocks
每个工具使用块都必须用相应的工具结果块来回答。它们之间的连接通过匹配的ID来维护:

工具结果块的结构包括:
tool_result_block = {
"type": "tool_result",
"tool_use_id": tool_request.id,
"content": json.dumps(tool_output),
"is_error": False
}
Error Handling
稳健的工具执行需要处理潜在的错误。当工具失败时,我们仍然需要向Claude提供一个结果块:
try:
tool_output = run_tool(tool_request.name, tool_request.input)
tool_result_block = {
"type": "tool_result",
"tool_use_id": tool_request.id,
"content": json.dumps(tool_output),
"is_error": False
}
except Exception as e:
tool_result_block = {
"type": "tool_result",
"tool_use_id": tool_request.id,
"content": f"Error: {e}",
"is_error": True
}
可扩展的工具路由
为了支持多个工具,创建一个路由函数,将工具名称映射到它们的实现:
def run_tool(tool_name, tool_input):
if tool_name == "get_current_datetime":
return get_current_datetime(**tool_input)
elif tool_name == "another_tool":
return another_tool(**tool_input)
# 根据需要添加更多工具
这种方法使得添加新工具变得简单,无需修改核心对话逻辑。
Complete Workflow
完整的多轮对话工作流程如下:
- 向Claude发送用户消息,并提供可用工具
- Claude响应文本和/或工具请求
- 执行所有请求的工具并创建结果块
- 将工具结果作为用户消息发送回去
- 重复此过程,直到Claude提供最终答案
这创造了一种无缝体验,Claude可以在多个轮次中使用多个工具来完整回答复杂的用户请求。对话历史保持完整的上下文,允许Claude基于之前的工具结果构建并提供全面的响应。
==================================================
此文档由 学习AI的1000天 翻译制作(抖音,B站,YouTube)
邮箱: szqshan@gmail.com | 微信: szqshan
网址: www.xueai.org