Gradio 4.37.1官方教程三:Chatbot


传送门:

gradio(GitHub)Chatbot官方教程ChatInterface官方文档

一、使用ChatInterface创建聊天机器人

  聊天机器人是大型语言模型的一种流行应用。使用 Gradio,可以轻松构建聊天机器人模型的演示。gr.ChatInterface()是一个高级抽象,通常只需一行代码即可快速创建聊天机器人 UI,还可以与几个流行的 API 和库(包括 langchain、openai 和 Hugging Face)中的实际语言模型结合使用。

1.1 定义聊天函数

   在使用 gr.ChatInterface() 时,首先需要定义聊天函数。你的聊天函数应接受两个参数:messagehistory(参数名称可以随意,但顺序必须如此)。

  • message:表示用户输入的字符串。
  • history:表示到目前为止的对话历史记录的列表。每个内嵌列表由两个字符串组成,表示一个对话对:[user input, bot response]

最终返回返回一个字符串响应(bot response)。下面是一个简单的示例:

import random
import gradio as gr

def alternatingly_agree(message, history):
    if len(history) % 2 == 0:
        return f"Yes, I do think that '{
     message}'"
    else:
        return "I don't think so"

gr.ChatInterface(alternatingly_agree).launch()

在这里插入图片描述

1.2 流式聊天机器人(Streaming chatbots)

  流式聊天机器人的响应是逐步生成并显示的,这样用户在等待完整回复的过程中,可以逐步看到部分回复(实时反馈),提高了互动的流畅度和用户体验。在聊天函数中,使用 yield 逐步生成响应,就能实现一个流式聊天机器人。

import time
import gradio as gr

def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.3)
        yield "You typed: " + message[: i+1]

gr.ChatInterface(slow_echo).launch()

  slow_echo:在每次迭代中,函数都会暂停 0.3 秒,然后将用户输入的信息一个个字母的生成出来。另外,在响应流式传输时,“Submit”按钮会变成“Stop”按钮,用来停止生成器函数。你可以使用 stop_btn 参数自定义“Stop”按钮的外观和行为。

1.3 自定义聊天机器人

和Gradio的Interface类一样,gr.ChatInterface类也包括许多相同的参数,可以用来自定义聊天机器人的外观和感觉,比如:

  • 使用titledescription参数在聊天机器人上方添加标题和描述。
  • 使用themecss参数添加主题或自定义CSS。
  • 使用placeholder参数用于设置聊天界面的“占位符”(用户未输入时的起始显示,用于提示用户输入),该参数接受Markdown或HTML。占位符会在聊天机器人中居中显示。
  • 使用examples添加示例,并设置cache_examples=True缓存示例(启动demo时自动运行示例,缓存结果)。
  • 更改或禁用聊天界面中的各个按钮:submit_btnretry_btnundo_btnclear_btn
  • 自定义ChatInterface中的gr.Chatbotgr.Textbox等组件
import gradio as gr

def yes_man(message, history):
    if message.endswith("?"):
        return "Yes"
    else:
        return "Ask me anything!"

gr.ChatInterface(
    yes_man,
    chatbot=gr.Chatbot(height=300,placeholder="<strong>Your Personal Yes-Man</strong><br>Ask Me Anything"),
    textbox=gr.Textbox(placeholder="Ask me a yes or no question", container=False, scale=7),
    title="Yes Man",
    description="Ask Yes Man any question",
    theme="soft",
    examples=["Hello", "Am I cool?", "Are tomatoes vegetables?"],
    cache_examples=True,
    retry_btn=None,
    undo_btn="Delete Previous",
    clear_btn="Clear",
).launch()

在这里插入图片描述

1.4 添加多模态功能

  你可以向聊天机器人添加多模态功能。例如,你可能希望用户能够轻松上传图片或文件,并向聊天机器人提问。在gr.ChatInterface中设置multimodal=True可以使聊天机器人“多模态化”。

  当multimodal=True时,函数fn的签名会稍微变化。你的函数的第一个参数应该接受一个包含提交文本和上传文件的字典,比如{"text": "user input", "file": ["file_path1", "file_path2", ...]}。同样,你提供的任何示例也应该是这种形式的字典。函数返回值不变,仍旧返回一个单一的字符串消息。

import gradio as gr
import time

def count_files(message, history):
    num_files = len(message["files"])
    return f"You uploaded {
     num_files} files"

demo = gr.ChatInterface(fn=count_files, examples=[{
   "text": "Hello", "files": []}], title="Echo Bot", multimodal=True)

demo.launch()

在这里插入图片描述

✍️ 提示:如果你想自定义多模态聊天机器人的文本框的UI/UX,你应该传递一个gr.MultimodalTextbox实例到ChatInterface的textbox参数,而不是gr.Textbox实例。

1.5 通过additional_inputs添加额外组件

  通过additional_inputs参数可以添加额外的输入组件,例如,添加一个系统提示的文本框,或设置聊天机器人响应中token数量的滑块。以下是更具体的说明:

  • additional_inputs 参数接受一个组件或组件列表,你可以直接传递组件实例,或使用它们的字符串快捷方式(比如用“textbox”代替gr.Textbox()
  • 如果传递的组件尚未渲染,会出现在聊天机器人(和任何示例)下面的折叠面板中(gr.Accordion(),可以打开/折叠)。可以使用additional_inputs_accordion_name参数设置此折叠面板的标签

  下面创建一个带有额外输入参数的聊天机器人界面,用户可以在折叠面板的系统提示语文本框中输入自定义提示语,使用滑块设置响应的最大token数量。聊天机器人根据用户输入的消息和系统提示语生成响应,并逐字符显示响应内容,模拟打字效果。

import gradio as gr
import time

def echo(message, history, system_prompt, tokens):
    response = f"System prompt: {
     system_prompt}\n Message: {
     message}."
    for i in range(min(len(respons
Building prefix dict from the default dictionary ... DEBUG:jieba:Building prefix dict from the default dictionary ... Loading model from cache C:\Users\LY-AI\AppData\Local\Temp\jieba.cache DEBUG:jieba:Loading model from cache C:\Users\LY-AI\AppData\Local\Temp\jieba.cache Loading model cost 0.717 seconds. DEBUG:jieba:Loading model cost 0.717 seconds. Prefix dict has been built successfully. DEBUG:jieba:Prefix dict has been built successfully. C:\Users\LY-AI\Desktop\AI\vits-uma-genshin-honkai\python3.9.13\3.9.13\lib\site-packages\gradio\processing_utils.py:183: UserWarning: Trying to convert audio automatically from float32 to 16-bit int format. warnings.warn(warning.format(data.dtype)) Traceback (most recent call last): File "C:\Users\LY-AI\Desktop\AI\vits-uma-genshin-honkai\python3.9.13\3.9.13\lib\site-packages\gradio\routes.py", line 442, in run_predict output = await app.get_blocks().process_api( File "C:\Users\LY-AI\Desktop\AI\vits-uma-genshin-honkai\python3.9.13\3.9.13\lib\site-packages\gradio\blocks.py", line 1392, in process_api data = self.postprocess_data(fn_index, result["prediction"], state) File "C:\Users\LY-AI\Desktop\AI\vits-uma-genshin-honkai\python3.9.13\3.9.13\lib\site-packages\gradio\blocks.py", line 1326, in postprocess_data prediction_value = block.postprocess(prediction_value) File "C:\Users\LY-AI\Desktop\AI\vits-uma-genshin-honkai\app.py", line 42, in audio_postprocess return gr_processing_utils.encode_url_or_file_to_base64(data["name"]) AttributeError: module 'gradio.processing_utils' has no attribute 'encode_url_or_file_to_base64'
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神洛华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值