当前位置: 首页 > news >正文

Gradio全解8——ChatInterfaceChatbot:聊天界面类与聊天机器人(4)——返回复杂响应与直接修改Chatbot值

Gradio全解8——ChatInterface&Chatbot:聊天界面类与聊天机器人(4)——返回复杂响应与直接修改Chatbot值

    • 8.4 返回复杂响应与直接修改chatbot值
      • 8.4.1 返回复杂响应
        • 1. 返回Gradio各类组件
        • 2. 提供预设回复options
        • 3. 返回多条附加消息
      • 8.4.2 返回直接修改chatbot_value

本章目录如下:

  1. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(1)——ChatInterface类示例与构造参数》
  2. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(2)——ChatInterface的自定义函数和界面》
  3. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(3)——ChatInterface的多模态功能与附加输入输出》
  4. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(4)——返回复杂响应与直接修改Chatbot值》
  5. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(5)——通过API加载、聊天历史和用户反馈》
  6. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(6)——gr.ChatInterface与流行LLM库和API结合》
  7. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(7)——组件gr.Chatbot及gr.ChatMessage》
  8. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(8)——组件Chatbot的特殊Events》
  9. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(9)——使用Blocks创建自定义聊天机器人》
  10. 《ChatInterface&Chatbot:聊天界面类与聊天机器人(10)——使用显示思考和引用构建UI》

8.4 返回复杂响应与直接修改chatbot值

本节讲解如何在ChatInterface显示处理函数返回的复杂响应,返回值也可直接修改ChatInterface类的参数chatbot_value,从而影响显示效果。

8.4.1 返回复杂响应

我们之前提到过,在最简单的情况下,聊天函数应返回一个呈现为文本的字符串响应。然而聊天函数也可以返回更复杂的响应,比如返回Gradio组件、提供预设回复或返回多条消息等。

1. 返回Gradio各类组件

目前以下Gradio组件可以显示在聊天界面中:gr.Image、gr.Plot、gr.Audio、gr.HTML、gr.Video、gr.Gallery和gr.File。只需从fn函数中返回这些组件之一,即可显示在gr.ChatInterface的输出框中。以下是一个返回音频文件的示例:

import gradio as gr
def music(message, history):if message.strip():return gr.Audio("https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav")else:return "Please provide the name of an artist"gr.ChatInterface(music,type="messages",textbox=gr.Textbox(placeholder="Which artist's music do you want to listen to?", scale=7),
).launch()

运行界面如图8-9:
在这里插入图片描述

图8-9

类似地,可以使用gr.Image返回图片文件,使用gr.Video返回视频文件,或者使用gr.File组件返回任意文件。

2. 提供预设回复options

我们可能希望提供预设回复,供用户聊天时选择。为此,可以从聊天函数中返回一个完整的OpenAI风格的消息字典,并在返回的字典中添加options键来预设回复。字典应包含以下键:

  • role:设置为"assistant",代表机器人。
  • content:可设置为一个字符串或字典。设置为字典时,键为path,值为要返回的文件路径或URL。
  • options:应该对应一个字典列表,每个字典包含一个value(一个字符串,当单击时被发送给聊天函数)和一个可选的label(如果提供,则作为预设回复显示的文本,否则显示value)。

以下示例展示了如何使用预设回复:

import gradio as gr
import random
example_code = """
Here's an example Python lambda function:lambda x: x + {}Is this correct?
"""
def chat(message, history):if message == "Yes, that's correct.":return "Great!"else:return {"role": "assistant","content": example_code.format(random.randint(1, 100)),"options": [{"value": "Yes, that's correct.", "label": "Yes"},{"value": "No"}]}
demo = gr.ChatInterface(chat,type="messages",examples=["Write an example Python lambda function."]
)
demo.launch()

运行界面如图8-10:
在这里插入图片描述

图8-10

单击按钮Yes后,会向函数chat传递对应的预设消息值“Yes, that’s correct.”,然后函数chat回复“Great!”结束会话。

3. 返回多条附加消息

我们还可以通过返回上述任意类型的消息列表(甚至可以混合使用),从而使聊天函数中返回多条附加消息。例如你可以发送一条带有文件的消息,如下例所示:

import gradio as gr
def echo_multimodal(message, history):response = []response.append("You wrote: '" + message["text"] + "' and uploaded:")if message.get("files"):for file in message["files"]:response.append(gr.File(value=file))return responsedemo = gr.ChatInterface(echo_multimodal,type="messages",multimodal=True,textbox=gr.MultimodalTextbox(file_count="multiple"),
)
demo.launch()

运行界面如图8-11:
在这里插入图片描述

图8-11

注意组件MultimodalTextbox的设置,此时函数echo_multimodal返回输入信息和上传的文件,MultimodalTextbox可以正确显示函数返回的消息和文件。

8.4.2 返回直接修改chatbot_value

我们有时希望通过自定义事件(而非gr.ChatInterface内置事件)来修改参数chatbot的值。例如创建下拉菜单以预填充特定对话历史,或添加独立按钮以清除对话记录。gr.ChatInterface支持这些事件,但需要将gr.ChatInterface.chatbot_value作为事件的输入或输出组件。
本示例使用gr.Radio组件预填充特定对话的chatbot:

import gradio as gr
import random
def prefill_chatbot(choice):if choice == "Greeting":return [{"role": "user", "content": "Hi there!"},{"role": "assistant", "content": "Hello! How can I assist you today?"}]elif choice == "Complaint":return [{"role": "user", "content": "I'm not happy with the service."},{"role": "assistant", "content": "I'm sorry to hear that. Can you please tell me more about the issue?"}]else:return []
def random_response(message, history):return random.choice(["Yes", "No"])
with gr.Blocks() as demo:radio = gr.Radio(["Greeting", "Complaint", "Blank"])chat = gr.ChatInterface(random_response, type="messages")radio.change(prefill_chatbot, radio, chat.chatbot_value)
demo.launch()

运行界面如图8-12:
在这里插入图片描述

图8-12

当单击单选框的值时,chat.chatbot_value会修改对应ChatInterface中的参数chatbot,对应的聊天内容也会随之改变。

http://www.dtcms.com/a/301537.html

相关文章:

  • Java Ai(day03)
  • 【秋招笔试】7月26日科大讯飞秋招第一题
  • 【最新最完整】SpringAI-1.0.0开发MCP Server,搭建MCP Client 实战笔记(进阶+详细+完整代码)
  • AI Agent学习
  • MyBatis-Plus IService 接口全量方法实现与测试(续)
  • 【c++】从 “勉强能用” 到 “真正好用”:中文问答系统的 200 行关键优化——关于我用AI编写了一个聊天机器人……(16)
  • 中级全栈工程师笔试题
  • DP之背包基础
  • 详解力扣高频SQL50题之180. 连续出现的数字【困难】
  • CPA会计-5- 投资性房地产
  • 逆向入门(42)程序逆向篇-riijj_cm_20041121
  • 生态环境大数据技术专业的深度解析
  • 物理实验仿真平台设计与实现(抛体运动与电磁场交互)
  • 构建可扩展的状态系统:基于 ArkTS 的模块化状态管理设计与实现
  • MPI环形AllReduce算法实现与深度解析
  • lombok插件@NoArgsConstructor、@AllArgsConstructor、@RequiredArgsConstructor的区别
  • RS485 半双工系统中 DE 控制端默认 0 的技术原理与工程实践
  • (实用教程)Linux操作系统(二)
  • 零基础 “入坑” Java--- 十五、字符串String
  • 【I】题目解析
  • Spring MVC设计精粹:源码级架构解析与实践指南
  • 发布 VS Code 扩展的流程:以颜色主题为例
  • Python学习-----1.认识Python
  • 墨者:X-Forwarded-For注入漏洞实战
  • 解决ubantu系统下matplotlib中文乱码问题
  • MySQL进阶学习与初阶复习第四天
  • 数据库连接操作详解:左连接、右连接、全连接与内连接
  • ABP VNext + Elastic APM:微服务性能监控
  • 【优选算法】BFS解决最短路问题(单源)
  • 初始Redis:概念、特性、使用场景、安装教程