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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
+ # Dynamically generate Plotly visualizations based on GPT-4o suggestions
112
+ def generate_visualization(suggestion, df):
113
+ chart_type = suggestion.get("chart_type", "bar").lower()
114
+ x_axis = suggestion.get("x_axis")
115
+ y_axis = suggestion.get("y_axis")
116
+ group_by = suggestion.get("group_by")
117
+
118
+ # Dynamically determine the best Y-axis if GPT-4o doesn't suggest one
119
+ if not y_axis:
120
+ numeric_columns = df.select_dtypes(include='number').columns.tolist()
121
+
122
+ if x_axis in numeric_columns:
123
+ # Avoid using the same column for both axes
124
+ numeric_columns.remove(x_axis)
125
+
126
+ # Prioritize the first available numeric column for y-axis
127
+ y_axis = numeric_columns[0] if numeric_columns else None
128
+
129
+ # Ensure both axes are identified
130
+ if not x_axis or not y_axis:
131
+ st.warning("⚠️ Unable to determine relevant columns for visualization.")
132
+ return None
133
+
134
+ # Dynamically select the Plotly function
135
+ plotly_function = getattr(px, chart_type, None)
136
+
137
+ if not plotly_function:
138
+ st.warning(f"⚠️ Unsupported chart type '{chart_type}' suggested by GPT-4o.")
139
+ return None
140
+
141
+ # Prepare dynamic plot arguments
142
+ plot_args = {"data_frame": df, "x": x_axis, "y": y_axis}
143
+ if group_by and group_by in df.columns:
144
+ plot_args["color"] = group_by
145
+
146
+ try:
147
+ # Generate the dynamic visualization
148
+ fig = plotly_function(**plot_args)
149
+ fig.update_layout(
150
+ title=f"{chart_type.title()} Plot of {y_axis.replace('_', ' ').title()} by {x_axis.replace('_', ' ').title()}",
151
+ xaxis_title=x_axis.replace('_', ' ').title(),
152
+ yaxis_title=y_axis.replace('_', ' ').title(),
153
+ )
154
+
155
+ # Apply statistics intelligently
156
+ fig = add_stats_to_figure(fig, df, y_axis, chart_type)
157
+
158
+ return fig
159
+
160
+ except Exception as e:
161
+ st.error(f"⚠️ Failed to generate visualization: {e}")
162
+ return None
163
+
164
+
165
+ def add_stats_to_figure(fig, df, y_axis, chart_type):
166
+ # Calculate statistics
167
+ min_val = df[y_axis].min()
168
+ max_val = df[y_axis].max()
169
+ avg_val = df[y_axis].mean()
170
+ median_val = df[y_axis].median()
171
+ std_dev_val = df[y_axis].std()
172
+
173
+ # Stats summary text
174
+ stats_text = (
175
+ f"πŸ“Š **Statistics**\n\n"
176
+ f"- **Min:** ${min_val:,.2f}\n"
177
+ f"- **Max:** ${max_val:,.2f}\n"
178
+ f"- **Average:** ${avg_val:,.2f}\n"
179
+ f"- **Median:** ${median_val:,.2f}\n"
180
+ f"- **Std Dev:** ${std_dev_val:,.2f}"
181
+ )
182
+
183
+ # Charts suitable for stats annotations
184
+ if chart_type in ["bar", "line", "scatter"]:
185
+ # Add annotation box
186
+ fig.add_annotation(
187
+ text=stats_text,
188
+ xref="paper", yref="paper",
189
+ x=1.05, y=1,
190
+ showarrow=False,
191
+ align="left",
192
+ font=dict(size=12, color="black"),
193
+ bordercolor="black",
194
+ borderwidth=1,
195
+ bgcolor="rgba(255, 255, 255, 0.8)"
196
+ )
197
+
198
+ # Add horizontal lines for min, median, avg, max
199
+ fig.add_hline(y=min_val, line_dash="dot", line_color="red", annotation_text="Min", annotation_position="bottom right")
200
+ fig.add_hline(y=median_val, line_dash="dash", line_color="orange", annotation_text="Median", annotation_position="top right")
201
+ fig.add_hline(y=avg_val, line_dash="dashdot", line_color="green", annotation_text="Avg", annotation_position="top right")
202
+ fig.add_hline(y=max_val, line_dash="dot", line_color="blue", annotation_text="Max", annotation_position="top right")
203
+
204
+ elif chart_type == "box":
205
+ # Box plots already show distribution (no extra stats needed)
206
+ pass
207
+
208
+ elif chart_type == "pie":
209
+ # Pie charts don't need statistical overlays
210
+ st.info("πŸ“Š Pie charts focus on proportions. No additional stats displayed.")
211
+
212
+ else:
213
+ st.warning(f"⚠️ No stats added for unsupported chart type: {chart_type}")
214
+
215
+ return fig
216
+
217
+
218
+ # Function to create TXT file
219
+ def create_text_report_with_viz_temp(report, conclusion, visualizations):
220
+ content = f"### Analysis Report\n\n{report}\n\n### Visualizations\n"
221
+
222
+ for i, fig in enumerate(visualizations, start=1):
223
+ fig_title = fig.layout.title.text if fig.layout.title.text else f"Visualization {i}"
224
+ x_axis = fig.layout.xaxis.title.text if fig.layout.xaxis.title.text else "X-axis"
225
+ y_axis = fig.layout.yaxis.title.text if fig.layout.yaxis.title.text else "Y-axis"
226
+
227
+ content += f"\n{i}. {fig_title}\n"
228
+ content += f" - X-axis: {x_axis}\n"
229
+ content += f" - Y-axis: {y_axis}\n"
230
+
231
+ if fig.data:
232
+ trace_types = set(trace.type for trace in fig.data)
233
+ content += f" - Chart Type(s): {', '.join(trace_types)}\n"
234
+ else:
235
+ content += " - No data available in this visualization.\n"
236
+
237
+ content += f"\n\n\n{conclusion}"
238
+
239
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode='w', encoding='utf-8') as temp_txt:
240
+ temp_txt.write(content)
241
+ return temp_txt.name
242
+
243
+
244
+
245
+ # Function to create PDF with report text and visualizations
246
+ def create_pdf_report_with_viz(report, conclusion, visualizations):
247
+ pdf = FPDF()
248
+ pdf.set_auto_page_break(auto=True, margin=15)
249
+ pdf.add_page()
250
+ pdf.set_font("Arial", size=12)
251
+
252
+ # Title
253
+ pdf.set_font("Arial", style="B", size=18)
254
+ pdf.cell(0, 10, "πŸ“Š Analysis Report", ln=True, align="C")
255
+ pdf.ln(10)
256
+
257
+ # Report Content
258
+ pdf.set_font("Arial", style="B", size=14)
259
+ pdf.cell(0, 10, "Analysis", ln=True)
260
+ pdf.set_font("Arial", size=12)
261
+ pdf.multi_cell(0, 10, report)
262
+
263
+ pdf.ln(10)
264
+ pdf.set_font("Arial", style="B", size=14)
265
+ pdf.cell(0, 10, "Conclusion", ln=True)
266
+ pdf.set_font("Arial", size=12)
267
+ pdf.multi_cell(0, 10, conclusion)
268
+
269
+ # Add Visualizations
270
+ pdf.add_page()
271
+ pdf.set_font("Arial", style="B", size=16)
272
+ pdf.cell(0, 10, "πŸ“ˆ Visualizations", ln=True)
273
+ pdf.ln(5)
274
+
275
+ with tempfile.TemporaryDirectory() as temp_dir:
276
+ for i, fig in enumerate(visualizations, start=1):
277
+ fig_title = fig.layout.title.text if fig.layout.title.text else f"Visualization {i}"
278
+ x_axis = fig.layout.xaxis.title.text if fig.layout.xaxis.title.text else "X-axis"
279
+ y_axis = fig.layout.yaxis.title.text if fig.layout.yaxis.title.text else "Y-axis"
280
+
281
+ # Save each visualization as a PNG image
282
+ img_path = os.path.join(temp_dir, f"viz_{i}.png")
283
+ fig.write_image(img_path)
284
+
285
+ # Insert Title and Description
286
+ pdf.set_font("Arial", style="B", size=14)
287
+ pdf.multi_cell(0, 10, f"{i}. {fig_title}")
288
+ pdf.set_font("Arial", size=12)
289
+ pdf.multi_cell(0, 10, f"X-axis: {x_axis} | Y-axis: {y_axis}")
290
+ pdf.ln(3)
291
+
292
+ # Embed Visualization
293
+ pdf.image(img_path, w=170)
294
+ pdf.ln(10)
295
+
296
+ # Save PDF
297
+ temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
298
+ pdf.output(temp_pdf.name)
299
+
300
+ return temp_pdf
301
+
302
+ def escape_markdown(text):
303
+ # Ensure text is a string
304
+ text = str(text)
305
+ # Escape Markdown characters: *, _, `, ~
306
+ escape_chars = r"(\*|_|`|~)"
307
+ return re.sub(escape_chars, r"\\\1", text)
308
+
309
+ # SQL-RAG Analysis
310
+ if st.session_state.df is not None:
311
+ temp_dir = tempfile.TemporaryDirectory()
312
+ db_path = os.path.join(temp_dir.name, "data.db")
313
+ connection = sqlite3.connect(db_path)
314
+ st.session_state.df.to_sql("salaries", connection, if_exists="replace", index=False)
315
+ db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
316
+
317
+ @tool("list_tables")
318
+ def list_tables() -> str:
319
+ """List all tables in the database."""
320
+ return ListSQLDatabaseTool(db=db).invoke("")
321
+
322
+ @tool("tables_schema")
323
+ def tables_schema(tables: str) -> str:
324
+ """Get the schema and sample rows for the specified tables."""
325
+ return InfoSQLDatabaseTool(db=db).invoke(tables)
326
+
327
+ @tool("execute_sql")
328
+ def execute_sql(sql_query: str) -> str:
329
+ """Execute a SQL query against the database and return the results."""
330
+ return QuerySQLDataBaseTool(db=db).invoke(sql_query)
331
+
332
+ @tool("check_sql")
333
+ def check_sql(sql_query: str) -> str:
334
+ """Validate the SQL query syntax and structure before execution."""
335
+ return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
336
+
337
+ # Agents for SQL data extraction and analysis
338
+ sql_dev = Agent(
339
+ role="Senior Database Developer",
340
+ goal="Extract data using optimized SQL queries.",
341
+ backstory="An expert in writing optimized SQL queries for complex databases.",
342
+ llm=llm,
343
+ tools=[list_tables, tables_schema, execute_sql, check_sql],
344
+ )
345
+
346
+ data_analyst = Agent(
347
+ role="Senior Data Analyst",
348
+ goal="Analyze the data and produce insights.",
349
+ backstory="A seasoned analyst who identifies trends and patterns in datasets.",
350
+ llm=llm,
351
+ )
352
+
353
+ report_writer = Agent(
354
+ role="Technical Report Writer",
355
+ goal="Write a structured report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
356
+ backstory="Specializes in detailed analytical reports without conclusions.",
357
+ llm=llm,
358
+ )
359
+
360
+ conclusion_writer = Agent(
361
+ role="Conclusion Specialist",
362
+ goal="Summarize findings into a clear and concise 3-5 line Conclusion highlighting only the most important insights.",
363
+ backstory="An expert in crafting impactful and clear conclusions.",
364
+ llm=llm,
365
+ )
366
+
367
+ # Define tasks for report and conclusion
368
+ extract_data = Task(
369
+ description="Extract data based on the query: {query}.",
370
+ expected_output="Database results matching the query.",
371
+ agent=sql_dev,
372
+ )
373
+
374
+ analyze_data = Task(
375
+ description="Analyze the extracted data for query: {query}.",
376
+ expected_output="Key Insights and Analysis without any Introduction or Conclusion.",
377
+ agent=data_analyst,
378
+ context=[extract_data],
379
+ )
380
+
381
+ write_report = Task(
382
+ description="Write the analysis report with Introduction and Key Insights. DO NOT include any Conclusion or Summary.",
383
+ expected_output="Markdown-formatted report excluding Conclusion.",
384
+ agent=report_writer,
385
+ context=[analyze_data],
386
+ )
387
+
388
+ write_conclusion = Task(
389
+ description="Summarize the key findings in 3-5 impactful lines, highlighting the maximum, minimum, and average salaries."
390
+ "Emphasize significant insights on salary distribution and influential compensation trends for strategic decision-making.",
391
+ expected_output="Markdown-formatted Conclusion section with key insights and statistics.",
392
+ agent=conclusion_writer,
393
+ context=[analyze_data],
394
+ )
395
+
396
+
397
+
398
+ # Separate Crews for report and conclusion
399
+ crew_report = Crew(
400
+ agents=[sql_dev, data_analyst, report_writer],
401
+ tasks=[extract_data, analyze_data, write_report],
402
+ process=Process.sequential,
403
+ verbose=True,
404
+ )
405
+
406
+ crew_conclusion = Crew(
407
+ agents=[data_analyst, conclusion_writer],
408
+ tasks=[write_conclusion],
409
+ process=Process.sequential,
410
+ verbose=True,
411
+ )
412
+
413
+ # Tabs for Query Results and Visualizations
414
+ tab1, tab2 = st.tabs(["πŸ” Query Insights + Viz", "πŸ“Š Full Data Viz"])
415
+
416
+ # Query Insights + Visualization
417
+ with tab1:
418
+ query = st.text_area("Enter Query:", value="Provide insights into the salary of a Principal Data Scientist.")
419
+ if st.button("Submit Query"):
420
+ with st.spinner("Processing query..."):
421
+ # Step 1: Generate the analysis report
422
+ report_inputs = {"query": query + " Provide detailed analysis but DO NOT include Conclusion."}
423
+ report_result = crew_report.kickoff(inputs=report_inputs)
424
+
425
+ # Step 2: Generate only the concise conclusion
426
+ conclusion_inputs = {"query": query + " Provide ONLY the most important insights in 3-5 concise lines."}
427
+ conclusion_result = crew_conclusion.kickoff(inputs=conclusion_inputs)
428
+
429
+ # Step 3: Display the report
430
+ #st.markdown("### Analysis Report:")
431
+ st.markdown(report_result if report_result else "⚠️ No Report Generated.")
432
+
433
+ # Step 4: Generate Visualizations
434
+
435
+
436
+ # Step 5: Insert Visual Insights
437
+ st.markdown("### Visual Insights")
438
+
439
+
440
+ # Step 6: Display Concise Conclusion
441
+ #st.markdown("#### Conclusion")
442
+
443
+ safe_conclusion = escape_markdown(conclusion_result if conclusion_result else "⚠️ No Conclusion Generated.")
444
+ st.markdown(safe_conclusion)
445
+
446
+ # Full Data Visualization Tab
447
+ with tab2:
448
+ st.subheader("πŸ“Š Comprehensive Data Visualizations")
449
+
450
+ fig1 = px.histogram(st.session_state.df, x="job_title", title="Job Title Frequency")
451
+ st.plotly_chart(fig1)
452
+
453
+ fig2 = px.bar(
454
+ st.session_state.df.groupby("experience_level")["salary_in_usd"].mean().reset_index(),
455
+ x="experience_level", y="salary_in_usd",
456
+ title="Average Salary by Experience Level"
457
+ )
458
+ st.plotly_chart(fig2)
459
+
460
+ fig3 = px.box(st.session_state.df, x="employment_type", y="salary_in_usd",
461
+ title="Salary Distribution by Employment Type")
462
+ st.plotly_chart(fig3)
463
+
464
+ temp_dir.cleanup()
465
+ else:
466
+ st.info("Please load a dataset to proceed.")
467
+
468
+
469
+ # Sidebar Reference
470
+ with st.sidebar:
471
+ st.header("πŸ“š Reference:")
472
+ 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)")