import os import pandas as pd from langchain_openai import ChatOpenAI from langchain.agents import AgentExecutor from langchain.agents.agent_types import AgentType from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent, create_csv_agent import chainlit as cl from deep_translator import GoogleTranslator def create_agent(filename: str): """ Create an agent that can access and use a large language model (LLM). Args: filename: The path to the CSV file that contains the data. Returns: An agent that can access and use the LLM. """ # Create an OpenAI object. os.environ['OPENAI_API_KEY'] = os.environ['OPENAI_API_KEY'] llm = ChatOpenAI(temperature=0, model="gpt-4o-2024-05-13") # Read the CSV file into a Pandas DataFrame. df = pd.read_csv(filename) # Create a Pandas DataFrame agent. return create_csv_agent(llm, filename, verbose=False, allow_dangerous_code=True, handle_parsing_errors=True, agent_type=AgentType.OPENAI_FUNCTIONS) async def LLMAnswer(message): agent = create_agent("./public/surveyia.csv") cb = cl.AsyncLangchainCallbackHandler() try: res = await agent.acall("Réponds en langue française à la question suivante : " + message.content, callbacks=[cb]) await cl.Message(author="COPILOT",content=GoogleTranslator(source='auto', target='fr').translate(res['output'])).send() except ValueError as e: res = str(e) resArray = res.split(":") ans = '' if str(res).find('parsing') != -1: for i in range(2,len(resArray)): ans += resArray[i] await cl.Message(author="COPILOT",content=ans.replace("`","")).send() else: await cl.Message(author="COPILOT",content="Reformulez votre requête, s'il vous plait 😃").send() # Query the agent. #response = query_agent(agent=agent, query=message.content) # Decode the response. #decoded_response = decode_response(response) # Write the response to the Streamlit app. #result = write_response(decoded_response) #await cl.Message(author="COPILOT",content=GoogleTranslator(source='auto', target='fr').translate(result)).send()