第八章 搭建一个带评估的端到端问答系统¶
在本章中,我们将搭建一个带评估的端到端问答系统,这个系统综合了之前多节课的内容,并加入了评估过程。
检查输入,确认其是否能通过审核 API 的审核。
如果通过了审核,我们将查找产品列表。
如果找到了产品,我们将尝试查找它们的相关信息。
我们使用模型回答用户提出的问题。
我们将通过审核 API 对生成的答案进行审核。
如果没有被标记为有害的,我们将把答案返回给用户。
一、环境配置¶
同上一章,我们首先需要配置使用 OpenAI API 的环境
In [1]:
# 配置 OpenAI KEY
import os
import openai
import sys
sys.path.append('../..')
# 使用英文 Prompt 的工具包
import utils_en
# 使用中文 Prompt 的工具包
import utils_zh
import panel as pn # 用于图形化界面
pn.extension()
openai.api_key = "sk-..."
# 设置 API_KEY, 请替换成您自己的 API_KEY
# 以下为基于环境变量的配置方法示例,这样更加安全。仅供参考,后续将不再涉及。
# import openai
# import os
# OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
# openai.api_key = OPENAI_API_KEY
In [2]:
def get_completion_from_messages(messages,
model="gpt-3.5-turbo",
temperature=0,
max_tokens=500):
'''
封装一个访问 OpenAI GPT3.5 的函数
参数:
messages: 这是一个消息列表,每个消息都是一个字典,包含 role(角色)和 content(内容)。角色可以是'system'、'user' 或 'assistant’,内容是角色的消息。
model: 调用的模型,默认为 gpt-3.5-turbo(ChatGPT),有内测资格的用户可以选择 gpt-4
temperature: 这决定模型输出的随机程度,默认为0,表示输出将非常确定。增加温度会使输出更随机。
max_tokens: 这决定模型输出的最大的 token 数。
'''
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature, # 这决定模型输出的随机程度
max_tokens=max_tokens, # 这决定模型输出的最大的 token 数
)
return response.choices[0].message["content"]
二、用于处理用户查询的链式 Prompt 系统¶
2.1 一个端到端实现问答的函数¶
In [15]:
def process_user_message(user_input, all_messages, debug=True):
"""
对用户信息进行预处理
参数:
user_input : 用户输入
all_messages : 历史信息
debug : 是否开启 DEBUG 模式,默认开启
"""
# 分隔符
delimiter = "```"
# 第一步: 使用 OpenAI 的 Moderation API 检查用户输入是否合规或者是一个注入的 Prompt
response = openai.Moderation.create(input=user_input)
moderation_output = response["results"][0]
# 经过 Moderation API 检查该输入不合规
if moderation_output["flagged"]:
print("第一步:输入被 Moderation 拒绝")
return "抱歉,您的请求不合规"
# 如果开启了 DEBUG 模式,打印实时进度
if debug: print("第一步:输入通过 Moderation 检查")
# 第二步:抽取出商品和对应的目录,类似于之前课程中的方法,做了一个封装
category_and_product_response = utils_en.find_category_and_product_only(user_input, utils_en.get_products_and_category())
#print(category_and_product_response)
# 将抽取出来的字符串转化为列表
category_and_product_list = utils_en.read_string_to_list(category_and_product_response)
#print(category_and_product_list)
if debug: print("第二步:抽取出商品列表")
# 第三步:查找商品对应信息
product_information = utils_en.generate_output_string(category_and_product_list)
if debug: print("第三步:查找抽取出的商品信息")
# 第四步:根据信息生成回答
system_message = f"""
You are a customer service assistant for a large electronic store. \
Respond in a friendly and helpful tone, with concise answers. \
Make sure to ask the user relevant follow-up questions.
"""
# 插入 message
messages = [
{'role': 'system', 'content': system_message},
{'role': 'user', 'content': f"{delimiter}{user_input}{delimiter}"},
{'role': 'assistant', 'content': f"Relevant product information:\n{product_information}"}
]
# 获取 GPT3.5 的回答
# 通过附加 all_messages 实现多轮对话
final_response = get_completion_from_messages(all_messages + messages)
if debug:print("第四步:生成用户回答")
# 将该轮信息加入到历史信息中
all_messages = all_messages + messages[1:]
# 第五步:基于 Moderation API 检查输出是否合规
response = openai.Moderation.create(input=final_response)
moderation_output = response["results"][0]
# 输出不合规
if moderation_output["flagged"]:
if debug: print("第五步:输出被 Moderation 拒绝")
return "抱歉,我们不能提供该信息"
if debug: print("第五步:输出经过 Moderation 检查")
# 第六步:模型检查是否很好地回答了用户问题
user_message = f"""
Customer message: {delimiter}{user_input}{delimiter}
Agent response: {delimiter}{final_response}{delimiter}
Does the response sufficiently answer the question?
"""
messages = [
{'role': 'system', 'content': system_message},
{'role': 'user', 'content': user_message}
]
# 要求模型评估回答
evaluation_response = get_completion_from_messages(messages)
if debug: print("第六步:模型评估该回答")
# 第七步:如果评估为 Y,输出回答;如果评估为 N,反馈将由人工修正答案
if "Y" in evaluation_response: # 使用 in 来避免模型可能生成 Yes
if debug: print("第七步:模型赞同了该回答.")
return final_response, all_messages
else:
if debug: print("第七步:模型不赞成该回答.")
neg_str = "很抱歉,我无法提供您所需的信息。我将为您转接到一位人工客服代表以获取进一步帮助。"
return neg_str, all_messages
user_input = "tell me about the smartx pro phone and the fotosnap camera, the dslr one. Also what tell me about your tvs"
response,_ = process_user_message(user_input,[])
print(response)
第一步:输入通过 Moderation 检查 第二步:抽取出商品列表 第三步:查找抽取出的商品信息 第四步:生成用户回答 第五步:输出经过 Moderation 检查 第六步:模型评估该回答 第七步:模型赞同了该回答. The SmartX ProPhone is a powerful smartphone with a 6.1-inch display, 128GB storage, 12MP dual camera, and 5G capabilities. The FotoSnap DSLR Camera is a versatile camera with a 24.2MP sensor, 1080p video, 3-inch LCD, and interchangeable lenses. As for our TVs, we have a range of options including the CineView 4K TV with a 55-inch display, 4K resolution, HDR, and smart TV capabilities, the CineView 8K TV with a 65-inch display, 8K resolution, HDR, and smart TV capabilities, and the CineView OLED TV with a 55-inch display, 4K resolution, HDR, and smart TV capabilities. Do you have any specific questions about these products or would you like me to recommend a product based on your needs?
In [4]:
'''
注意:限于模型对中文理解能力较弱,中文 Prompt 可能会随机出现不成功,可以多次运行;也非常欢迎同学探究更稳定的中文 Prompt
'''
def process_user_message_ch(user_input, all_messages, debug=True):
"""
对用户信息进行预处理
参数:
user_input : 用户输入
all_messages : 历史信息
debug : 是否开启 DEBUG 模式,默认开启
"""
# 分隔符
delimiter = "```"
# 第一步: 使用 OpenAI 的 Moderation API 检查用户输入是否合规或者是一个注入的 Prompt
response = openai.Moderation.create(input=user_input)
moderation_output = response["results"][0]
# 经过 Moderation API 检查该输入不合规
if moderation_output["flagged"]:
print("第一步:输入被 Moderation 拒绝")
return "抱歉,您的请求不合规"
# 如果开启了 DEBUG 模式,打印实时进度
if debug: print("第一步:输入通过 Moderation 检查")
# 第二步:抽取出商品和对应的目录,类似于之前课程中的方法,做了一个封装
category_and_product_response = utils_zh.find_category_and_product_only(user_input, utils_zh.get_products_and_category())
#print(category_and_product_response)
# 将抽取出来的字符串转化为列表
category_and_product_list = utils_zh.read_string_to_list(category_and_product_response)
#print(category_and_product_list)
if debug: print("第二步:抽取出商品列表")
# 第三步:查找商品对应信息
product_information = utils_zh.generate_output_string(category_and_product_list)
if debug: print("第三步:查找抽取出的商品信息")
# 第四步:根据信息生成回答
system_message = f"""
您是一家大型电子商店的客户服务助理。\
请以友好和乐于助人的语气回答问题,并提供简洁明了的答案。\
请确保向用户提出相关的后续问题。
"""
# 插入 message
messages = [
{'role': 'system', 'content': system_message},
{'role': 'user', 'content': f"{delimiter}{user_input}{delimiter}"},
{'role': 'assistant', 'content': f"相关商品信息:\n{product_information}"}
]
# 获取 GPT3.5 的回答
# 通过附加 all_messages 实现多轮对话
final_response = get_completion_from_messages(all_messages + messages)
if debug:print("第四步:生成用户回答")
# 将该轮信息加入到历史信息中
all_messages = all_messages + messages[1:]
# 第五步:基于 Moderation API 检查输出是否合规
response = openai.Moderation.create(input=final_response)
moderation_output = response["results"][0]
# 输出不合规
if moderation_output["flagged"]:
if debug: print("第五步:输出被 Moderation 拒绝")
return "抱歉,我们不能提供该信息"
if debug: print("第五步:输出经过 Moderation 检查")
# 第六步:模型检查是否很好地回答了用户问题
user_message = f"""
用户信息: {delimiter}{user_input}{delimiter}
代理回复: {delimiter}{final_response}{delimiter}
回复是否足够回答问题
如果足够,回答 Y
如果不足够,回答 N
仅回答上述字母即可
"""
# print(final_response)
messages = [
{'role': 'system', 'content': system_message},
{'role': 'user', 'content': user_message}
]
# 要求模型评估回答
evaluation_response = get_completion_from_messages(messages)
# print(evaluation_response)
if debug: print("第六步:模型评估该回答")
# 第七步:如果评估为 Y,输出回答;如果评估为 N,反馈将由人工修正答案
if "Y" in evaluation_response: # 使用 in 来避免模型可能生成 Yes
if debug: print("第七步:模型赞同了该回答.")
return final_response, all_messages
else:
if debug: print("第七步:模型不赞成该回答.")
neg_str = "很抱歉,我无法提供您所需的信息。我将为您转接到一位人工客服代表以获取进一步帮助。"
return neg_str, all_messages
user_input = "请告诉我关于 smartx pro phone 和 the fotosnap camera 的信息。另外,请告诉我关于你们的tvs的情况。"
response,_ = process_user_message_ch(user_input,[])
print(response)
第一步:输入通过 Moderation 检查 第二步:抽取出商品列表 第三步:查找抽取出的商品信息 第四步:生成用户回答 第五步:输出经过 Moderation 检查 第六步:模型评估该回答 第七步:模型赞同了该回答. 关于SmartX ProPhone和FotoSnap相机的信息: SmartX ProPhone是一款功能强大的智能手机,具有6.1英寸的显示屏,128GB的存储空间,12MP的双摄像头和5G网络。售价为899.99美元。 FotoSnap相机系列包括DSLR相机、无反相机和即时相机。DSLR相机具有24.2MP传感器、1080p视频、3英寸LCD和可更换镜头。无反相机具有20.1MP传感器、4K视频、3英寸触摸屏和可更换镜头。即时相机可以即时打印照片,具有内置闪光灯、自拍镜和电池供电。售价分别为599.99美元、799.99美元和69.99美元。 关于我们的电视: 我们有多种电视可供选择,包括CineView 4K电视、CineView 8K电视和CineView OLED电视。CineView 4K电视具有55英寸的显示屏、4K分辨率、HDR和智能电视功能。CineView 8K电视具有65英寸的显示屏、8K分辨率、HDR和智能电视功能。CineView OLED电视具有55英寸的显示屏、4K分辨率、HDR和智能电视功能。我们还提供SoundMax家庭影院和SoundMax声音栏,以提供更好的音频体验。售价从199.99美元到2999.99美元不等,保修期为1年或2年。
2.2 持续收集用户和助手消息的函数¶
实现一个可视化界面
In [17]:
def collect_messages_en(debug=False):
"""
用于收集用户的输入并生成助手的回答
参数:
debug: 用于觉得是否开启调试模式
"""
user_input = inp.value_input
if debug: print(f"User Input = {user_input}")
if user_input == "":
return
inp.value = ''
global context
# 调用 process_user_message 函数
#response, context = process_user_message(user_input, context, utils.get_products_and_category(),debug=True)
response, context = process_user_message(user_input, context, debug=False)
context.append({'role':'assistant', 'content':f"{response}"})
panels.append(
pn.Row('User:', pn.pane.Markdown(user_input, width=600)))
panels.append(
pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))
return pn.Column(*panels) # 包含了所有的对话信息
In [ ]:
# 调用中文 Prompt 版本
def collect_messages_ch(debug=False):
"""
用于收集用户的输入并生成助手的回答
参数:
debug: 用于觉得是否开启调试模式
"""
user_input = inp.value_input
if debug: print(f"User Input = {user_input}")
if user_input == "":
return
inp.value = ''
global context
# 调用 process_user_message 函数
#response, context = process_user_message(user_input, context, utils.get_products_and_category(),debug=True)
response, context = process_user_message_ch(user_input, context, debug=False)
context.append({'role':'assistant', 'content':f"{response}"})
panels.append(
pn.Row('User:', pn.pane.Markdown(user_input, width=600)))
panels.append(
pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))
return pn.Column(*panels) # 包含了所有的对话信息
In [18]:
panels = [] # collect display
# 系统信息
context = [ {'role':'system', 'content':"You are Service Assistant"} ]
inp = pn.widgets.TextInput( placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Service Assistant")
interactive_conversation = pn.bind(collect_messages, button_conversation)
dashboard = pn.Column(
inp,
pn.Row(button_conversation),
pn.panel(interactive_conversation, loading_indicator=True, height=300),
)
dashboard
Out[18]:
通过监控系统在更多输入上的质量,您可以修改步骤,提高系统的整体性能。
也许我们会发现,对于某些步骤,我们的提示可能更好,也许有些步骤甚至不必要,也许我们会找到更好的检索方法等等。
我们将在下一章中进一步讨论这个问题。