Veda0718 commited on
Commit
ef3fe43
·
verified ·
1 Parent(s): 3b6c4c1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import io
4
+ import base64
5
+ import pandas as pd
6
+ import matplotlib.pyplot as plt
7
+ import seaborn as sns
8
+ from langchain_openai import ChatOpenAI
9
+ from langchain_experimental.agents.agent_toolkits import create_csv_agent
10
+ from langchain.agents.agent_types import AgentType
11
+
12
+ class CSVChatbot:
13
+ def __init__(self):
14
+ self.agent = None
15
+ self.file_path = None
16
+
17
+ def initialize_agent(self, file, api_key):
18
+ if file is None or api_key.strip() == "":
19
+ return "Please upload a CSV file and enter your OpenAI API key."
20
+
21
+ self.file_path = file.name
22
+ os.environ["OPENAI_API_KEY"] = api_key
23
+
24
+ try:
25
+ model = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
26
+ self.agent = create_csv_agent(
27
+ llm=model,
28
+ path=self.file_path,
29
+ verbose=True,
30
+ agent_type=AgentType.OPENAI_FUNCTIONS,
31
+ allow_dangerous_code=True
32
+ )
33
+ return "CSV file loaded and agent initialized successfully!"
34
+ except Exception as e:
35
+ return f"An error occurred: {str(e)}"
36
+
37
+ def chat(self, message, history):
38
+ if self.agent is None:
39
+ return "Please initialize the agent first by uploading a CSV file and providing an API key."
40
+
41
+ try:
42
+ CSV_PROMPT_PREFIX = "First get the column names from the CSV file, then answer the question."
43
+ CSV_PROMPT_SUFFIX = """
44
+ - **ALWAYS** before giving the Final Answer, try another method.
45
+ Then reflect on the answers of the two methods you did and ask yourself
46
+ if it answers correctly the original question.
47
+ If you are not sure, try another method.
48
+ - If the methods tried do not give the same result, reflect and
49
+ try again until you have two methods that have the same result.
50
+ - If you still cannot arrive to a consistent result, say that
51
+ you are not sure of the answer.
52
+ - If you are sure of the correct answer, create a beautiful
53
+ and thorough response using Markdown.
54
+ - **DO NOT MAKE UP AN ANSWER OR USE PRIOR KNOWLEDGE,
55
+ ONLY USE THE RESULTS OF THE CALCULATIONS YOU HAVE DONE**.
56
+ - **ALWAYS**, as part of your "Final Answer", explain how you got
57
+ to the answer on a section that starts with: "\n\nExplanation:\n".
58
+ In the explanation, mention the column names that you used to get
59
+ to the final answer.
60
+ """
61
+ result = self.agent.run(CSV_PROMPT_PREFIX + message + CSV_PROMPT_SUFFIX)
62
+ fig = plt.gcf()
63
+ if fig.get_axes():
64
+ buf = io.BytesIO()
65
+ fig.savefig(buf, format='png')
66
+ buf.seek(0)
67
+ img_str = base64.b64encode(buf.getvalue()).decode()
68
+ img_markdown = f"![plot](data:image/png;base64,{img_str})"
69
+ plt.close(fig) # Close the figure to free up memory
70
+ return result + "\n\n" + img_markdown
71
+ else:
72
+ return result
73
+ except Exception as e:
74
+ return f"An error occurred: {str(e)}"
75
+
76
+ csv_chatbot = CSVChatbot()
77
+
78
+ with gr.Blocks() as demo:
79
+ gr.Markdown("# CSV Analysis Chatbot with OpenAI")
80
+
81
+ with gr.Row():
82
+ file_input = gr.File(label="Upload CSV File")
83
+ api_key_input = gr.Textbox(label="Enter OpenAI API Key", type="password")
84
+
85
+ initialize_button = gr.Button("Initialize Agent")
86
+ init_output = gr.Textbox(label="Initialization Status")
87
+
88
+ chatbot = gr.Chatbot()
89
+ msg = gr.Textbox()
90
+ clear = gr.Button("Clear")
91
+
92
+ def user(user_message, history):
93
+ return "", history + [[user_message, None]]
94
+
95
+ def bot(history):
96
+ user_message = history[-1][0]
97
+ bot_message = csv_chatbot.chat(user_message, history)
98
+ history[-1][1] = bot_message
99
+ return history
100
+
101
+ def clear_chat():
102
+ return None
103
+
104
+ initialize_button.click(csv_chatbot.initialize_agent, inputs=[file_input, api_key_input], outputs=init_output)
105
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
106
+ bot, chatbot, chatbot
107
+ )
108
+ clear.click(clear_chat, None, chatbot, queue=False)
109
+
110
+ demo.launch()