chatbot模块是Gradio中的一个组件,用于展示聊天机器人的输出,包括用户提交的消息和机器人的回复。它支持一些Markdown语法,包括粗体、斜体、代码和图片等。Chatbot模块的输入不接受用户输入,而是通过函数返回的列表来设置聊天内容。返回的列表应包含多个内部列表,每个内部列表包含两个元素:用户消息和机器人回复。消息可以是字符串、元组或None。如果消息是字符串,可以包含Markdown格式的文本。如果消息是元组,应包含文件路径和可选的替代文本。值为None的消息将不会显示在聊天界面上。
下面是一些常用的参数:
一些实践案例(参考:使用Gradio创建一个chatbot机器人):
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("清除")
def respond(message, chat_history):
bot_message = random.choice(["你好吗?", "我爱你", "我很饿"])
chat_history.append((message, bot_message))
time.sleep(1)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch()
其中,chatbot可以作为输入项,在respond
函数中是聊天历史信息,其中chatbot()
接收的可以是[['testtt ', '我爱你'], ('11111', '我爱你')]
元组集合。
另外,清除按钮clear.click
可以lambda: None
直接清除信息
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("清除")
def user(user_message, history):
return "", history + [[user_message, None]]
def bot(history):
bot_message = random.choice(["你好吗?", "我爱你", "我很饿"])
history[-1][1] = ""
for character in bot_message:
history[-1][1] += character
time.sleep(0.05)
yield history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
demo.queue()
demo.launch()
流式处理这里使用.then()
方法链接了两个事件user
+ bot
, yield
来进行流式化;
另外,历史数据同样可以通过chatbot还回传,就是这句了:history + [[user_message, None]]
其中,
我们通过运行demo.queue()启用排队,这是流式输出所需的.
当然,这里其实还可以使用一些色彩填充的方式,让chatbot的对话框好看:
chatbot = gr.Chatbot().style(color_map=("green", "pink"))