Create csvanswer.py
Browse files- csvanswer.py +59 -0
csvanswer.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import pandas as pd
|
3 |
+
|
4 |
+
from langchain_openai import ChatOpenAI
|
5 |
+
|
6 |
+
from langchain.agents import AgentExecutor
|
7 |
+
from langchain.agents.agent_types import AgentType
|
8 |
+
from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent, create_csv_agent
|
9 |
+
|
10 |
+
import chainlit as cl
|
11 |
+
|
12 |
+
from deep_translator import GoogleTranslator
|
13 |
+
|
14 |
+
def create_agent(filename: str):
|
15 |
+
"""
|
16 |
+
Create an agent that can access and use a large language model (LLM).
|
17 |
+
|
18 |
+
Args:
|
19 |
+
filename: The path to the CSV file that contains the data.
|
20 |
+
|
21 |
+
Returns:
|
22 |
+
An agent that can access and use the LLM.
|
23 |
+
"""
|
24 |
+
|
25 |
+
# Create an OpenAI object.
|
26 |
+
os.environ['OPENAI_API_KEY'] = os.environ['OPENAI_API_KEY']
|
27 |
+
llm = ChatOpenAI(temperature=0, model="gpt-4o-2024-05-13")
|
28 |
+
|
29 |
+
# Read the CSV file into a Pandas DataFrame.
|
30 |
+
df = pd.read_csv(filename)
|
31 |
+
|
32 |
+
# Create a Pandas DataFrame agent.
|
33 |
+
return create_csv_agent(llm, filename, verbose=False, allow_dangerous_code=True, handle_parsing_errors=True, agent_type=AgentType.OPENAI_FUNCTIONS)
|
34 |
+
|
35 |
+
|
36 |
+
async def LLMAnswer():
|
37 |
+
agent = create_agent("./public/surveyia.csv")
|
38 |
+
cb = cl.AsyncLangchainCallbackHandler()
|
39 |
+
try:
|
40 |
+
res = await agent.acall("Réponds en langue française à la question suivante : " + message.content, callbacks=[cb])
|
41 |
+
await cl.Message(author="COPILOT",content=GoogleTranslator(source='auto', target='fr').translate(res['output'])).send()
|
42 |
+
except ValueError as e:
|
43 |
+
res = str(e)
|
44 |
+
resArray = res.split(":")
|
45 |
+
ans = ''
|
46 |
+
if str(res).find('parsing') != -1:
|
47 |
+
for i in range(2,len(resArray)):
|
48 |
+
ans += resArray[i]
|
49 |
+
await cl.Message(author="COPILOT",content=ans.replace("`","")).send()
|
50 |
+
else:
|
51 |
+
await cl.Message(author="COPILOT",content="Reformulez votre requête, s'il vous plait 😃").send()
|
52 |
+
# Query the agent.
|
53 |
+
#response = query_agent(agent=agent, query=message.content)
|
54 |
+
# Decode the response.
|
55 |
+
#decoded_response = decode_response(response)
|
56 |
+
|
57 |
+
# Write the response to the Streamlit app.
|
58 |
+
#result = write_response(decoded_response)
|
59 |
+
#await cl.Message(author="COPILOT",content=GoogleTranslator(source='auto', target='fr').translate(result)).send()
|