You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求问:Gradio中Plotly图表响应示例异常及Multimodal模式实践经验

在Gradio多模态聊天机器人中返回Plotly图表的可行方案

以下是经过验证的实现方案,能在Gradio Blocks的多模态聊天场景中正常返回Plotly图表:

核心实现要点

  • 确保使用Gradio 4.x及以上版本,该版本对Plotly图表的渲染支持更稳定
  • Chatbot组件支持直接接收Plotly的fig对象作为消息内容,无需额外转换为HTML或图片
  • 在响应函数中,将图表作为元组元素返回(适配多模态消息格式)

可运行代码示例

import gradio as gr
import plotly.express as px
import pandas as pd

def generate_plot(message, history):
    # 模拟根据用户输入生成数据(实际场景可替换为业务逻辑)
    df = pd.DataFrame({
        "x": [1, 2, 3, 4, 5],
        "y": [i**2 for i in range(1,6)]
    })
    # 创建Plotly图表
    fig = px.line(df, x="x", y="y", title="示例折线图")
    # 返回图表作为多模态消息
    return (fig,)

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(height=500)
    msg = gr.Textbox(label="输入请求")
    clear = gr.Button("清空聊天")

    def user(user_message, history):
        return "", history + [[user_message, None]]

    def bot(history):
        user_message = history[-1][0]
        # 调用生成图表的函数
        response = generate_plot(user_message, history)
        history[-1][1] = response
        return history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()

常见问题排查

  • 如果图表无法渲染:检查是否安装了对应版本的依赖,执行pip install gradio>=4.0 plotly>=5.0 pandas更新库
  • 避免手动转换fig为HTML:Gradio会自动处理Plotly对象的渲染,手动转换反而可能导致显示异常
  • 确保响应函数返回格式正确:必须将图表放在元组中(如(fig,)),否则Chatbot无法识别为多模态内容

内容的提问来源于stack exchange,提问作者NiMa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:12:33