walaa2022 commited on
Commit
36f6a1d
·
verified ·
1 Parent(s): b167b1a

Update pages/dashboard-page.py

Browse files
Files changed (1) hide show
  1. pages/dashboard-page.py +127 -283
pages/dashboard-page.py CHANGED
@@ -1,48 +1,11 @@
 
 
 
 
 
1
  def render_financial_dashboard(startup_data, cash_flow_df):
2
- """
3
- Render the AI-powered financial dashboard page.
4
-
5
- This dashboard uses AI to analyze financial data and provide actionable insights
6
- to startup founders, helping them make better decisions about their runway,
7
- spending, and financial health.
8
- """
9
- st.markdown("<h1 class='main-header'>Financial Dashboard</h1>", unsafe_allow_html=True)
10
- st.markdown("<p class='sub-header'>AI-powered financial insights at a glance</p>", unsafe_allow_html=True)
11
-
12
- # How AI helps with financial dashboards
13
- with st.expander("ℹ️ How AI enhances your financial dashboard"):
14
- st.markdown("""
15
- ### How AI Powers Your Financial Dashboard
16
-
17
- The financial dashboard uses AI to transform raw financial data into actionable intelligence:
18
-
19
- - **Automated Analysis**: Instead of manually calculating runway and burn rates, our AI model analyzes your data and highlights critical trends
20
- - **Predictive Forecasting**: AI forecasts your runway using pattern recognition and predictive analytics to account for varying growth rates
21
- - **Anomaly Detection**: The system identifies unusual spending patterns or concerning financial trends that human analysis might miss
22
- - **Strategic Recommendations**: Based on your specific financial situation, the AI provides tailored recommendations to optimize your runway
23
- - **Benchmark Comparison**: Your metrics are automatically compared against industry standards for startups at your funding stage
24
-
25
- This helps founders save time, catch financial issues early, and make data-driven decisions without needing financial expertise.
26
- """)
27
-
28
- # AI Insights Summary
29
- insights_key = f"dashboard_{date.today().isoformat()}"
30
- if insights_key not in st.session_state.insights_cache:
31
- insights = generate_ai_response(f"""
32
- You are a financial advisor for startups. Based on this startup's data:
33
- - Current cash: ${startup_data['cash']}
34
- - Monthly burn rate: ${startup_data['burn_rate']}
35
- - Monthly revenue: ${startup_data['revenue']}
36
- - Monthly growth rate: {startup_data['growth_rate'] * 100}%
37
-
38
- Provide the top 3 most important financial insights that the founder should know today.
39
- Format each insight as a brief, action-oriented bullet point.
40
- """, simulate=True)
41
- st.session_state.insights_cache[insights_key] = insights
42
-
43
- with st.expander("📊 AI Financial Insights", expanded=True):
44
- st.markdown("<span class='ai-badge'>AI-Generated Insights</span>", unsafe_allow_html=True)
45
- st.markdown(st.session_state.insights_cache[insights_key])
46
 
47
  # Key metrics
48
  col1, col2, col3, col4 = st.columns(4)
@@ -55,42 +18,14 @@ def render_financial_dashboard(startup_data, cash_flow_df):
55
  startup_data['growth_rate']
56
  )
57
 
58
- # Determine status colors based on financial health indicators
59
- runway_status = "danger-metric" if runway_months < 6 else ("warning-metric" if runway_months < 9 else "good-metric")
60
- burn_status = "danger-metric" if startup_data['burn_rate'] > 100000 else ("warning-metric" if startup_data['burn_rate'] > 80000 else "good-metric")
61
- revenue_status = "good-metric" if startup_data['revenue'] > 20000 else ("warning-metric" if startup_data['revenue'] > 10000 else "danger-metric")
62
-
63
  with col1:
64
- st.markdown(f"""
65
- <div class='metric-card'>
66
- <p class='metric-label'>Current Cash</p>
67
- <p class='metric-value'>${startup_data['cash']:,}</p>
68
- </div>
69
- """, unsafe_allow_html=True)
70
-
71
  with col2:
72
- st.markdown(f"""
73
- <div class='metric-card'>
74
- <p class='metric-label'>Monthly Burn</p>
75
- <p class='metric-value {burn_status}'>${startup_data['burn_rate']:,}</p>
76
- </div>
77
- """, unsafe_allow_html=True)
78
-
79
  with col3:
80
- st.markdown(f"""
81
- <div class='metric-card'>
82
- <p class='metric-label'>Monthly Revenue</p>
83
- <p class='metric-value {revenue_status}'>${startup_data['revenue']:,}</p>
84
- </div>
85
- """, unsafe_allow_html=True)
86
-
87
  with col4:
88
- st.markdown(f"""
89
- <div class='metric-card'>
90
- <p class='metric-label'>Runway</p>
91
- <p class='metric-value {runway_status}'>{runway_months} months</p>
92
- </div>
93
- """, unsafe_allow_html=True)
94
 
95
  # Financial charts
96
  st.subheader("Financial Overview")
@@ -101,29 +36,19 @@ def render_financial_dashboard(startup_data, cash_flow_df):
101
  # Runway projection chart
102
  fig = px.line(runway_df.reset_index(), x='index', y='Cumulative_Cash',
103
  title="Cash Runway Projection",
104
- labels={'index': 'Date', 'Cumulative_Cash': 'Remaining Cash ($)'},
105
- color_discrete_sequence=['#0066cc'])
106
- fig.add_hline(y=0, line_dash="dash", line_color="red", annotation_text="Out of Cash")
107
- fig.update_layout(
108
- height=400,
109
- plot_bgcolor='rgba(240,247,255,0.8)',
110
- xaxis_title="Date",
111
- yaxis_title="Cash Balance ($)",
112
- font=dict(family="Arial, sans-serif", size=12),
113
- margin=dict(l=20, r=20, t=40, b=20),
114
- )
115
  st.plotly_chart(fig, use_container_width=True)
116
 
117
  # Get analysis from Gemini
118
- with st.expander("🔍 AI Financial Analysis", expanded=True):
119
- # Use cache to avoid repeated API calls
120
- analysis_key = f"runway_{date.today().isoformat()}"
121
- if analysis_key not in st.session_state.insights_cache:
122
- analysis = get_runway_analysis(startup_data)
123
- st.session_state.insights_cache[analysis_key] = analysis
124
-
125
- st.markdown("<span class='ai-badge'>AI Financial Analysis</span>", unsafe_allow_html=True)
126
- st.markdown(st.session_state.insights_cache[analysis_key])
127
 
128
  with tab2:
129
  # Revenue vs Expenses chart
@@ -131,71 +56,17 @@ def render_financial_dashboard(startup_data, cash_flow_df):
131
  fig = px.bar(rev_exp_df, x='Month', y=['Revenue', 'Total_Expenses'],
132
  title="Revenue vs. Expenses",
133
  barmode='group',
134
- labels={'value': 'Amount ($)', 'variable': 'Category'},
135
- color_discrete_sequence=['#28a745', '#dc3545'])
136
- fig.update_layout(
137
- height=400,
138
- plot_bgcolor='rgba(240,247,255,0.8)',
139
- xaxis_title="Month",
140
- yaxis_title="Amount ($)",
141
- font=dict(family="Arial, sans-serif", size=12),
142
- legend_title="",
143
- margin=dict(l=20, r=20, t=40, b=20),
144
- )
145
  st.plotly_chart(fig, use_container_width=True)
146
-
147
- # Calculate revenue growth
148
- revenue_growth = [(cash_flow_df['Revenue'].iloc[i] / cash_flow_df['Revenue'].iloc[i-1] - 1) * 100 if i > 0 else 0
149
- for i in range(len(cash_flow_df))]
150
- avg_growth = sum(revenue_growth[1:]) / len(revenue_growth[1:])
151
-
152
- col1, col2 = st.columns(2)
153
- with col1:
154
- st.metric("Average Monthly Revenue Growth", f"{avg_growth:.1f}%")
155
- with col2:
156
- expense_growth = (cash_flow_df['Total_Expenses'].iloc[-1] / cash_flow_df['Total_Expenses'].iloc[0] - 1) * 100
157
- st.metric("Total Expense Growth", f"{expense_growth:.1f}%", delta=f"{expense_growth - avg_growth:.1f}%", delta_color="inverse")
158
 
159
  with tab3:
160
  # Burn rate trend
161
  fig = px.line(cash_flow_df, x='Month', y='Net_Burn',
162
  title="Monthly Net Burn Trend",
163
- labels={'Net_Burn': 'Net Burn ($)'},
164
- color_discrete_sequence=['#dc3545'])
165
- fig.update_layout(
166
- height=400,
167
- plot_bgcolor='rgba(240,247,255,0.8)',
168
- xaxis_title="Month",
169
- yaxis_title="Net Burn ($)",
170
- font=dict(family="Arial, sans-serif", size=12),
171
- margin=dict(l=20, r=20, t=40, b=20),
172
- )
173
-
174
- # Add efficiency ratio as a second y-axis
175
- efficiency_ratio = [cash_flow_df['Revenue'].iloc[i] / cash_flow_df['Total_Expenses'].iloc[i] * 100
176
- for i in range(len(cash_flow_df))]
177
-
178
- fig.add_trace(go.Scatter(
179
- x=cash_flow_df['Month'],
180
- y=efficiency_ratio,
181
- name='Efficiency Ratio (%)',
182
- yaxis='y2',
183
- line=dict(color='#0066cc', width=2, dash='dot')
184
- ))
185
-
186
- fig.update_layout(
187
- yaxis2=dict(
188
- title='Efficiency Ratio (%)',
189
- overlaying='y',
190
- side='right',
191
- range=[0, max(efficiency_ratio) * 1.2]
192
- )
193
- )
194
-
195
  st.plotly_chart(fig, use_container_width=True)
196
-
197
- with st.expander("🔎 Understanding Efficiency Ratio"):
198
- st.info("The efficiency ratio measures how efficiently your startup is generating revenue relative to expenses. A higher percentage means you're getting more revenue per dollar spent. Venture-backed startups typically aim for at least 40% before Series B funding.")
199
 
200
  # Expense breakdown
201
  st.subheader("Expense Breakdown")
@@ -205,138 +76,111 @@ def render_financial_dashboard(startup_data, cash_flow_df):
205
  expense_categories = ['Payroll', 'Marketing', 'Office', 'Software', 'Travel', 'Legal', 'Misc']
206
  expense_values = [last_month[cat] for cat in expense_categories]
207
 
208
- col1, col2 = st.columns([2, 1])
209
-
210
- with col1:
211
- fig = px.pie(values=expense_values, names=expense_categories,
212
- title="Current Month Expense Breakdown",
213
- color_discrete_sequence=px.colors.sequential.Blues_r)
214
- fig.update_layout(
215
- height=400,
216
- font=dict(family="Arial, sans-serif", size=12),
217
- margin=dict(l=20, r=20, t=40, b=20),
218
- )
219
- fig.update_traces(textposition='inside', textinfo='percent+label')
220
- st.plotly_chart(fig, use_container_width=True)
221
-
222
- with col2:
223
- # Expense analysis
224
- st.markdown("<h4>Expense Analysis</h4>", unsafe_allow_html=True)
225
-
226
- # Calculate industry benchmarks (simulated)
227
- benchmarks = {
228
- "Payroll": "70-80%",
229
- "Marketing": "10-15%",
230
- "Office": "5-8%",
231
- "Software": "3-5%"
232
- }
233
-
234
- # Create a table with expense categories, amounts, and % of total
235
- expense_df = pd.DataFrame({
236
- "Category": expense_categories,
237
- "Amount": expense_values,
238
- "% of Total": [v / sum(expense_values) * 100 for v in expense_values]
239
- })
240
-
241
- # Add benchmark column
242
- expense_df["Industry Benchmark"] = expense_df["Category"].map(
243
- lambda x: benchmarks.get(x, "N/A")
244
- )
245
-
246
- # Format the dataframe for display
247
- formatted_df = expense_df.copy()
248
- formatted_df["Amount"] = formatted_df["Amount"].apply(lambda x: f"${x:,.0f}")
249
- formatted_df["% of Total"] = formatted_df["% of Total"].apply(lambda x: f"{x:.1f}%")
250
-
251
- st.table(formatted_df)
252
-
253
- # AI-powered spending optimization
254
- with st.expander("💡 AI Spending Optimization"):
255
- st.markdown("<span class='ai-badge'>AI Recommendation</span>", unsafe_allow_html=True)
256
-
257
- # Use cache to avoid repeated API calls
258
- spending_key = f"spending_{date.today().isoformat()}"
259
- if spending_key not in st.session_state.insights_cache:
260
- spending_recommendation = generate_ai_response("""
261
- Based on your expense breakdown, recommend 2-3 specific ways to optimize spending to extend runway.
262
- Focus on industry best practices for seed-stage startups.
263
- """, simulate=True)
264
- st.session_state.insights_cache[spending_key] = spending_recommendation
265
-
266
- st.markdown(st.session_state.insights_cache[spending_key])
267
-
268
- # Fundraising Readiness Assessment
269
- st.subheader("Fundraising Readiness")
270
-
271
- # Get AI analysis of fundraising readiness
272
- fundraising_key = f"fundraising_{date.today().isoformat()}"
273
- if fundraising_key not in st.session_state.insights_cache:
274
- fundraising_analysis = get_fundraising_readiness_analysis(startup_data, cash_flow_df)
275
- st.session_state.insights_cache[fundraising_key] = fundraising_analysis
276
-
277
- st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
278
- st.markdown("<span class='ai-badge'>AI Fundraising Assessment</span>", unsafe_allow_html=True)
279
- st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[fundraising_key]}</p>", unsafe_allow_html=True)
280
- st.markdown("</div>", unsafe_allow_html=True)
281
-
282
- # Call-to-action for advisor
283
- st.info("📅 Need personalized guidance on fundraising? [Book a session](#book-a-session) with our AI financial advisor.")
284
 
285
  def get_runway_analysis(financial_data):
286
  """Get runway analysis using Gemini."""
287
- prompt = f"""
288
- You are a financial advisor for startups. Analyze this startup's financial data:
289
- - Current cash: ${financial_data['cash']}
290
- - Monthly burn rate: ${financial_data['burn_rate']}
291
- - Monthly revenue: ${financial_data['revenue']}
292
- - Monthly growth rate: {financial_data['growth_rate'] * 100}%
 
 
 
 
 
 
 
 
 
 
 
293
 
294
- Provide a detailed analysis of their runway and financial health. Include:
295
- 1. Exact runway calculation in months
296
- 2. Assessment of financial health (critical, concerning, stable, or healthy)
297
- 3. Benchmarks compared to similar seed-stage startups
298
- 4. Three specific, actionable recommendations to improve runway
299
- 5. Key metrics they should focus on
 
 
 
 
 
300
 
301
- Format your response in a structured, easy-to-read format with clear sections and bullet points.
302
- """
303
-
304
- return generate_ai_response(prompt)
 
305
 
306
- def get_fundraising_readiness_analysis(startup_data, cash_flow_df):
307
- """Get AI analysis of fundraising readiness."""
308
- metrics = {
309
- "MRR Growth": f"{(cash_flow_df['Revenue'].iloc[-1] / cash_flow_df['Revenue'].iloc[-2] - 1) * 100:.1f}%",
310
- "Gross Margin": f"{(cash_flow_df['Revenue'].iloc[-1] - cash_flow_df['Total_Expenses'].iloc[-1] / 2) / cash_flow_df['Revenue'].iloc[-1] * 100:.1f}%",
311
- "CAC": "$950", # Example value
312
- "LTV": "$4,500", # Example value
313
- "Churn": "3.2%", # Example value
314
- }
315
-
316
- metrics_text = "\n".join([f"- {k}: {v}" for k, v in metrics.items()])
317
-
318
- prompt = f"""
319
- You are a startup fundraising advisor. Analyze this startup's readiness for their next funding round:
320
-
321
- Company Profile:
322
- - Stage: {startup_data['stage']}
323
- - Last Funding: {startup_data['last_funding']}
324
- - Current Cash: ${startup_data['cash']}
325
- - Monthly Burn: ${startup_data['burn_rate']}
326
- - Runway: {startup_data['cash'] / (startup_data['burn_rate'] - startup_data['revenue']):.1f} months
327
-
328
- Key Metrics:
329
- {metrics_text}
330
-
331
- Provide a comprehensive fundraising readiness assessment:
332
- 1. Overall fundraising readiness score (0-10)
333
- 2. Assessment of current metrics compared to investor expectations for next round
334
- 3. Identify the 3 most critical metrics to improve before fundraising
335
- 4. Recommend specific targets for each key metric
336
- 5. Suggest timeline and specific milestones for fundraising preparation
337
- 6. Estimate reasonable valuation range based on metrics and market conditions
338
-
339
- Be specific with numbers, timelines, and actionable targets.
340
- """
341
-
342
- return generate_ai_response(prompt)
 
1
+ import streamlit as st
2
+ import plotly.express as px
3
+ import pandas as pd
4
+ import google.generativeai as genai
5
+
6
  def render_financial_dashboard(startup_data, cash_flow_df):
7
+ """Render financial dashboard page."""
8
+ st.title("Financial Dashboard")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  # Key metrics
11
  col1, col2, col3, col4 = st.columns(4)
 
18
  startup_data['growth_rate']
19
  )
20
 
 
 
 
 
 
21
  with col1:
22
+ st.metric("Current Cash", f"${startup_data['cash']:,}")
 
 
 
 
 
 
23
  with col2:
24
+ st.metric("Monthly Burn", f"${startup_data['burn_rate']:,}")
 
 
 
 
 
 
25
  with col3:
26
+ st.metric("Monthly Revenue", f"${startup_data['revenue']:,}")
 
 
 
 
 
 
27
  with col4:
28
+ st.metric("Runway", f"{runway_months} months")
 
 
 
 
 
29
 
30
  # Financial charts
31
  st.subheader("Financial Overview")
 
36
  # Runway projection chart
37
  fig = px.line(runway_df.reset_index(), x='index', y='Cumulative_Cash',
38
  title="Cash Runway Projection",
39
+ labels={'index': 'Date', 'Cumulative_Cash': 'Remaining Cash'})
40
+ fig.add_hline(y=0, line_dash="dash", line_color="red")
41
+ fig.update_layout(height=400)
 
 
 
 
 
 
 
 
42
  st.plotly_chart(fig, use_container_width=True)
43
 
44
  # Get analysis from Gemini
45
+ try:
46
+ if setup_genai():
47
+ with st.expander("AI Financial Analysis"):
48
+ analysis = get_runway_analysis(startup_data)
49
+ st.write(analysis)
50
+ except Exception as e:
51
+ st.error(f"Error generating AI analysis: {e}")
 
 
52
 
53
  with tab2:
54
  # Revenue vs Expenses chart
 
56
  fig = px.bar(rev_exp_df, x='Month', y=['Revenue', 'Total_Expenses'],
57
  title="Revenue vs. Expenses",
58
  barmode='group',
59
+ labels={'value': 'Amount ($)', 'variable': 'Category'})
60
+ fig.update_layout(height=400)
 
 
 
 
 
 
 
 
 
61
  st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  with tab3:
64
  # Burn rate trend
65
  fig = px.line(cash_flow_df, x='Month', y='Net_Burn',
66
  title="Monthly Net Burn Trend",
67
+ labels={'Net_Burn': 'Net Burn ($)'})
68
+ fig.update_layout(height=400)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  st.plotly_chart(fig, use_container_width=True)
 
 
 
70
 
71
  # Expense breakdown
72
  st.subheader("Expense Breakdown")
 
76
  expense_categories = ['Payroll', 'Marketing', 'Office', 'Software', 'Travel', 'Legal', 'Misc']
77
  expense_values = [last_month[cat] for cat in expense_categories]
78
 
79
+ fig = px.pie(values=expense_values, names=expense_categories,
80
+ title="Current Month Expense Breakdown")
81
+ fig.update_layout(height=400)
82
+ st.plotly_chart(fig, use_container_width=True)
83
+
84
+ def calculate_runway(initial_cash, monthly_burn, monthly_revenue, growth_rate, months=24):
85
+ """Calculate runway based on current burn rate and revenue growth."""
86
+ from datetime import datetime, timedelta
87
+ import pandas as pd
88
+
89
+ dates = [datetime.now() + timedelta(days=30*i) for i in range(months)]
90
+ df = pd.DataFrame(index=dates, columns=['Cash', 'Revenue', 'Expenses', 'Net_Burn', 'Cumulative_Cash'])
91
+
92
+ current_cash = initial_cash
93
+ current_revenue = monthly_revenue
94
+ df.iloc[0, df.columns.get_loc('Cash')] = current_cash
95
+ df.iloc[0, df.columns.get_loc('Revenue')] = current_revenue
96
+ df.iloc[0, df.columns.get_loc('Expenses')] = monthly_burn
97
+ df.iloc[0, df.columns.get_loc('Net_Burn')] = monthly_burn - current_revenue
98
+ df.iloc[0, df.columns.get_loc('Cumulative_Cash')] = current_cash
99
+
100
+ runway_months = months
101
+ for i in range(1, months):
102
+ current_revenue = current_revenue * (1 + growth_rate)
103
+ net_burn = monthly_burn - current_revenue
104
+ current_cash = current_cash - net_burn
105
+
106
+ df.iloc[i, df.columns.get_loc('Cash')] = current_cash
107
+ df.iloc[i, df.columns.get_loc('Revenue')] = current_revenue
108
+ df.iloc[i, df.columns.get_loc('Expenses')] = monthly_burn
109
+ df.iloc[i, df.columns.get_loc('Net_Burn')] = net_burn
110
+ df.iloc[i, df.columns.get_loc('Cumulative_Cash')] = current_cash
111
+
112
+ if current_cash <= 0:
113
+ runway_months = i
114
+ break
115
+
116
+ return runway_months, df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  def get_runway_analysis(financial_data):
119
  """Get runway analysis using Gemini."""
120
+ try:
121
+ prompt = f"""
122
+ You are a financial advisor for startups. Analyze this startup's financial data:
123
+ - Current cash: ${financial_data['cash']}
124
+ - Monthly burn rate: ${financial_data['burn_rate']}
125
+ - Monthly revenue: ${financial_data['revenue']}
126
+ - Monthly growth rate: {financial_data['growth_rate'] * 100}%
127
+
128
+ Calculate and explain their runway, financial health, and recommendations in a concise paragraph.
129
+ """
130
+
131
+ model = genai.GenerativeModel('gemini-pro')
132
+ response = model.generate_content(prompt)
133
+
134
+ return response.text
135
+ except Exception as e:
136
+ return f"Error generating runway analysis: {e}"
137
 
138
+ def get_fundraising_readiness_analysis(financial_data):
139
+ """Analyze startup's readiness for fundraising."""
140
+ try:
141
+ prompt = f"""
142
+ You are a fundraising advisor for startups. Evaluate this startup's fundraising readiness:
143
+ - Current cash: ${financial_data['cash']}
144
+ - Monthly burn rate: ${financial_data['burn_rate']}
145
+ - Monthly revenue: ${financial_data['revenue']}
146
+ - Monthly growth rate: {financial_data['growth_rate'] * 100}%
147
+ - Last funding: {financial_data.get('last_funding', 'Not specified')}
148
+ - Company stage: {financial_data.get('stage', 'Not specified')}
149
 
150
+ Provide insights on:
151
+ 1. Current runway and funding needs
152
+ 2. Attractiveness to potential investors
153
+ 3. Recommended fundraising strategy
154
+ 4. Key metrics to improve before fundraising
155
 
156
+ Respond in a concise, actionable paragraph.
157
+ """
158
+
159
+ model = genai.GenerativeModel('gemini-pro')
160
+ response = model.generate_content(prompt)
161
+
162
+ return response.text
163
+ except Exception as e:
164
+ return f"Error generating fundraising readiness analysis: {e}"
165
+
166
+ def setup_genai():
167
+ """Setup Google Generative AI"""
168
+ try:
169
+ import os
170
+ import streamlit as st
171
+
172
+ # Try getting API key from Streamlit secrets first
173
+ if 'GOOGLE_API_KEY' in st.secrets:
174
+ api_key = st.secrets['GOOGLE_API_KEY']
175
+ # Fall back to environment variable
176
+ elif 'GOOGLE_API_KEY' in os.environ:
177
+ api_key = os.environ['GOOGLE_API_KEY']
178
+ else:
179
+ st.warning("Google API key not found. Using simulated AI responses.")
180
+ return False
181
+
182
+ genai.configure(api_key=api_key)
183
+ return True
184
+ except Exception as e:
185
+ st.error(f"Error setting up Generative AI: {e}")
186
+ return False