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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import sqlite3
4
+ import tempfile
5
+ from fpdf import FPDF
6
+ import os
7
+ import re
8
+ import json
9
+ from pathlib import Path
10
+ import plotly.express as px
11
+ from datetime import datetime, timezone
12
+ from crewai import Agent, Crew, Process, Task
13
+ from crewai.tools import tool
14
+ from langchain_groq import ChatGroq
15
+ from langchain_openai import ChatOpenAI
16
+ from langchain.schema.output import LLMResult
17
+ from langchain_community.tools.sql_database.tool import (
18
+ InfoSQLDatabaseTool,
19
+ ListSQLDatabaseTool,
20
+ QuerySQLCheckerTool,
21
+ QuerySQLDataBaseTool,
22
+ )
23
+ from langchain_community.utilities.sql_database import SQLDatabase
24
+ from datasets import load_dataset
25
+ import tempfile
26
+
27
+ st.title("SQL-RAG Using CrewAI πŸš€")
28
+ st.write("Analyze datasets using natural language queries powered by SQL and CrewAI.")
29
+
30
+ # Initialize LLM
31
+ llm = None
32
+
33
+ # Model Selection
34
+ model_choice = st.radio("Select LLM", ["GPT-4o", "llama-3.3-70b"], index=0, horizontal=True)
35
+
36
+ # API Key Validation and LLM Initialization
37
+ groq_api_key = os.getenv("GROQ_API_KEY")
38
+ openai_api_key = os.getenv("OPENAI_API_KEY")
39
+
40
+ if model_choice == "llama-3.3-70b":
41
+ if not groq_api_key:
42
+ st.error("Groq API key is missing. Please set the GROQ_API_KEY environment variable.")
43
+ llm = None
44
+ else:
45
+ llm = ChatGroq(groq_api_key=groq_api_key, model="groq/llama-3.3-70b-versatile")
46
+ elif model_choice == "GPT-4o":
47
+ if not openai_api_key:
48
+ st.error("OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable.")
49
+ llm = None
50
+ else:
51
+ llm = ChatOpenAI(api_key=openai_api_key, model="gpt-4o")
52
+
53
+ # Initialize session state for data persistence
54
+ if "df" not in st.session_state:
55
+ st.session_state.df = None
56
+ if "show_preview" not in st.session_state:
57
+ st.session_state.show_preview = False
58
+
59
+ # Dataset Input
60
+ input_option = st.radio("Select Dataset Input:", ["Use Hugging Face Dataset", "Upload CSV File"])
61
+
62
+ if input_option == "Use Hugging Face Dataset":
63
+ dataset_name = st.text_input("Enter Hugging Face Dataset Name:", value="Einstellung/demo-salaries")
64
+ if st.button("Load Dataset"):
65
+ try:
66
+ with st.spinner("Loading dataset..."):
67
+ dataset = load_dataset(dataset_name, split="train")
68
+ st.session_state.df = pd.DataFrame(dataset)
69
+ st.session_state.show_preview = True # Show preview after loading
70
+ st.success(f"Dataset '{dataset_name}' loaded successfully!")
71
+ except Exception as e:
72
+ st.error(f"Error: {e}")
73
+
74
+ elif input_option == "Upload CSV File":
75
+ uploaded_file = st.file_uploader("Upload CSV File:", type=["csv"])
76
+ if uploaded_file:
77
+ try:
78
+ st.session_state.df = pd.read_csv(uploaded_file)
79
+ st.session_state.show_preview = True # Show preview after loading
80
+ st.success("File uploaded successfully!")
81
+ except Exception as e:
82
+ st.error(f"Error loading file: {e}")
83
+
84
+ # Show Dataset Preview Only After Loading
85
+ if st.session_state.df is not None and st.session_state.show_preview:
86
+ st.subheader("πŸ“‚ Dataset Preview")
87
+ st.dataframe(st.session_state.df.head())
88
+
89
+ """# Ask GPT-4o for Visualization Suggestions
90
+ def ask_gpt4o_for_visualization(query, df, llm):
91
+ columns = ', '.join(df.columns)
92
+ prompt = f"""
93
+ Analyze the query and suggest the best visualization.
94
+ Query: "{query}"
95
+ Available Columns: {columns}
96
+ Respond in this JSON format:
97
+ {{
98
+ "chart_type": "bar/box/line/scatter",
99
+ "x_axis": "column_name",
100
+ "y_axis": "column_name",
101
+ "group_by": "optional_column_name"
102
+ }}
103
+ """
104
+ response = llm.generate(prompt)
105
+ try:
106
+ return json.loads(response)
107
+ except json.JSONDecodeError:
108
+ st.error("⚠️ GPT-4o failed to generate a valid suggestion.")
109
+ return None"""
110
+
111
+ def add_stats_to_figure(fig, df, y_axis, chart_type):
112
+ """
113
+ Add relevant statistical annotations to the visualization
114
+ based on the chart type.
115
+ """
116
+ # Check if the y-axis column is numeric
117
+ if not pd.api.types.is_numeric_dtype(df[y_axis]):
118
+ st.warning(f"⚠️ Cannot compute statistics for non-numeric column: {y_axis}")
119
+ return fig
120
+
121
+ # Compute statistics for numeric data
122
+ min_val = df[y_axis].min()
123
+ max_val = df[y_axis].max()
124
+ avg_val = df[y_axis].mean()
125
+ median_val = df[y_axis].median()
126
+ std_dev_val = df[y_axis].std()
127
+
128
+ # Format the stats for display
129
+ stats_text = (
130
+ f"πŸ“Š **Statistics**\n\n"
131
+ f"- **Min:** ${min_val:,.2f}\n"
132
+ f"- **Max:** ${max_val:,.2f}\n"
133
+ f"- **Average:** ${avg_val:,.2f}\n"
134
+ f"- **Median:** ${median_val:,.2f}\n"
135
+ f"- **Std Dev:** ${std_dev_val:,.2f}"
136
+ )
137
+
138
+ # Apply stats only to relevant chart types
139
+ if chart_type in ["bar", "line"]:
140
+ # Add annotation box for bar and line charts
141
+ fig.add_annotation(
142
+ text=stats_text,
143
+ xref="paper", yref="paper",
144
+ x=1.02, y=1,
145
+ showarrow=False,
146
+ align="left",
147
+ font=dict(size=12, color="black"),
148
+ bordercolor="gray",
149
+ borderwidth=1,
150
+ bgcolor="rgba(255, 255, 255, 0.85)"
151
+ )
152
+
153
+ # Add horizontal reference lines
154
+ fig.add_hline(y=min_val, line_dash="dot", line_color="red", annotation_text="Min", annotation_position="bottom right")
155
+ fig.add_hline(y=median_val, line_dash="dash", line_color="orange", annotation_text="Median", annotation_position="top right")
156
+ fig.add_hline(y=avg_val, line_dash="dashdot", line_color="green", annotation_text="Avg", annotation_position="top right")
157
+ fig.add_hline(y=max_val, line_dash="dot", line_color="blue", annotation_text="Max", annotation_position="top right")
158
+
159
+ elif chart_type == "scatter":
160
+ # Add stats annotation only, no lines for scatter plots
161
+ fig.add_annotation(
162
+ text=stats_text,
163
+ xref="paper", yref="paper",
164
+ x=1.02, y=1,
165
+ showarrow=False,
166
+ align="left",
167
+ font=dict(size=12, color="black"),
168
+ bordercolor="gray",
169
+ borderwidth=1,
170
+ bgcolor="rgba(255, 255, 255, 0.85)"
171
+ )
172
+
173
+ elif chart_type == "box":
174
+ # Box plots inherently show distribution; no extra stats needed
175
+ pass
176
+
177
+ elif chart_type == "pie":
178
+ # Pie charts represent proportions, not suitable for stats
179
+ st.info("πŸ“Š Pie charts represent proportions. Additional stats are not applicable.")
180
+
181
+ elif chart_type == "heatmap":
182
+ # Heatmaps already reflect data intensity
183
+ st.info("πŸ“Š Heatmaps inherently reflect distribution. No additional stats added.")
184
+
185
+ else:
186
+ st.warning(f"⚠️ No statistical overlays applied for unsupported chart type: '{chart_type}'.")
187
+
188
+ return fig
189
+
190
+
191
+ # Dynamically generate Plotly visualizations based on GPT-4o suggestions
192
+ def generate_visualization(suggestion, df):
193
+ chart_type = suggestion.get("chart_type", "bar").lower()
194
+ x_axis = suggestion.get("x_axis")
195
+ y_axis = suggestion.get("y_axis")
196
+ group_by = suggestion.get("group_by")
197
+
198
+ # Dynamically determine the best Y-axis if GPT-4o doesn't suggest one
199
+ if not y_axis:
200
+ numeric_columns = df.select_dtypes(include='number').columns.tolist()
201
+
202
+ if x_axis in numeric_columns:
203
+ # Avoid using the same column for both axes
204
+ numeric_columns.remove(x_axis)
205
+
206
+ # Prioritize the first available numeric column for y-axis
207
+ y_axis = numeric_columns[0] if numeric_columns else None
208
+
209
+ # Ensure both axes are identified
210
+ if not x_axis or not y_axis:
211
+ st.warning("⚠️ Unable to determine relevant columns for visualization.")
212
+ return None
213
+
214
+ # Dynamically select the Plotly function
215
+ plotly_function = getattr(px, chart_type, None)
216
+
217
+ if not plotly_function:
218
+ st.warning(f"⚠️ Unsupported chart type '{chart_type}' suggested by GPT-4o.")
219
+ return None
220
+
221
+ # Prepare dynamic plot arguments
222
+ plot_args = {"data_frame": df, "x": x_axis, "y": y_axis}
223
+ if group_by and group_by in df.columns:
224
+ plot_args["color"] = group_by
225
+
226
+ try:
227
+ # Generate the dynamic visualization
228
+ fig = plotly_function(**plot_args)
229
+ fig.update_layout(
230
+ title=f"{chart_type.title()} Plot of {y_axis.replace('_', ' ').title()} by {x_axis.replace('_', ' ').title()}",
231
+ xaxis_title=x_axis.replace('_', ' ').title(),
232
+ yaxis_title=y_axis.replace('_', ' ').title(),
233
+ )
234
+
235
+ # Apply statistics intelligently
236
+ fig = add_stats_to_figure(fig, df, y_axis, chart_type)
237
+
238
+ return fig
239
+
240
+ except Exception as e:
241
+ st.error(f"⚠️ Failed to generate visualization: {e}")
242
+ return None
243
+
244
+
245
+ # Function to create TXT file
246
+ def create_text_report_with_viz_temp(report, conclusion, visualizations):
247
+ content = f"### Analysis Report\n\n{report}\n\n### Visualizations\n"
248
+
249
+ for i, fig in enumerate(visualizations, start=1):
250
+ fig_title = fig.layout.title.text if fig.layout.title.text else f"Visualization {i}"
251
+ x_axis = fig.layout.xaxis.title.text if fig.layout.xaxis.title.text else "X-axis"
252
+ y_axis = fig.layout.yaxis.title.text if fig.layout.yaxis.title.text else "Y-axis"
253
+
254
+ content += f"\n{i}. {fig_title}\n"
255
+ content += f" - X-axis: {x_axis}\n"
256
+ content += f" - Y-axis: {y_axis}\n"
257
+
258
+ if fig.data:
259
+ trace_types = set(trace.type for trace in fig.data)
260
+ content += f" - Chart Type(s): {', '.join(trace_types)}\n"
261
+ else:
262
+ content += " - No data available in this visualization.\n"
263
+
264
+ content += f"\n\n\n{conclusion}"
265
+
266
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode='w', encoding='utf-8') as temp_txt:
267
+ temp_txt.write(content)
268
+ return temp_txt.name
269
+
270
+
271
+
272
+ # Function to create PDF with report text and visualizations
273
+ def create_pdf_report_with_viz(report, conclusion, visualizations):
274
+ pdf = FPDF()
275
+ pdf.set_auto_page_break(auto=True, margin=15)
276
+ pdf.add_page()
277
+ pdf.set_font("Arial", size=12)
278
+
279
+ # Title
280
+ pdf.set_font("Arial", style="B", size=18)
281
+ pdf.cell(0, 10, "πŸ“Š Analysis Report", ln=True, align="C")
282
+ pdf.ln(10)
283
+
284
+ # Report Content
285
+ pdf.set_font("Arial", style="B", size=14)
286
+ pdf.cell(0, 10, "Analysis", ln=True)
287
+ pdf.set_font("Arial", size=12)
288
+ pdf.multi_cell(0, 10, report)
289
+
290
+ pdf.ln(10)
291
+ pdf.set_font("Arial", style="B", size=14)
292
+ pdf.cell(0, 10, "Conclusion", ln=True)
293
+ pdf.set_font("Arial", size=12)
294
+ pdf.multi_cell(0, 10, conclusion)
295
+
296
+ # Add Visualizations
297
+ pdf.add_page()
298
+ pdf.set_font("Arial", style="B", size=16)
299
+ pdf.cell(0, 10, "πŸ“ˆ Visualizations", ln=True)
300
+ pdf.ln(5)
301
+
302
+ with tempfile.TemporaryDirectory() as temp_dir:
303
+ for i, fig in enumerate(visualizations, start=1):
304
+ fig_title = fig.layout.title.text if fig.layout.title.text else f"Visualization {i}"
305
+ x_axis = fig.layout.xaxis.title.text if fig.layout.xaxis.title.text else "X-axis"
306
+ y_axis = fig.layout.yaxis.title.text if fig.layout.yaxis.title.text else "Y-axis"
307
+
308
+ # Save each visualization as a PNG image
309
+ img_path = os.path.join(temp_dir, f"viz_{i}.png")
310
+ fig.write_image(img_path)
311
+
312
+ # Insert Title and Description
313
+ pdf.set_font("Arial", style="B", size=14)
314
+ pdf.multi_cell(0, 10, f"{i}. {fig_title}")
315
+ pdf.set_font("Arial", size=12)
316
+ pdf.multi_cell(0, 10, f"X-axis: {x_axis} | Y-axis: {y_axis}")
317
+ pdf.ln(3)
318
+
319
+ # Embed Visualization
320
+ pdf.image(img_path, w=170)
321
+ pdf.ln(10)
322
+
323
+ # Save PDF
324
+ temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
325
+ pdf.output(temp_pdf.name)
326
+
327
+ return temp_pdf
328
+
329
+ def escape_markdown(text):
330
+ # Ensure text is a string
331
+ text = str(text)
332
+ # Escape Markdown characters: *, _, `, ~
333
+ escape_chars = r"(\*|_|`|~)"
334
+ return re.sub(escape_chars, r"\\\1", text)
335
+
336
+ # SQL-RAG Analysis
337
+ if st.session_state.df is not None:
338
+ temp_dir = tempfile.TemporaryDirectory()
339
+ db_path = os.path.join(temp_dir.name, "data.db")
340
+ connection = sqlite3.connect(db_path)
341
+ st.session_state.df.to_sql("salaries", connection, if_exists="replace", index=False)
342
+ db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
343
+
344
+ @tool("list_tables")
345
+ def list_tables() -> str:
346
+ """List all tables in the database."""
347
+ return ListSQLDatabaseTool(db=db).invoke("")
348
+
349
+ @tool("tables_schema")
350
+ def tables_schema(tables: str) -> str:
351
+ """Get the schema and sample rows for the specified tables."""
352
+ return InfoSQLDatabaseTool(db=db).invoke(tables)
353
+
354
+ @tool("execute_sql")
355
+ def execute_sql(sql_query: str) -> str:
356
+ """Execute a SQL query against the database and return the results."""
357
+ return QuerySQLDataBaseTool(db=db).invoke(sql_query)
358
+
359
+ @tool("check_sql")
360
+ def check_sql(sql_query: str) -> str:
361
+ """Validate the SQL query syntax and structure before execution."""
362
+ return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
363
+
364
+ # Agents for SQL data extraction and analysis
365
+ sql_dev = Agent(
366
+ role="Senior Database Developer",
367
+ goal="Extract data using optimized SQL queries.",
368
+ backstory="An expert in writing optimized SQL queries for complex databases.",
369
+ llm=llm,
370
+ tools=[list_tables, tables_schema, execute_sql, check_sql],
371
+ )
372
+
373
+ data_analyst = Agent(
374
+ role="Senior Data Analyst",
375
+ goal="Analyze the data and produce insights.",
376
+ backstory="A seasoned analyst who identifies trends and patterns in datasets.",
377
+ llm=llm,
378
+ )
379
+
380
+ report_writer = Agent(
381
+ role="Technical Report Writer",
382
+ goal="Write a structured report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
383
+ backstory="Specializes in detailed analytical reports without conclusions.",
384
+ llm=llm,
385
+ )
386
+
387
+ conclusion_writer = Agent(
388
+ role="Conclusion Specialist",
389
+ goal="Summarize findings into a clear and concise 3-5 line Conclusion highlighting only the most important insights.",
390
+ backstory="An expert in crafting impactful and clear conclusions.",
391
+ llm=llm,
392
+ )
393
+
394
+ # Define tasks for report and conclusion
395
+ extract_data = Task(
396
+ description="Extract data based on the query: {query}.",
397
+ expected_output="Database results matching the query.",
398
+ agent=sql_dev,
399
+ )
400
+
401
+ analyze_data = Task(
402
+ description="Analyze the extracted data for query: {query}.",
403
+ expected_output="Key Insights and Analysis without any Introduction or Conclusion.",
404
+ agent=data_analyst,
405
+ context=[extract_data],
406
+ )
407
+
408
+ write_report = Task(
409
+ description="Write the analysis report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
410
+ expected_output="Markdown-formatted report excluding Conclusion.",
411
+ agent=report_writer,
412
+ context=[analyze_data],
413
+ )
414
+
415
+ write_conclusion = Task(
416
+ description="Summarize the key findings in 3-5 impactful lines, highlighting the maximum, minimum, and average salaries."
417
+ "Emphasize significant insights on salary distribution and influential compensation trends for strategic decision-making.",
418
+ expected_output="Markdown-formatted Conclusion section with key insights and statistics.",
419
+ agent=conclusion_writer,
420
+ context=[analyze_data],
421
+ )
422
+
423
+
424
+
425
+ # Separate Crews for report and conclusion
426
+ crew_report = Crew(
427
+ agents=[sql_dev, data_analyst, report_writer],
428
+ tasks=[extract_data, analyze_data, write_report],
429
+ process=Process.sequential,
430
+ verbose=True,
431
+ )
432
+
433
+ crew_conclusion = Crew(
434
+ agents=[data_analyst, conclusion_writer],
435
+ tasks=[write_conclusion],
436
+ process=Process.sequential,
437
+ verbose=True,
438
+ )
439
+
440
+ # Tabs for Query Results and Visualizations
441
+ tab1, tab2 = st.tabs(["πŸ” Query Insights + Viz", "πŸ“Š Full Data Viz"])
442
+
443
+ # Query Insights + Visualization
444
+ with tab1:
445
+ query = st.text_area("Enter Query:", value="Provide insights into the salary of a Principal Data Scientist.")
446
+ if st.button("Submit Query"):
447
+ with st.spinner("Processing query..."):
448
+ # Step 1: Generate the analysis report
449
+ report_inputs = {"query": query + " Provide detailed analysis but DO NOT include Conclusion."}
450
+ report_result = crew_report.kickoff(inputs=report_inputs)
451
+
452
+ # Step 2: Generate only the concise conclusion
453
+ conclusion_inputs = {"query": query + " Provide ONLY the most important insights in 3-5 concise lines."}
454
+ conclusion_result = crew_conclusion.kickoff(inputs=conclusion_inputs)
455
+
456
+ # Step 3: Display the report
457
+ #st.markdown("### Analysis Report:")
458
+ st.markdown(report_result if report_result else "⚠️ No Report Generated.")
459
+
460
+ # Step 4: Generate Visualizations
461
+
462
+
463
+ # Step 5: Insert Visual Insights
464
+ st.markdown("### Visual Insights")
465
+
466
+
467
+ # Step 6: Display Concise Conclusion
468
+ #st.markdown("#### Conclusion")
469
+
470
+ safe_conclusion = escape_markdown(conclusion_result if conclusion_result else "⚠️ No Conclusion Generated.")
471
+ st.markdown(safe_conclusion)
472
+
473
+ # Full Data Visualization Tab
474
+ with tab2:
475
+ st.subheader("πŸ“Š Comprehensive Data Visualizations")
476
+
477
+ fig1 = px.histogram(st.session_state.df, x="job_title", title="Job Title Frequency")
478
+ st.plotly_chart(fig1)
479
+
480
+ fig2 = px.bar(
481
+ st.session_state.df.groupby("experience_level")["salary_in_usd"].mean().reset_index(),
482
+ x="experience_level", y="salary_in_usd",
483
+ title="Average Salary by Experience Level"
484
+ )
485
+ st.plotly_chart(fig2)
486
+
487
+ fig3 = px.box(st.session_state.df, x="employment_type", y="salary_in_usd",
488
+ title="Salary Distribution by Employment Type")
489
+ st.plotly_chart(fig3)
490
+
491
+ temp_dir.cleanup()
492
+ else:
493
+ st.info("Please load a dataset to proceed.")
494
+
495
+
496
+ # Sidebar Reference
497
+ with st.sidebar:
498
+ st.header("πŸ“š Reference:")
499
+ 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)")