Gradio是python中一种用于构建AI界面的开源库,可以让您快速构建自己的应用程序并与AI模型进行交互,轻松部署模型。官方文档:Gradio,本文我们尝试使用Gradio构建一个基于大模型的聊天机器人demo。
安装
Gradio的安装非常简单,代码:
pip install gradio
聊天机器人demo实现
Gradio提供了Chatbot组件用于展示聊天机器人的输出,包括用户提交的消息和机器人的回复。它支持一些Markdown语法,包括粗体、斜体、代码和图片等。Chatbot模块的输入不接受用户输入,而是通过函数返回的列表来设置聊天内容。返回的列表应包含多个内部列表,每个内部列表包含两个元素:用户消息和机器人回复。消息可以是字符串、元组或None。如果消息是字符串,可以包含Markdown格式的文本。如果消息是元组,应包含文件路径和可选的替代文本。值为None的消息将不会显示在聊天界面上。
参数 | 描述 | 数据类型 | 默认值 |
---|---|---|---|
value | Chatbot的默认值,应为一个列表,其中每个元素为一个内部列表,包含用户消息和机器人回复。可以是可调用对象,在应用程序加载时设置初始值。 | list[list[str | tuple[str] | tuple[str, str] | None]] | Callable | None | None |
color_map | 颜色映射,用于设置不同类型消息的颜色。 | dict[str, str] | None | None |
label | 组件的标签。 | str | None | None |
every | 如果value是一个可调用对象,在客户端连接开启时每隔一段时间运行函数。以秒为单位解释。队列必须启用。 | float | None | None |
show_label | 是否显示标签。 | bool | True |
container | 是否将组件放入容器中,提供一些额外的边框填充。 | bool | True |
scale | 相对于相邻组件的宽度比例。例如,如果组件A的scale=2,组件B的scale=1,则组件A的宽度是组件B的两倍。应为整数。 | int | None | None |
min_width | 最小像素宽度,如果屏幕空间不足以满足此值,则换行。如果某个scale值导致该组件比min_width更窄,则首先遵守min_width参数。 | int | 160 |
visible | 组件是否可见。 bool True | ||
elem_id | 作为HTML DOM中此组件的id分配的可选字符串。可用于定位CSS样式。 | str | None | None |
elem_classes | 作为HTML DOM中此组件的类分配的可选字符串列表。可用于定位CSS样式。 | list[str] | str | None | None |
height | 组件的高度(以像素为单位)。 | int | None | None |
latex_delimiters | 用于渲染LaTeX表达式的左右分隔符及其显示方式的设置。 | list[dict[str, str | bool]] | None | None |
简单使用的demo:
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.ClearButton([msg, chatbot])
def respond(message, chat_history):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
chat_history.append((message, bot_message))
time.sleep(2)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
demo.launch()
效果:
此外,Gradio还提供了一个多模态的聊天机器人gr.ChatInterface类,它可以方便地创建一个具有多模态输入聊天框的机器人交互界面。
def echo(message, history):
return message["text"]
chatbot = gr.Chatbot(value=[[None, "您好,我是chat。"]],bubble_full_width = False,
avatar_images=('C:\workplace\pycharm_workplace\pythonProject\pics\man1.png','C:\workplace\pycharm_workplace\pythonProject\pics\women1.png'))
chatbot_infer = gr.ChatInterface(fn=echo, examples=[{"text": "我有些难过"}, {"text": "你可以安慰我吗"}], multimodal=True, chatbot=chatbot,submit_btn='发送')
echo是推理的函数,在这个例子中,机器人会将用户的输入值返回回来: