
本文将介绍如何使用Gradio和OpenAI API来实现一个流式问答机器人。通过这个教程,你将学会如何构建一个可以处理文本输入并返回连续响应的聊天机器人。
在开始之前,确保你已经安装了必要的Python库。你可以使用以下命令安装Gradio和OpenAI库:
pip install gradio openai
我们将代码分为几个部分进行详细解读:
首先,我们需要导入Gradio和OpenAI库,以及操作系统相关的库。
import osimport gradio as gr from openaiimport OpenAI
add_message函数用于将用户的输入消息添加到聊天记录中。
def add_message(history, message):
for x in message["files"]:
history.append(((x,), None))
if message["text"] is not None:
history.append((message["text"], None))
return history, gr.MultimodalTextbox(value=None, interactive=False)函数参数:
history:聊天记录。
message:用户输入的消息,是一个字符串。
函数功能:
bot函数用于处理用户输入,并通过OpenAI API生成机器人响应。
def bot(history):
history[-1][1] = ""
history_openai_format = []
for human, assistant in history[:-1]:
history_openai_format.append({"role": "user", "content": human})
history_openai_format.append({"role": "assistant", "content": assistant})
history_openai_format.append({"role": "user", "content": history[-1][0]})
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-turbo",
messages=history_openai_format,
temperature=0.1,
stream=True,
)
for chunk in completion:
history[-1][1] += chunk.choices[0].delta.content
yield history函数参数:
history:聊天记录。
函数功能:
prompt)。
yield逐步更新聊天记录,实现流式响应。
为方便对接国内大模型,我们使用了DashScope API代替OpenAI API,只需要改写api_key、base_url和model即可使用。
接下来,我们使用Gradio创建一个用户界面来展示聊天机器人。
with gr.Blocks() as demo:
chatbot = gr.Chatbot([], elem_id="chatbot", bubble_full_width=False)
chat_input = gr.MultimodalTextbox(
interactive=True,
file_types=[],
placeholder="Enter message or upload file...",
show_label=False,
)
chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input]
)
bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response")
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
demo.queue()
demo.launch()步骤说明:
gr.Blocks实例作为整个应用的容器。
Chatbot组件来显示聊天内容。
MultimodalTextbox组件作为用户的输入框。
add_message函数更新聊天记录。
then方法链式调用bot函数处理并生成机器人响应。
launch()启动Gradio应用。
import os
import gradio as gr
from openai import OpenAI
def add_message(history, message):
for x in message["files"]:
history.append(((x,), None))
if message["text"] is not None:
history.append((message["text"], None))
return history, gr.MultimodalTextbox(value=None, interactive=False)
def bot(history):
history[-1][1] = ""
history_openai_format = []
for human, assistant in history[:-1]:
history_openai_format.append({"role": "user", "content": human})
history_openai_format.append({"role": "assistant", "content": assistant})
history_openai_format.append({"role": "user", "content": history[-1][0]})
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-turbo",
messages=history_openai_format,
temperature=0.1,
stream=True,
)
for chunk in completion:
history[-1][1] += chunk.choices[0].delta.content
yield history
with gr.Blocks() as demo:
chatbot = gr.Chatbot([], elem_id="chatbot", bubble_full_width=False)
chat_input = gr.MultimodalTextbox(
interactive=True,
file_types=[],
placeholder="Enter message or upload file...",
show_label=False,
)
chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input]
)
bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response")
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
demo.queue()
demo.launch()可以看到,LLM响应是流式输出的,并且LLM在处理第二个问题“里面有哪些教程”时,理解了用户想要问的上下文是“Datawhale里面有哪些教程”。
暂时无法在飞书文档外展示此内容
通过上述步骤,我们成功地实现了一个基于Gradio和OpenAI的流式问答机器人。这个教程展示了如何处理用户输入并使用OpenAI API生成连续的响应,希望对你有所帮助。
现在,你可以根据自己的需求进一步定制和扩展这个聊天机器人,例如添加更多的对话逻辑或支持更多类型的输入。