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

在Streamlit应用中使用LangChain+ChatGPT无法显示可视化图表问题

解决Streamlit应用中LangChain CSV Agent无法显示可视化图表的问题

原代码的核心问题是:LangChain的CSV Agent在生成图表时默认调用matplotlib.pyplot.show(),该方法在Jupyter环境中可以直接渲染图表,但在Streamlit中无法自动显示,需要改用Streamlit提供的st.pyplot()方法来处理图表渲染。

以下是修改后的完整代码,附带关键修改说明:

import os
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from langchain.agents import create_csv_agent
from langchain.llms import OpenAI


def initialize_agent(openai_api_key, csv_path, verbose=False):
    agent = create_csv_agent(
        OpenAI(temperature=0, openai_api_key=openai_api_key),
        csv_path,
        verbose=verbose
    )
    return agent


def main():
    st.set_page_config(page_title="LangChain Streamlit App")
    st.title("LangChain Streamlit App")

    # 获取侧边栏输入的OpenAI API密钥
    openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password")
    if not openai_api_key:
        st.info("请添加您的OpenAI API密钥以继续。")
        st.stop()

    # 获取用户上传的CSV文件
    uploaded_file = st.file_uploader("上传CSV文件", type=["csv"])
    if not uploaded_file:
        st.info("请上传一个CSV文件以继续。")
        st.stop()

    # 读取CSV文件为DataFrame
    df = pd.read_csv(uploaded_file)

    # 显示DataFrame前几行
    st.write("已上传的CSV文件:")
    st.dataframe(df.head())

    # 保存为临时CSV文件
    temp_csv_path = "temp.csv"
    df.to_csv(temp_csv_path, index=False)

    # 关键修改1:替换matplotlib的show方法,适配Streamlit
    original_plt_show = plt.show
    plt.show = lambda fig=None: st.pyplot(plt.gcf() if fig is None else fig)

    agent = initialize_agent(openai_api_key, temp_csv_path)

    # 获取用户查询
    user_query = st.text_input("想问点什么:")

    if user_query:
        # 关键修改2:清空之前的matplotlib图形,避免图表重叠
        plt.clf()
        # 运行LangChain Agent处理查询
        response = agent.run(user_query)
        st.write("响应:")
        st.write(response)

    # 关键修改3:使用try-finally确保临时文件被删除,避免文件占用问题
    try:
        pass
    finally:
        if os.path.exists(temp_csv_path):
            os.remove(temp_csv_path)

    # 恢复matplotlib的原始show方法(可选,避免影响其他代码)
    plt.show = original_plt_show


if __name__ == "__main__":
    main()

关键修改说明:

  1. 替换matplotlib的show方法:将默认的plt.show()替换为调用st.pyplot(),这样当CSV Agent执行绘图代码并调用plt.show()时,图表会自动在Streamlit中渲染。
  2. 清空matplotlib图形:在处理新的用户查询前调用plt.clf(),清除之前的图形缓存,避免多次查询后图表重叠。
  3. 安全删除临时文件:使用try-finally块确保临时文件无论代码是否出错都会被删除,避免文件占用或残留问题。

额外提示:

  • 如果你的可视化使用Seaborn库,基于matplotlib,上述修改同样适用;
  • 如果使用Plotly库,则需要使用st.plotly_chart(),此时需要调整CSV Agent的绘图逻辑,或捕获Plotly图表对象后调用该方法显示;
  • 可以开启agent的verbose=True参数,查看agent执行的中间步骤,帮助排查绘图相关问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:06:10