DrishtiSharma commited on
Commit
112e5fa
Β·
verified Β·
1 Parent(s): 56f1eb3

Create super_flawed_dynamic_viz_v1.py

Browse files
Files changed (1) hide show
  1. mylab/super_flawed_dynamic_viz_v1.py +630 -0
mylab/super_flawed_dynamic_viz_v1.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import sqlite3
4
+ import tempfile
5
+ from fpdf import FPDF
6
+ import time
7
+ import os
8
+ import re
9
+ import json
10
+ from pathlib import Path
11
+ import plotly.express as px
12
+ from datetime import datetime, timezone
13
+ from crewai import Agent, Crew, Process, Task
14
+ from crewai.tools import tool
15
+ from langchain_groq import ChatGroq
16
+ from langchain_openai import ChatOpenAI
17
+ from langchain.schema.output import LLMResult
18
+ from langchain_community.tools.sql_database.tool import (
19
+ InfoSQLDatabaseTool,
20
+ ListSQLDatabaseTool,
21
+ QuerySQLCheckerTool,
22
+ QuerySQLDataBaseTool,
23
+ )
24
+ from langchain_community.utilities.sql_database import SQLDatabase
25
+ from datasets import load_dataset
26
+ import tempfile
27
+
28
+ st.title("SQL-RAG Using CrewAI πŸš€")
29
+ st.write("Analyze datasets using natural language queries.")
30
+
31
+ # Initialize LLM
32
+ llm = None
33
+
34
+ # Model Selection
35
+ model_choice = st.radio("Select LLM", ["GPT-4o", "llama-3.3-70b"], index=0, horizontal=True)
36
+
37
+ # API Key Validation and LLM Initialization
38
+ groq_api_key = os.getenv("GROQ_API_KEY")
39
+ openai_api_key = os.getenv("OPENAI_API_KEY")
40
+
41
+ if model_choice == "llama-3.3-70b":
42
+ if not groq_api_key:
43
+ st.error("Groq API key is missing. Please set the GROQ_API_KEY environment variable.")
44
+ llm = None
45
+ else:
46
+ llm = ChatGroq(groq_api_key=groq_api_key, model="groq/llama-3.3-70b-versatile")
47
+ elif model_choice == "GPT-4o":
48
+ if not openai_api_key:
49
+ st.error("OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable.")
50
+ llm = None
51
+ else:
52
+ llm = ChatOpenAI(api_key=openai_api_key, model="gpt-4o")
53
+
54
+ # Initialize session state for data persistence
55
+ if "df" not in st.session_state:
56
+ st.session_state.df = None
57
+ if "show_preview" not in st.session_state:
58
+ st.session_state.show_preview = False
59
+
60
+ # Dataset Input
61
+ input_option = st.radio("Select Dataset Input:", ["Use Hugging Face Dataset", "Upload CSV File"])
62
+
63
+ if input_option == "Use Hugging Face Dataset":
64
+ dataset_name = st.text_input("Enter Hugging Face Dataset Name:", value="Einstellung/demo-salaries")
65
+ if st.button("Load Dataset"):
66
+ try:
67
+ with st.spinner("Loading dataset..."):
68
+ dataset = load_dataset(dataset_name, split="train")
69
+ st.session_state.df = pd.DataFrame(dataset)
70
+ st.session_state.show_preview = True # Show preview after loading
71
+ st.success(f"Dataset '{dataset_name}' loaded successfully!")
72
+ except Exception as e:
73
+ st.error(f"Error: {e}")
74
+
75
+ elif input_option == "Upload CSV File":
76
+ uploaded_file = st.file_uploader("Upload CSV File:", type=["csv"])
77
+ if uploaded_file:
78
+ try:
79
+ st.session_state.df = pd.read_csv(uploaded_file)
80
+ st.session_state.show_preview = True # Show preview after loading
81
+ st.success("File uploaded successfully!")
82
+ except Exception as e:
83
+ st.error(f"Error loading file: {e}")
84
+
85
+ # Show Dataset Preview Only After Loading
86
+ if st.session_state.df is not None and st.session_state.show_preview:
87
+ st.subheader("πŸ“‚ Dataset Preview")
88
+ st.dataframe(st.session_state.df.head())
89
+
90
+
91
+ # Helper Function for Validation
92
+ def is_valid_suggestion(suggestion):
93
+ chart_type = suggestion.get("chart_type", "").lower()
94
+
95
+ if chart_type in ["bar", "line", "box", "scatter"]:
96
+ return all(k in suggestion for k in ["chart_type", "x_axis", "y_axis"])
97
+
98
+ elif chart_type == "pie":
99
+ return all(k in suggestion for k in ["chart_type", "x_axis"])
100
+
101
+ elif chart_type == "heatmap":
102
+ return all(k in suggestion for k in ["chart_type", "x_axis", "y_axis"])
103
+
104
+ else:
105
+ return False
106
+
107
+ def ask_gpt4o_for_visualization(query, df, llm, retries=2):
108
+ import json
109
+
110
+ # Identify numeric and categorical columns
111
+ numeric_columns = df.select_dtypes(include='number').columns.tolist()
112
+ categorical_columns = df.select_dtypes(exclude='number').columns.tolist()
113
+
114
+ # Prompt with Dataset-Specific, Query-Based Examples
115
+ prompt = f"""
116
+ Analyze the following query and suggest the most suitable visualization(s) using the dataset.
117
+ **Query:** "{query}"
118
+ **Dataset Overview:**
119
+ - **Numeric Columns (for Y-axis):** {', '.join(numeric_columns) if numeric_columns else 'None'}
120
+ - **Categorical Columns (for X-axis or grouping):** {', '.join(categorical_columns) if categorical_columns else 'None'}
121
+ Suggest visualizations in this exact JSON format:
122
+ [
123
+ {{
124
+ "chdart_type": "bar/box/line/scatter/pie/heatmap",
125
+ "x_axis": "categorical_or_time_column",
126
+ "y_axis": "numeric_column",
127
+ "group_by": "optional_column_for_grouping",
128
+ "title": "Title of the chart",
129
+ "description": "Why this chart is suitable"
130
+ }}
131
+ ]
132
+ **Query-Based Examples:**
133
+ - **Query:** "What is the salary distribution across different job titles?"
134
+ **Suggested Visualization:**
135
+ {{
136
+ "chart_type": "box",
137
+ "x_axis": "job_title",
138
+ "y_axis": "salary_in_usd",
139
+ "group_by": "experience_level",
140
+ "title": "Salary Distribution by Job Title and Experience",
141
+ "description": "A box plot to show how salaries vary across different job titles and experience levels."
142
+ }}
143
+ - **Query:** "Show the average salary by company size and employment type."
144
+ **Suggested Visualizations:**
145
+ [
146
+ {{
147
+ "chart_type": "bar",
148
+ "x_axis": "company_size",
149
+ "y_axis": "salary_in_usd",
150
+ "group_by": "employment_type",
151
+ "title": "Average Salary by Company Size and Employment Type",
152
+ "description": "A grouped bar chart comparing average salaries across company sizes and employment types."
153
+ }},
154
+ {{
155
+ "chart_type": "heatmap",
156
+ "x_axis": "company_size",
157
+ "y_axis": "salary_in_usd",
158
+ "group_by": "employment_type",
159
+ "title": "Salary Heatmap by Company Size and Employment Type",
160
+ "description": "A heatmap showing salary concentration across company sizes and employment types."
161
+ }}
162
+ ]
163
+ - **Query:** "How has the average salary changed over the years?"
164
+ **Suggested Visualization:**
165
+ {{
166
+ "chart_type": "line",
167
+ "x_axis": "work_year",
168
+ "y_axis": "salary_in_usd",
169
+ "group_by": "experience_level",
170
+ "title": "Average Salary Trend Over Years",
171
+ "description": "A line chart showing how the average salary has changed across different experience levels over the years."
172
+ }}
173
+ - **Query:** "What is the employee distribution by company location?"
174
+ **Suggested Visualization:**
175
+ {{
176
+ "chart_type": "pie",
177
+ "x_axis": "company_location",
178
+ "y_axis": null,
179
+ "group_by": null,
180
+ "title": "Employee Distribution by Company Location",
181
+ "description": "A pie chart showing the distribution of employees across company locations."
182
+ }}
183
+ - **Query:** "Is there a relationship between remote work ratio and salary?"
184
+ **Suggested Visualization:**
185
+ {{
186
+ "chart_type": "scatter",
187
+ "x_axis": "remote_ratio",
188
+ "y_axis": "salary_in_usd",
189
+ "group_by": "experience_level",
190
+ "title": "Remote Work Ratio vs Salary",
191
+ "description": "A scatter plot to analyze the relationship between remote work ratio and salary."
192
+ }}
193
+ - **Query:** "Which job titles have the highest salaries across regions?"
194
+ **Suggested Visualization:**
195
+ {{
196
+ "chart_type": "heatmap",
197
+ "x_axis": "job_title",
198
+ "y_axis": "employee_residence",
199
+ "group_by": null,
200
+ "title": "Salary Heatmap by Job Title and Region",
201
+ "description": "A heatmap showing the concentration of high-paying job titles across regions."
202
+ }}
203
+ Only suggest visualizations that logically match the query and dataset.
204
+ """
205
+
206
+ for attempt in range(retries + 1):
207
+ try:
208
+ response = llm.generate(prompt)
209
+ suggestions = json.loads(response)
210
+
211
+ if isinstance(suggestions, list):
212
+ valid_suggestions = [s for s in suggestions if is_valid_suggestion(s)]
213
+ if valid_suggestions:
214
+ return valid_suggestions
215
+ else:
216
+ st.warning("⚠️ GPT-4o did not suggest valid visualizations.")
217
+ return None
218
+
219
+ elif isinstance(suggestions, dict):
220
+ if is_valid_suggestion(suggestions):
221
+ return [suggestions]
222
+ else:
223
+ st.warning("⚠️ GPT-4o's suggestion is incomplete or invalid.")
224
+ return None
225
+
226
+ except json.JSONDecodeError:
227
+ st.warning(f"⚠️ Attempt {attempt + 1}: GPT-4o returned invalid JSON.")
228
+ except Exception as e:
229
+ st.error(f"⚠️ Error during GPT-4o call: {e}")
230
+
231
+ if attempt < retries:
232
+ st.info("πŸ”„ Retrying visualization suggestion...")
233
+
234
+ st.error("❌ Failed to generate a valid visualization after multiple attempts.")
235
+ return None
236
+
237
+
238
+ def add_stats_to_figure(fig, df, y_axis, chart_type):
239
+ """
240
+ Add relevant statistical annotations to the visualization
241
+ based on the chart type.
242
+ """
243
+ # Check if the y-axis column is numeric
244
+ if not pd.api.types.is_numeric_dtype(df[y_axis]):
245
+ st.warning(f"⚠️ Cannot compute statistics for non-numeric column: {y_axis}")
246
+ return fig
247
+
248
+ # Compute statistics for numeric data
249
+ min_val = df[y_axis].min()
250
+ max_val = df[y_axis].max()
251
+ avg_val = df[y_axis].mean()
252
+ median_val = df[y_axis].median()
253
+ std_dev_val = df[y_axis].std()
254
+
255
+ # Format the stats for display
256
+ stats_text = (
257
+ f"πŸ“Š **Statistics**\n\n"
258
+ f"- **Min:** ${min_val:,.2f}\n"
259
+ f"- **Max:** ${max_val:,.2f}\n"
260
+ f"- **Average:** ${avg_val:,.2f}\n"
261
+ f"- **Median:** ${median_val:,.2f}\n"
262
+ f"- **Std Dev:** ${std_dev_val:,.2f}"
263
+ )
264
+
265
+ # Apply stats only to relevant chart types
266
+ if chart_type in ["bar", "line"]:
267
+ # Add annotation box for bar and line charts
268
+ fig.add_annotation(
269
+ text=stats_text,
270
+ xref="paper", yref="paper",
271
+ x=1.02, y=1,
272
+ showarrow=False,
273
+ align="left",
274
+ font=dict(size=12, color="black"),
275
+ bordercolor="gray",
276
+ borderwidth=1,
277
+ bgcolor="rgba(255, 255, 255, 0.85)"
278
+ )
279
+
280
+ # Add horizontal reference lines
281
+ fig.add_hline(y=min_val, line_dash="dot", line_color="red", annotation_text="Min", annotation_position="bottom right")
282
+ fig.add_hline(y=median_val, line_dash="dash", line_color="orange", annotation_text="Median", annotation_position="top right")
283
+ fig.add_hline(y=avg_val, line_dash="dashdot", line_color="green", annotation_text="Avg", annotation_position="top right")
284
+ fig.add_hline(y=max_val, line_dash="dot", line_color="blue", annotation_text="Max", annotation_position="top right")
285
+
286
+ elif chart_type == "scatter":
287
+ # Add stats annotation only, no lines for scatter plots
288
+ fig.add_annotation(
289
+ text=stats_text,
290
+ xref="paper", yref="paper",
291
+ x=1.02, y=1,
292
+ showarrow=False,
293
+ align="left",
294
+ font=dict(size=12, color="black"),
295
+ bordercolor="gray",
296
+ borderwidth=1,
297
+ bgcolor="rgba(255, 255, 255, 0.85)"
298
+ )
299
+
300
+ elif chart_type == "box":
301
+ # Box plots inherently show distribution; no extra stats needed
302
+ pass
303
+
304
+ elif chart_type == "pie":
305
+ # Pie charts represent proportions, not suitable for stats
306
+ st.info("πŸ“Š Pie charts represent proportions. Additional stats are not applicable.")
307
+
308
+ elif chart_type == "heatmap":
309
+ # Heatmaps already reflect data intensity
310
+ st.info("πŸ“Š Heatmaps inherently reflect distribution. No additional stats added.")
311
+
312
+ else:
313
+ st.warning(f"⚠️ No statistical overlays applied for unsupported chart type: '{chart_type}'.")
314
+
315
+ return fig
316
+
317
+
318
+ # Dynamically generate Plotly visualizations based on GPT-4o suggestions
319
+ def generate_visualization(suggestion, df):
320
+ """
321
+ Generate a Plotly visualization based on GPT-4o's suggestion.
322
+ If the Y-axis is missing, infer it intelligently.
323
+ """
324
+ chart_type = suggestion.get("chart_type", "bar").lower()
325
+ x_axis = suggestion.get("x_axis")
326
+ y_axis = suggestion.get("y_axis")
327
+ group_by = suggestion.get("group_by")
328
+
329
+ # Step 1: Infer Y-axis if not provided
330
+ if not y_axis:
331
+ numeric_columns = df.select_dtypes(include='number').columns.tolist()
332
+
333
+ # Avoid using the same column for both axes
334
+ if x_axis in numeric_columns:
335
+ numeric_columns.remove(x_axis)
336
+
337
+ # Smart guess: prioritize salary or relevant metrics if available
338
+ priority_columns = ["salary_in_usd", "income", "earnings", "revenue"]
339
+ for col in priority_columns:
340
+ if col in numeric_columns:
341
+ y_axis = col
342
+ break
343
+
344
+ # Fallback to the first numeric column if no priority columns exist
345
+ if not y_axis and numeric_columns:
346
+ y_axis = numeric_columns[0]
347
+
348
+ # Step 2: Validate axes
349
+ if not x_axis or not y_axis:
350
+ st.warning("⚠️ Unable to determine appropriate columns for visualization.")
351
+ return None
352
+
353
+ # Step 3: Dynamically select the Plotly function
354
+ plotly_function = getattr(px, chart_type, None)
355
+ if not plotly_function:
356
+ st.warning(f"⚠️ Unsupported chart type '{chart_type}' suggested by GPT-4o.")
357
+ return None
358
+
359
+ # Step 4: Prepare dynamic plot arguments
360
+ plot_args = {"data_frame": df, "x": x_axis, "y": y_axis}
361
+ if group_by and group_by in df.columns:
362
+ plot_args["color"] = group_by
363
+
364
+ try:
365
+ # Step 5: Generate the visualization
366
+ fig = plotly_function(**plot_args)
367
+ fig.update_layout(
368
+ title=f"{chart_type.title()} Plot of {y_axis.replace('_', ' ').title()} by {x_axis.replace('_', ' ').title()}",
369
+ xaxis_title=x_axis.replace('_', ' ').title(),
370
+ yaxis_title=y_axis.replace('_', ' ').title(),
371
+ )
372
+
373
+ # Step 6: Apply statistics intelligently
374
+ fig = add_statistics_to_visualization(fig, df, y_axis, chart_type)
375
+
376
+ return fig
377
+
378
+ except Exception as e:
379
+ st.error(f"⚠️ Failed to generate visualization: {e}")
380
+ return None
381
+
382
+
383
+ def generate_multiple_visualizations(suggestions, df):
384
+ """
385
+ Generates one or more visualizations based on GPT-4o's suggestions.
386
+ Handles both single and multiple suggestions.
387
+ """
388
+ visualizations = []
389
+
390
+ for suggestion in suggestions:
391
+ fig = generate_visualization(suggestion, df)
392
+ if fig:
393
+ # Apply chart-specific statistics
394
+ fig = add_stats_to_figure(fig, df, suggestion["y_axis"], suggestion["chart_type"])
395
+ visualizations.append(fig)
396
+
397
+ if not visualizations and suggestions:
398
+ st.warning("⚠️ No valid visualization found. Displaying the most relevant one.")
399
+ best_suggestion = suggestions[0]
400
+ fig = generate_visualization(best_suggestion, df)
401
+ fig = add_stats_to_figure(fig, df, best_suggestion["y_axis"], best_suggestion["chart_type"])
402
+ visualizations.append(fig)
403
+
404
+ return visualizations
405
+
406
+
407
+ def handle_visualization_suggestions(suggestions, df):
408
+ """
409
+ Determines whether to generate a single or multiple visualizations.
410
+ """
411
+ visualizations = []
412
+
413
+ # If multiple suggestions, generate multiple plots
414
+ if isinstance(suggestions, list) and len(suggestions) > 1:
415
+ visualizations = generate_multiple_visualizations(suggestions, df)
416
+
417
+ # If only one suggestion, generate a single plot
418
+ elif isinstance(suggestions, dict) or (isinstance(suggestions, list) and len(suggestions) == 1):
419
+ suggestion = suggestions[0] if isinstance(suggestions, list) else suggestions
420
+ fig = generate_visualization(suggestion, df)
421
+ if fig:
422
+ visualizations.append(fig)
423
+
424
+ # Handle cases when no visualization could be generated
425
+ if not visualizations:
426
+ st.warning("⚠️ Unable to generate any visualization based on the suggestion.")
427
+
428
+ # Display all generated visualizations
429
+ for fig in visualizations:
430
+ st.plotly_chart(fig, use_container_width=True)
431
+
432
+
433
+ def escape_markdown(text):
434
+ # Ensure text is a string
435
+ text = str(text)
436
+ # Escape Markdown characters: *, _, `, ~
437
+ escape_chars = r"(\*|_|`|~)"
438
+ return re.sub(escape_chars, r"\\\1", text)
439
+
440
+
441
+ # Functions with Progress Bar Updates
442
+ def generate_report(query, crew_report, result_container, progress_bar, step):
443
+ progress_bar.progress(step, text="πŸ“ Generating Analysis Report...")
444
+ report_inputs = {"query": query + " Provide detailed analysis but DO NOT include Conclusion."}
445
+ result_container['report'] = crew_report.kickoff(inputs=report_inputs)
446
+ progress_bar.progress(step + 1, text="βœ… Analysis Report Ready!")
447
+
448
+ def generate_conclusion(query, crew_conclusion, result_container, progress_bar, step):
449
+ progress_bar.progress(step, text="πŸ“ Crafting Conclusion...")
450
+ conclusion_inputs = {"query": query + " Provide ONLY the most important insights in 3-5 concise lines."}
451
+ result_container['conclusion'] = crew_conclusion.kickoff(inputs=conclusion_inputs)
452
+ progress_bar.progress(step + 1, text="βœ… Conclusion Ready!")
453
+
454
+ def generate_visuals(query, df, llm, result_container, progress_bar, step):
455
+ progress_bar.progress(step, text="πŸ“Š Creating Visualizations...")
456
+ result_container['visuals'] = ask_gpt4o_for_visualization(query, df, llm)
457
+ progress_bar.progress(step + 1, text="βœ… Visualizations Ready!")
458
+
459
+
460
+ import threading
461
+
462
+ # SQL-RAG Analysis
463
+ if st.session_state.df is not None:
464
+ temp_dir = tempfile.TemporaryDirectory()
465
+ db_path = os.path.join(temp_dir.name, "data.db")
466
+ connection = sqlite3.connect(db_path)
467
+ st.session_state.df.to_sql("salaries", connection, if_exists="replace", index=False)
468
+ db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
469
+
470
+ @tool("list_tables")
471
+ def list_tables() -> str:
472
+ """List all tables in the database."""
473
+ return ListSQLDatabaseTool(db=db).invoke("")
474
+
475
+ @tool("tables_schema")
476
+ def tables_schema(tables: str) -> str:
477
+ """Get the schema and sample rows for the specified tables."""
478
+ return InfoSQLDatabaseTool(db=db).invoke(tables)
479
+
480
+ @tool("execute_sql")
481
+ def execute_sql(sql_query: str) -> str:
482
+ """Execute a SQL query against the database and return the results."""
483
+ return QuerySQLDataBaseTool(db=db).invoke(sql_query)
484
+
485
+ @tool("check_sql")
486
+ def check_sql(sql_query: str) -> str:
487
+ """Validate the SQL query syntax and structure before execution."""
488
+ return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
489
+
490
+ # Agents for SQL data extraction and analysis
491
+ sql_dev = Agent(
492
+ role="Senior Database Developer",
493
+ goal="Extract data using optimized SQL queries.",
494
+ backstory="An expert in writing optimized SQL queries for complex databases.",
495
+ llm=llm,
496
+ tools=[list_tables, tables_schema, execute_sql, check_sql],
497
+ )
498
+
499
+ data_analyst = Agent(
500
+ role="Senior Data Analyst",
501
+ goal="Analyze the data and produce insights.",
502
+ backstory="A seasoned analyst who identifies trends and patterns in datasets.",
503
+ llm=llm,
504
+ )
505
+
506
+ report_writer = Agent(
507
+ role="Technical Report Writer",
508
+ goal="Write a structured report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
509
+ backstory="Specializes in detailed analytical reports without conclusions.",
510
+ llm=llm,
511
+ )
512
+
513
+ conclusion_writer = Agent(
514
+ role="Conclusion Specialist",
515
+ goal="Summarize findings into a clear and concise 3-5 line Conclusion highlighting only the most important insights.",
516
+ backstory="An expert in crafting impactful and clear conclusions.",
517
+ llm=llm,
518
+ )
519
+
520
+ # Define tasks for report and conclusion
521
+ extract_data = Task(
522
+ description="Extract data based on the query: {query}.",
523
+ expected_output="Database results matching the query.",
524
+ agent=sql_dev,
525
+ )
526
+
527
+ analyze_data = Task(
528
+ description="Analyze the extracted data for query: {query}.",
529
+ expected_output="Key Insights and Analysis without any Introduction or Conclusion.",
530
+ agent=data_analyst,
531
+ context=[extract_data],
532
+ )
533
+
534
+ write_report = Task(
535
+ description="Write the analysis report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
536
+ expected_output="Markdown-formatted report excluding Conclusion.",
537
+ agent=report_writer,
538
+ context=[analyze_data],
539
+ )
540
+
541
+ write_conclusion = Task(
542
+ description="Summarize the key findings in 3-5 impactful lines, highlighting the maximum, minimum, and average salaries."
543
+ "Emphasize significant insights on salary distribution and influential compensation trends for strategic decision-making.",
544
+ expected_output="Markdown-formatted Conclusion section with key insights and statistics.",
545
+ agent=conclusion_writer,
546
+ context=[analyze_data],
547
+ )
548
+
549
+ # Separate Crews for report and conclusion
550
+ crew_report = Crew(
551
+ agents=[sql_dev, data_analyst, report_writer],
552
+ tasks=[extract_data, analyze_data, write_report],
553
+ process=Process.sequential,
554
+ verbose=True,
555
+ )
556
+
557
+ crew_conclusion = Crew(
558
+ agents=[data_analyst, conclusion_writer],
559
+ tasks=[write_conclusion],
560
+ process=Process.sequential,
561
+ verbose=True,
562
+ )
563
+
564
+ # Tabs for Query Results and Visualizations
565
+ tab1, tab2 = st.tabs(["πŸ” Query Insights + Viz", "πŸ“Š Full Data Viz"])
566
+
567
+ # Query Insights + Visualization
568
+ with tab1:
569
+ query = st.text_area("Enter Query:", value="Provide insights into the salary of a Principal Data Scientist.")
570
+ if st.button("Submit Query"):
571
+ result_container = {"report": None, "conclusion": None, "visuals": None}
572
+ progress_bar = st.progress(0, text="πŸš€ Starting Analysis...")
573
+
574
+ # Define parallel tasks
575
+ def generate_report():
576
+ progress_bar.progress(20, text="πŸ“ Generating Analysis Report...")
577
+ report_inputs = {"query": query + " Provide detailed analysis but DO NOT include Conclusion."}
578
+ result_container['report'] = crew_report.kickoff(inputs=report_inputs)
579
+ progress_bar.progress(40, text="βœ… Analysis Report Ready!")
580
+
581
+ def generate_conclusion():
582
+ progress_bar.progress(40, text="πŸ“ Crafting Conclusion...")
583
+ conclusion_inputs = {"query": query + " Provide ONLY the most important insights in 3-5 concise lines."}
584
+ result_container['conclusion'] = crew_conclusion.kickoff(inputs=conclusion_inputs)
585
+ progress_bar.progress(60, text="βœ… Conclusion Ready!")
586
+
587
+ def generate_visuals():
588
+ progress_bar.progress(60, text="πŸ“Š Creating Visualizations...")
589
+ result_container['visuals'] = ask_gpt4o_for_visualization(query, st.session_state.df, llm)
590
+ progress_bar.progress(80, text="βœ… Visualizations Ready!")
591
+
592
+ # Run tasks in parallel
593
+ thread_report = threading.Thread(target=generate_report)
594
+ thread_conclusion = threading.Thread(target=generate_conclusion)
595
+ thread_visuals = threading.Thread(target=generate_visuals)
596
+
597
+ thread_report.start()
598
+ thread_conclusion.start()
599
+ thread_visuals.start()
600
+
601
+ # Wait for all threads to finish
602
+ thread_report.join()
603
+ thread_conclusion.join()
604
+ thread_visuals.join()
605
+
606
+ progress_bar.progress(100, text="βœ… Full Analysis Complete!")
607
+ time.sleep(0.5)
608
+ progress_bar.empty()
609
+
610
+ # Display Report
611
+ st.markdown("## πŸ“Š Analysis Report")
612
+ st.markdown(result_container['report'] if result_container['report'] else "⚠️ No Report Generated.")
613
+
614
+ # Display Visual Insights
615
+ st.markdown("## πŸ“ˆ Visual Insights")
616
+ if result_container['visuals']:
617
+ handle_visualization_suggestions(result_container['visuals'], st.session_state.df)
618
+ else:
619
+ st.warning("⚠️ No suitable visualizations to display.")
620
+
621
+ # Display Conclusion
622
+ st.markdown("## πŸ“ Conclusion")
623
+ safe_conclusion = escape_markdown(result_container['conclusion'] if result_container['conclusion'] else "⚠️ No Conclusion Generated.")
624
+ st.markdown(safe_conclusion)
625
+
626
+
627
+ # Sidebar Reference
628
+ with st.sidebar:
629
+ st.header("πŸ“š Reference:")
630
+ st.markdown("[SQL Agents w CrewAI & Llama 3 - Plaban Nayak](https://github.com/plaban1981/Agents/blob/main/SQL_Agents_with_CrewAI_and_Llama_3.ipynb)")