File size: 2,237 Bytes
6c8e68a cbb8c9c 6c8e68a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
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() |