-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
207 lines (168 loc) Β· 7.19 KB
/
app.py
File metadata and controls
207 lines (168 loc) Β· 7.19 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import time
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_deepseek import ChatDeepSeek
from langchain_community.callbacks.manager import get_openai_callback
from src.graph.workflow import create_workflow
st.set_page_config(
page_title="Data Analysis Assistant",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
import streamlit as st
with st.sidebar:
st.title("βοΈ Configuration")
st.divider()
st.subheader("Select LLM Provider")
llm_provider = st.selectbox(
"Choose LLM",
["OpenAI", "Claude", "DeepSeek"],
index=0
)
llm_models = {
"OpenAI": ["gpt-4o-mini", "gpt-4o", "gpt-5.2-2025-12-11"],
"Claude": ["claude-3-5-sonnet-20240620", "claude-3-7-sonnet-20250219"],
"DeepSeek": ["deepseek-chat"]
}
selected_model = st.selectbox(
"Choose Model",
llm_models[llm_provider]
)
st.subheader(f"{llm_provider} API Settings")
api_key = st.text_input(f"Enter your {llm_provider} API key", type="password")
session_key = f"{llm_provider.lower()}_api_key"
if api_key:
if llm_provider == "OpenAI" and not api_key.startswith(('sk-', 'org-')):
st.error("Invalid OpenAI API key format")
st.stop()
elif llm_provider == "Claude" and not api_key.startswith("sk-ant-"):
st.error("Invalid Claude API key format")
st.stop()
elif llm_provider == "DeepSeek" and not api_key.startswith("sk-"):
st.error("Invalid DeepSeek API key format")
st.stop()
st.session_state[session_key] = api_key
st.success(f"{llm_provider} API key configured! β
")
else:
if session_key in st.session_state:
del st.session_state[session_key]
st.warning(f"β οΈ Please enter your {llm_provider} API key")
st.stop()
st.title("π Data Analysis Assistant")
tab1, tab2 = st.tabs(["π― Overview", "π Instructions"])
with tab1:
st.markdown("""
Welcome to the Data Analysis Assistant! This tool helps you:
- π Analyze complex datasets with natural language
- π¨ Generate insightful visualizations
- π Create detailed summaries and reports
""")
with tab2:
st.markdown("""
**How to use:**
1. Upload your CSV or Excel file
2. Preview your data to ensure it's loaded correctly
3. Ask questions in natural language
4. Watch as the assistant analyzes your data step by step
""")
uploaded_file = st.file_uploader("π Upload your dataset", type=["csv", "xlsx"])
if uploaded_file:
try:
file_size = uploaded_file.size
if file_size > 200 * 1024 * 1024:
st.error("File size exceeds 200MB limit")
st.stop()
if uploaded_file.type == "text/csv":
df = pd.read_csv(uploaded_file)
else:
df = pd.read_excel(uploaded_file)
if df.empty:
st.error("The file contains no data")
st.stop()
if llm_provider == "OpenAI":
llm = ChatOpenAI(
model=selected_model,
temperature=0,
top_p=0.2,
api_key=st.session_state["openai_api_key"]
)
elif llm_provider == "Claude":
llm = ChatAnthropic(
model=selected_model,
temperature=0,
top_p=0.2,
api_key=st.session_state["claude_api_key"]
)
elif llm_provider == "DeepSeek":
llm = ChatDeepSeek(
model=selected_model,
temperature=0,
top_p=0.2,
api_key=st.session_state["deepseek_api_key"]
)
st.write(f"LLM Configured: **{llm_provider} - {selected_model}** β
")
workflow = create_workflow(llm, df)
st.dataframe(
df,
use_container_width=True,
height=300
)
st.divider()
st.subheader("πAsk Questions About Your Data")
question = st.text_input(
"",
placeholder="e.g., 'Show monthly sales trends' or 'Create a summary of revenue by region'",
key="question_input"
)
if st.button("π Analyze", use_container_width=True):
if not question:
st.warning("Please enter a question first")
st.stop()
try:
with st.status(label="π€ Analysis in Progress", state="running") as status:
with get_openai_callback() as cb:
state = workflow.invoke({
"user_query": question,
"error": None,
"iterations": 0
})
st.subheader("π Analysis Plan")
st.code(state["task_plan"], language='python')
st.subheader("π Generated Code")
st.code(state["code"], language='python')
if state.get("output"):
st.subheader("π Analysis Results")
for key, value in state["output"].items():
if isinstance(value, pd.DataFrame):
st.write(f"π {key}")
st.dataframe(value, use_container_width=True)
elif isinstance(value, go.Figure):
st.plotly_chart(value, use_container_width=True)
elif isinstance(value, pd.Series):
st.write(f"π {key}")
st.dataframe(pd.DataFrame(value), use_container_width=True)
else:
st.info(f"{key}: {value}")
time.sleep(2.0)
if state.get("answer"):
st.subheader("π Summary")
st.success(state["answer"])
col1, col2 = st.columns(2)
with col1:
st.caption(f"Total Tokens Used: {cb.total_tokens}")
with col2:
st.caption(f"Analysis Cost: ${cb.total_cost:.4f}")
status.update(label="β
Analysis Complete", state="complete")
except Exception as e:
st.error(f"An error occurred during analysis: {str(e)}")
st.info("π‘ If you're facing issues, try rephrasing your question or ensure your API key is correct.")
except Exception as e:
st.error(f"Error processing file: {str(e)}")
st.info("π‘ Please ensure your file is properly formatted and try again.")
else:
st.info("π Upload a CSV or Excel file to begin your analysis!")