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

使用OpenAI与Streamlit开发CSV对话应用遇ValueError问题求助

修复Streamlit+OpenAI Chat with CSV的ValueError问题

问题根源

你碰到的错误是因为直接把Streamlit的UploadedFile对象传给了需要字符串/列表输入的方法(比如OpenAI接口或数据处理函数),没有先将上传文件的内容转换成正确格式。

具体修复步骤

1. 正确读取上传文件内容

Streamlit上传的UploadedFile是文件对象,不能直接当作字符串传入接口,需要先读取内容:

import streamlit as st
import pandas as pd

uploaded_file = st.file_uploader("上传CSV文件", type="csv")

if uploaded_file is not None:
    # 方式1:读取为字符串(保留原始CSV格式)
    csv_content = uploaded_file.read().decode("utf-8")
    # 方式2:读取为DataFrame后转成易读的字符串格式
    df = pd.read_csv(uploaded_file)
    csv_content = df.to_string()

注:如果CSV是GBK编码,把decode("utf-8")改成decode("gbk")。

2. 将处理后的内容传入OpenAI接口

把转换后的字符串传给OpenAI的消息参数,而非原始的UploadedFile对象:

from openai import OpenAI

client = OpenAI(api_key=st.text_input("输入OpenAI API Key", type="password"))

if uploaded_file is not None and csv_content:
    user_query = st.text_input("输入你的问题")
    if user_query:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "你是CSV数据分析助手,根据提供的CSV内容回答问题"},
                {"role": "user", "content": f"CSV内容:\n{csv_content}\n\n问题:{user_query}"}
            ]
        )
        st.write(response.choices[0].message.content)

3. 额外注意事项

  • 必须先判断uploaded_file不为空再处理,避免空对象报错
  • 如果CSV文件过大,建议截取前N行内容传给OpenAI,或者用Embedding方式拆分处理(简易版可先限制上传文件大小)
  • 加入异常捕获,方便排查其他文件处理问题

完整可运行代码片段

import streamlit as st
import pandas as pd
from openai import OpenAI

st.title("Chat with CSV")

# 输入API Key
api_key = st.text_input("输入OpenAI API Key", type="password")
if not api_key:
    st.warning("请先输入API Key")
else:
    client = OpenAI(api_key=api_key)
    # 上传文件
    uploaded_file = st.file_uploader("选择CSV文件", type=["csv"])
    
    if uploaded_file is not None:
        try:
            # 读取并预览CSV
            df = pd.read_csv(uploaded_file)
            st.subheader("CSV数据预览")
            st.dataframe(df.head())
            # 转换为字符串
            csv_text = df.to_string()
            
            # 用户提问
            user_query = st.text_input("请输入你对CSV的问题")
            if user_query:
                # 调用OpenAI
                response = client.chat.completions.create(
                    model="gpt-3.5-turbo",
                    messages=[
                        {"role": "system", "content": "你是专业的CSV数据分析员,详细回答用户基于CSV数据的问题"},
                        {"role": "user", "content": f"CSV数据:\n{csv_text}\n\n用户问题:{user_query}"}
                    ]
                )
                st.subheader("回答")
                st.write(response.choices[0].message.content)
        except Exception as e:
            st.error(f"文件处理出错:{str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:33:11