AI实践:Gradio 部署易速鲜花聊天机器人 | 豆包MarsCode AI 刷题

21 阅读4分钟

Gradio 是什么

Gradio是一个用于创建机器学习模型交互式界面的 Python 库。通过Gradio,可以快速地为模型构建一个可视化的、易于使用的Web界面,无需编写任何Web前端代码。

Gradio 支持多种不同类型的输入(如文本、图像、音频等)和输出(如文本、图像、HTML等),并且可以直接在 Python 脚本中定义这些输入/输出和处理函数之间的关系。这使得 Gradio 非常适合用来演示和测试各种AI/ML模型,或者用来收集用户反馈。

一旦创建了一个Gradio应用,并启动了它,它就会在本地启动一个Web服务器,并生成一个 URL。然后你就可以在浏览器中打开这个URL来与你的模型进行交互。同时,如果需要将应用公开到Internet上供他人使用,也可以通过ngrok等工具实现。

“块”(Block)和“接口”(Interface)

在 Gradio 中,“块”(Block)和“接口”(Interface)是用来构建用户界面的两个不同抽象层:

  • Interface 是 Gradio 的早期抽象,适用于简单、快速地构建应用程序界面。它提供了一种直观的方式来将函数与输入输出组件连接起来。
  • Block 是 Gradio 的更高级抽象,适合构建更复杂的、多样化的界面。它支持更灵活的布局和交互,允许你精确控制组件的排列和行为。

以下是它们的主要区别:

特性InterfaceBlocks
用途适合快速、简单的应用适合复杂、多组件的应用
灵活性提供预定义布局提供完全自定义布局
组件组合通常只有输入、输出组件可以包含任意多个组件(输入、输出、布局等)
可扩展性功能简单,支持少量自定义更灵活,支持复杂交互和自定义逻辑

代码示例

Interface 示例:简单的文本输入输出
python
复制代码
import gradio as gr

# 定义简单的函数
def greet(name):
    return f"Hello, {name}!"

# 创建 Interface
interface = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(label="Your Name"),
    outputs=gr.Textbox(label="Greeting")
)

# 启动应用
interface.launch()
Blocks 示例:复杂布局与交互
python
复制代码
import gradio as gr

# 定义多个函数
def greet(name):
    return f"Hello, {name}!"

def length_of_name(name):
    return len(name)

# 创建 Blocks 应用
with gr.Blocks() as demo:
    gr.Markdown("# Welcome to the Gradio App!")
    with gr.Row():
        name_input = gr.Textbox(label="Your Name")
        greet_button = gr.Button("Greet Me")
    with gr.Row():
        greeting_output = gr.Textbox(label="Greeting")
        length_output = gr.Textbox(label="Length of Your Name")
    
    # 定义交互逻辑
    greet_button.click(
        fn=greet, 
        inputs=name_input, 
        outputs=greeting_output
    )
    greet_button.click(
        fn=length_of_name, 
        inputs=name_input, 
        outputs=length_output
    )

# 启动应用
demo.launch()

对比

  1. Interface 示例:

    • 只需要一个输入框和一个输出框,适合简单的功能。
    • 默认使用垂直布局,不能自定义布局。
  2. Blocks 示例:

    • 使用 Row 和其他布局组件来精确安排界面。
    • 同时定义了两个输出(问候语和名字长度),支持更多的组件和交互。

部署聊天机器人

下面我们在易速鲜花聊天客服机器人的开发 | 豆包MarsCode AI 刷题这篇文章的基础上,使用Gradio来部署聊天机器人。

import gradio as gr

# Gradio 接口函数
def chat_with_bot(history, user_input):
    """
    history: 保存多轮对话的历史记录([(用户输入, 机器人回复), ...])。
    user_input: 当前用户的输入问题。
    """
    # 从历史记录中提取多轮对话的上下文
    try:
        # 将历史记录转换为符合Gradio格式的消息结构
        formatted_history = []
        for h in history:
            formatted_history.append({'role': 'user', 'content': h[0]})
            formatted_history.append({'role': 'assistant', 'content': h[1]})

        # 获取机器人回答
        response = bot.ask(user_input)

        # 将当前的用户输入和机器人的回答加入历史记录
        history.append((user_input, response))

        # 格式化并返回
        formatted_history.append({'role': 'user', 'content': user_input})
        formatted_history.append({'role': 'assistant', 'content': response})

        # 清空输入框内容
        #user_input.update(value="")

        return formatted_history, history, gr.update(value="")  # 返回更新后的历史记录

    except Exception as e:
        return history, [(user_input, f"对话失败: {e}")], gr.update(value="")


if __name__ == "__main__":
    # 创建 Gradio 界面
    with gr.Blocks() as demo:
        gr.Markdown("### 🌺 花卉行家聊天机器人")
        chatbot = gr.Chatbot(label="花卉行家", height=500, type='messages')
        user_input = gr.Textbox(
            placeholder="请输入问题,比如:给准备结婚的女朋友买什么花?",
            label="你的提问",
            submit_btn=True
        )
        clear_btn = gr.Button("清除聊天记录")

        # 定义多轮对话历史
        state = gr.State([])  # 初始化历史为空列表

        # 按钮和输入事件绑定
        user_input.submit(chat_with_bot, [state, user_input], [chatbot, state, user_input])
        clear_btn.click(lambda: ([], []), [], [chatbot, state])  # 清空聊天记录

    # 启动 Gradio 应用
    demo.launch()

运行上面代码后,会显示share的链接,点击链接进去即可和聊天机器人对话:

截屏2024-11-17 18.10.45.png

截屏2024-11-17 18.10.56.png

至此,我们已经成功使用Gradio来部署易速鲜花聊天机器人!🎉🎉🎉