Streamlit文件上传器结合LangChain create_csv_agent触发ValueError问题求助
Streamlit文件上传器结合LangChain create_csv_agent触发ValueError问题求助
我来帮你解决这个问题!你遇到的ValueError核心原因是参数类型不匹配,咱们一步步理清楚:
问题根源
你调用user_csv.read()后得到的是字节流数据,但LangChain的create_csv_agent第二个参数path接受的是以下几种类型:
- 本地CSV文件的路径字符串
- 路径字符串组成的列表
- 类文件对象(比如Streamlit返回的
UploadedFile本身)
直接传递字节流会触发类型检查失败,也就是你看到的Expected str or list, got <class 'bytes'>错误。
两种快速解决方法
方法一:直接传递UploadedFile对象(最简单)
Streamlit的file_uploader返回的UploadedFile本身就是符合要求的类文件对象,不需要调用.read(),直接传进去就行:
from langchain.agents import create_csv_agent from langchain.llms import OpenAI from dotenv import load_dotenv import streamlit as st def main(): load_dotenv() st.set_page_config(page_title="Ask your CSV ", page_icon="📊") st.header("Ask your CSV") user_csv = st.file_uploader("Upload a CSV file", type="csv") if user_csv is not None: llm = OpenAI(temperature=0) # 直接传user_csv对象,不要加.read() agent = create_csv_agent(llm, user_csv, verbose=True) user_question = st.text_input("Ask your question") if user_question is not None and user_question != "": response = agent.run(user_question) st.write(response) if __name__ == "__main__": main()
方法二:临时保存文件到本地(适合需要持久化文件的场景)
如果后续需要用到文件路径,也可以把上传的字节流保存为本地临时文件,再传递路径:
from langchain.agents import create_csv_agent from langchain.llms import OpenAI from dotenv import load_dotenv import streamlit as st import tempfile import os def main(): load_dotenv() st.set_page_config(page_title="Ask your CSV ", page_icon="📊") st.header("Ask your CSV") user_csv = st.file_uploader("Upload a CSV file", type="csv") if user_csv is not None: # 创建临时文件保存上传的CSV with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp_file: tmp_file.write(user_csv.getbuffer()) tmp_path = tmp_file.name llm = OpenAI(temperature=0) # 传递临时文件路径给agent agent = create_csv_agent(llm, tmp_path, verbose=True) user_question = st.text_input("Ask your question") if user_question is not None and user_question != "": response = agent.run(user_question) st.write(response) # 用完后删除临时文件,避免占用磁盘空间 os.unlink(tmp_path) if __name__ == "__main__": main()
验证效果
你可以试试第一种方法,改动最小,直接去掉.read()就能解决问题,上传CSV后就能正常提问啦~
备注:内容来源于stack exchange,提问作者Abdulhakim
相关产品推荐
相关产品推荐

