Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List, Optional, Union
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import pandas as pd
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
from pandas import DataFrame
|
8 |
+
from smolagents import CodeAgent, LiteLLMModel, tool
|
9 |
+
|
10 |
+
# Load environment variables
|
11 |
+
load_dotenv()
|
12 |
+
|
13 |
+
def create_agent():
|
14 |
+
"""Create a CodeAgent instance with GPT-4 backend."""
|
15 |
+
model = LiteLLMModel(model_id="gpt-4o-mini")
|
16 |
+
|
17 |
+
@tool
|
18 |
+
def read_csv(filepath: str) -> DataFrame:
|
19 |
+
"""
|
20 |
+
Read a CSV file and return a pandas DataFrame.
|
21 |
+
|
22 |
+
Args:
|
23 |
+
filepath: Path to the CSV file
|
24 |
+
"""
|
25 |
+
return pd.read_csv(filepath)
|
26 |
+
|
27 |
+
@tool
|
28 |
+
def read_excel(filepath: str) -> DataFrame:
|
29 |
+
"""
|
30 |
+
Read an Excel file and return a pandas DataFrame.
|
31 |
+
|
32 |
+
Args:
|
33 |
+
filepath: Path to the Excel file
|
34 |
+
"""
|
35 |
+
return pd.read_excel(filepath)
|
36 |
+
|
37 |
+
agent = CodeAgent(
|
38 |
+
tools=[read_csv, read_excel],
|
39 |
+
model=model,
|
40 |
+
additional_authorized_imports=[
|
41 |
+
"pandas",
|
42 |
+
"numpy",
|
43 |
+
"matplotlib",
|
44 |
+
"seaborn",
|
45 |
+
"plotly",
|
46 |
+
"sklearn",
|
47 |
+
"scipy",
|
48 |
+
],
|
49 |
+
max_steps=5,
|
50 |
+
verbosity_level=1
|
51 |
+
)
|
52 |
+
return agent
|
53 |
+
|
54 |
+
def process_request(
|
55 |
+
files: Union[str, List[str]],
|
56 |
+
user_query: str,
|
57 |
+
api_key: str = "",
|
58 |
+
temperature: float = 0.7,
|
59 |
+
history: Optional[List[tuple]] = None
|
60 |
+
) -> tuple:
|
61 |
+
"""
|
62 |
+
Process user request with uploaded files and query.
|
63 |
+
|
64 |
+
Args:
|
65 |
+
files: Path or list of paths to uploaded files
|
66 |
+
user_query: Natural language query from user
|
67 |
+
api_key: Optional API key for GPT-4
|
68 |
+
temperature: Model temperature
|
69 |
+
history: Chat history
|
70 |
+
|
71 |
+
Returns:
|
72 |
+
Tuple of (output, error, new_history)
|
73 |
+
"""
|
74 |
+
if api_key:
|
75 |
+
os.environ["OPENAI_API_KEY"] = api_key
|
76 |
+
|
77 |
+
try:
|
78 |
+
# Create agent instance
|
79 |
+
agent = create_agent()
|
80 |
+
|
81 |
+
# Build context from files
|
82 |
+
file_context = ""
|
83 |
+
if isinstance(files, str):
|
84 |
+
files = [files]
|
85 |
+
|
86 |
+
for file in files:
|
87 |
+
filename = os.path.basename(file)
|
88 |
+
file_context += f"File uploaded: {filename}\n"
|
89 |
+
|
90 |
+
# Build complete prompt
|
91 |
+
prompt = f"""
|
92 |
+
{file_context}
|
93 |
+
|
94 |
+
User request: {user_query}
|
95 |
+
|
96 |
+
Please analyze the data and provide:
|
97 |
+
1. Code to perform the analysis
|
98 |
+
2. Explanation of approach
|
99 |
+
3. Visualizations if relevant
|
100 |
+
4. Key insights and findings
|
101 |
+
"""
|
102 |
+
|
103 |
+
# Execute agent
|
104 |
+
result = agent.run(prompt)
|
105 |
+
|
106 |
+
# Update history
|
107 |
+
new_history = history or []
|
108 |
+
new_history.append((user_query, result))
|
109 |
+
|
110 |
+
return result, None, new_history
|
111 |
+
|
112 |
+
except Exception as e:
|
113 |
+
return None, str(e), history
|
114 |
+
|
115 |
+
# Create Gradio interface
|
116 |
+
def create_interface():
|
117 |
+
"""Create Gradio interface for the AI coding assistant."""
|
118 |
+
|
119 |
+
with gr.Blocks(title="AI Coding Assistant") as interface:
|
120 |
+
gr.Markdown("""
|
121 |
+
# AI Coding Assistant
|
122 |
+
Upload data files and ask questions in natural language to get code, analysis and visualizations.
|
123 |
+
""")
|
124 |
+
|
125 |
+
with gr.Row():
|
126 |
+
with gr.Column():
|
127 |
+
files = gr.File(
|
128 |
+
label="Upload Data Files",
|
129 |
+
file_types=[".csv", ".xlsx", ".xls"],
|
130 |
+
multiple=True
|
131 |
+
)
|
132 |
+
query = gr.Textbox(
|
133 |
+
label="What would you like to analyze?",
|
134 |
+
placeholder="e.g., Create a scatter plot comparing column A vs B"
|
135 |
+
)
|
136 |
+
api_key = gr.Textbox(
|
137 |
+
label="API Key (Optional)",
|
138 |
+
placeholder="Your OpenAI API key",
|
139 |
+
type="password"
|
140 |
+
)
|
141 |
+
temperature = gr.Slider(
|
142 |
+
label="Temperature",
|
143 |
+
minimum=0.0,
|
144 |
+
maximum=1.0,
|
145 |
+
value=0.7,
|
146 |
+
step=0.1
|
147 |
+
)
|
148 |
+
submit = gr.Button("Analyze")
|
149 |
+
|
150 |
+
with gr.Column():
|
151 |
+
output = gr.Markdown(label="Output")
|
152 |
+
error = gr.Markdown(label="Errors")
|
153 |
+
|
154 |
+
# Hidden state for chat history
|
155 |
+
history = gr.State([])
|
156 |
+
|
157 |
+
# Handle submissions
|
158 |
+
submit.click(
|
159 |
+
process_request,
|
160 |
+
inputs=[files, query, api_key, temperature, history],
|
161 |
+
outputs=[output, error, history]
|
162 |
+
)
|
163 |
+
|
164 |
+
# Add examples
|
165 |
+
gr.Examples(
|
166 |
+
examples=[
|
167 |
+
[
|
168 |
+
None,
|
169 |
+
"Create a scatter plot showing the relationship between column A and B, with a trend line",
|
170 |
+
],
|
171 |
+
[
|
172 |
+
None,
|
173 |
+
"Calculate summary statistics and identify any outliers in the numerical columns",
|
174 |
+
],
|
175 |
+
[
|
176 |
+
None,
|
177 |
+
"Perform clustering analysis on the data and visualize the clusters",
|
178 |
+
],
|
179 |
+
],
|
180 |
+
inputs=[files, query],
|
181 |
+
)
|
182 |
+
|
183 |
+
return interface
|
184 |
+
|
185 |
+
if __name__ == "__main__":
|
186 |
+
interface = create_interface()
|
187 |
+
interface.launch()
|