Anthropic's Prompt Engineering Interactive Tutorial多工具集成:聊天机器人架构设计
Anthropic's Prompt Engineering Interactive Tutorial多工具集成:聊天机器人架构设计
在当今智能客服和自动化交互系统中,多工具集成的聊天机器人架构正成为提升用户体验的关键。本文将详细介绍如何基于Anthropic's Prompt Engineering Interactive Tutorial构建一个集成多工具的聊天机器人,涵盖架构设计、工具配置、流程实现和代码示例等核心内容。
架构概览
多工具集成的聊天机器人架构主要包含用户交互层、工具管理层、数据处理层和外部服务层四个部分。用户交互层负责接收用户输入并展示结果;工具管理层处理工具选择和调用逻辑;数据处理层处理工具返回结果并生成响应;外部服务层则集成各种功能工具如用户查询、订单管理等。
该架构的核心优势在于能够根据用户请求自动选择合适的工具,并通过多轮交互完成复杂任务。例如,当用户查询订单时,系统会先调用用户查询工具获取用户ID,再调用订单查询工具获取订单信息,最后将结果整理后返回给用户。
工具配置
工具配置是实现多工具集成的基础,需要定义工具的名称、描述和输入参数等信息。在本项目中,工具配置文件位于AmazonBedrock/toolUse_order_bot/order_bot_converse_api.py,主要包含以下工具:
get_user:通过邮箱、电话或用户名查询用户信息get_order_by_id:通过订单ID查询订单详情get_customer_orders:通过用户ID查询所有订单cancel_order:取消指定ID的订单(仅处理中订单可取消)
工具配置示例代码如下:
toolConfig = {
'tools': [
{
'toolSpec': {
'name': 'get_user',
'description': 'Looks up a user by email, phone, or username.',
'inputSchema': {
'json': {
'type': 'object',
'properties': {
'key': {
'type': 'string',
'enum': ['email', 'phone', 'username'],
'description': 'The attribute to search for a user by (email, phone, or username).'
},
'value': {
'type': 'string',
'description': 'The value to match for the specified attribute.'
}
},
'required': ['key', 'value']
}
}
}
},
# 其他工具配置...
],
'toolChoice': {
'auto': {}
}
}
工作流程
多工具聊天机器人的工作流程主要包括以下步骤:
- 接收用户请求:用户输入查询或操作请求
- 工具选择:根据用户请求自动选择合适的工具
- 参数提取:从用户请求中提取工具所需参数
- 工具调用:执行工具并获取结果
- 结果处理:整理工具返回结果
- 生成响应:将结果转换为自然语言响应
以查询用户订单为例,完整流程如下:
- 用户输入:"查询我的订单,邮箱是john@gmail.com"
- 系统选择
get_user工具,参数为key=email, value=john@gmail.com - 调用
get_user获取用户ID - 系统选择
get_customer_orders工具,参数为customer_id=1213210 - 调用
get_customer_orders获取订单列表 - 整理订单信息并生成自然语言响应
核心实现
数据库模拟
为了演示,项目中使用FakeDatabase类模拟用户和订单数据存储,代码位于AmazonBedrock/toolUse_order_bot/order_bot_converse_api.py:
class FakeDatabase:
def __init__(self):
self.customers = [
{"id": "1213210", "name": "John Doe", "email": "john@gmail.com", "phone": "123-456-7890", "username": "johndoe"},
# 其他用户数据...
]
self.orders = [
{"id": "24601", "customer_id": "1213210", "product": "Wireless Headphones", "quantity": 1, "price": 79.99, "status": "Shipped"},
# 其他订单数据...
]
# 数据库操作方法...
工具调用处理
process_tool_call函数负责将工具调用请求映射到实际的数据库操作,代码如下:
def process_tool_call(tool_name, tool_input):
if tool_name == "get_user":
return db.get_user(tool_input["key"], tool_input["value"])
elif tool_name == "get_order_by_id":
return db.get_order_by_id(tool_input["order_id"])
elif tool_name == "get_customer_orders":
return db.get_customer_orders(tool_input["customer_id"])
elif tool_name == "cancel_order":
return db.cancel_order(tool_input["order_id"])
聊天交互逻辑
simple_chat函数实现了基本的聊天交互循环,处理用户输入、工具调用和响应生成:
def simple_chat():
user_message = input("\nUser: ")
messages = [{"role": "user", "content": [{"text": user_message}]}]
while True:
# 发送请求到Claude模型
converse_api_params = {
"modelId": modelId,
"messages": messages,
"inferenceConfig": {"maxTokens": 4096},
"toolConfig": toolConfig,
}
response = bedrock_client.converse(**converse_api_params)
# 处理工具调用或直接响应
if response['stopReason'] == "tool_use":
# 执行工具调用并获取结果
tool_use = response['output']['message']['content'][-1]
tool_result = process_tool_call(tool_use['toolUse']['name'], tool_use['toolUse']['input'])
# 将工具结果添加到对话历史
messages.append({
"role": "user",
"content": [{"toolResult": {"toolUseId": tool_use['toolUse']['toolUseId'], "content": [{"text": str(tool_result)}]}}]
})
else:
# 直接输出模型响应
print(f"\nTechNova Support: {response['output']['message']['content'][0]['text']}")
user_message = input("\nUser: ")
messages.append({"role": "user", "content": [{"text": user_message}]})
示例交互
以下是一个完整的交互示例,展示了用户查询订单并取消订单的过程:
User: 我想查询我的订单,我的邮箱是john@gmail.com
Claude wants to use the get_user tool
Tool Input:
{
"key": "email",
"value": "john@gmail.com"
}
Tool Result:
{"id": "1213210", "name": "John Doe", "email": "john@gmail.com", "phone": "123-456-7890", "username": "johndoe"}
Claude wants to use the get_customer_orders tool
Tool Input:
{
"customer_id": "1213210"
}
Tool Result:
[
{"id": "24601", "customer_id": "1213210", "product": "Wireless Headphones", "quantity": 1, "price": 79.99, "status": "Shipped"},
{"id": "13579", "customer_id": "1213210", "product": "Smartphone Case", "quantity": 2, "price": 19.99, "status": "Processing"}
]
TechNova Support: John Doe,您有以下订单:
1. 订单ID: 24601,产品: Wireless Headphones,状态: Shipped
2. 订单ID: 13579,产品: Smartphone Case,状态: Processing
User: 请帮我取消订单13579
Claude wants to use the cancel_order tool
Tool Input:
{
"order_id": "13579"
}
Tool Result:
"Cancelled the order"
TechNova Support: 订单13579已成功取消。
总结与扩展
本文介绍了基于Anthropic's Prompt Engineering Interactive Tutorial构建多工具集成聊天机器人的完整流程,包括架构设计、工具配置、核心实现和示例交互。通过合理设计工具接口和工作流程,可以让聊天机器人具备处理复杂任务的能力。
后续可以从以下方面进行扩展:
- 添加更多工具,如支付查询、物流跟踪等
- 实现更复杂的错误处理和重试机制
- 添加用户认证和权限控制
- 优化工具选择逻辑,提高工具调用准确性
完整的代码实现可以参考项目中的AmazonBedrock/10_2_5_Chatbot_with_Multiple_Tools.ipynb和Anthropic 1P/10.2_Appendix_Tool Use.ipynb教程。
更多推荐





所有评论(0)