ValueError: Expected str or list, got <class 'streamlit.runtime.uploaded_file_manager.UploadedFile'>

import streamlit as st
from langchain.agents import create_csv_agent
from langchain.llms import OpenAI
from dotenv import load_dotenv

      
def main():
    load_dotenv()

    st.set_page_config(page_title='Ask your CSV')
    st.header("Ask your CSV")

    file = st.file_uploader('upload file', type='csv')


    if file:
        llm = OpenAI(temperature=0)
        user_input = st.text_input('Question here:')

        agent = create_csv_agent(llm, file, verbose=True)
        if user_input:
            response = agent.run(user_input)
            st.write(response)


if __name__ == "__main__":
    main()

I get an error

agent = create_csv_agent(llm, file, verbose=True)
  File "/home/appuser/venv/lib/python3.9/site-packages/langchain/agents/agent_toolkits/csv/base.py", line 33, in create_csv_agent
    raise ValueError(f"Expected str or list, got {type(path)}")

ValueError: Expected str or list, got <class 'streamlit.runtime.uploaded_file_manager.UploadedFile'>

Meanwhile the code runs well locally.

create_csv_agent is expecting the Path to a csv file, so you need to provide it a path, rather than an uploaded object itself. The easiest way to do this is by creating a NamedTemporaryFile, writing the uploaded content to that file, and pass that file’s path to create_csv_agent:

from tempfile import NamedTemporaryFile

import streamlit as st
from dotenv import load_dotenv
from langchain.agents import create_csv_agent
from langchain.llms import OpenAI


def main():
    load_dotenv()

    st.set_page_config(page_title="Ask your CSV")
    st.header("Ask your CSV")

    file = st.file_uploader("upload file", type="csv")

    if file:
        with NamedTemporaryFile() as f: # Create temporary file
            f.write(file.getvalue()) # Save uploaded contents to file
            llm = OpenAI(temperature=0)
            user_input = st.text_input("Question here:")

            agent = create_csv_agent(llm, f.name, verbose=True) # Pass temporary filename to create_csv_agent
            if user_input:
                response = agent.run(user_input)
                st.write(response)


if __name__ == "__main__":
    main()

Hi @blackary,
One thing β†’ You might need to flush() after writing to the file.

This is working for me!

if user_csv is not None:
        with NamedTemporaryFile(mode='w+b', suffix=".csv") as f:
            f.write(user_csv.getvalue())
            f.flush()
            llm = OpenAI(temperature=0)
            user_input = st.text_input("Question here:")
            agent = create_csv_agent(llm, f.name, verbose=True)
            if user_input:
                response = agent.run(user_input)
                st.write(response)

By the way, thanks @blackary for solution!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.