DrishtiSharma commited on
Commit
33e0269
Β·
verified Β·
1 Parent(s): 1c75dfd

Create almost_blah.py

Browse files
Files changed (1) hide show
  1. mylab/almost_blah.py +260 -0
mylab/almost_blah.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import sqlite3
4
+ import os
5
+ import json
6
+ from pathlib import Path
7
+ import plotly.express as px
8
+ from datetime import datetime, timezone
9
+ from crewai import Agent, Crew, Process, Task
10
+ from crewai.tools import tool
11
+ from langchain_groq import ChatGroq
12
+ from langchain_openai import ChatOpenAI
13
+ from langchain.schema.output import LLMResult
14
+ from langchain_community.tools.sql_database.tool import (
15
+ InfoSQLDatabaseTool,
16
+ ListSQLDatabaseTool,
17
+ QuerySQLCheckerTool,
18
+ QuerySQLDataBaseTool,
19
+ )
20
+ from langchain_community.utilities.sql_database import SQLDatabase
21
+ from datasets import load_dataset
22
+ import tempfile
23
+
24
+ st.title("SQL-RAG Using CrewAI πŸš€")
25
+ st.write("Analyze datasets using natural language queries powered by SQL and CrewAI.")
26
+
27
+ # Initialize LLM
28
+ llm = None
29
+
30
+ # Model Selection
31
+ model_choice = st.radio("Select LLM", ["GPT-4o", "llama-3.3-70b"], index=0, horizontal=True)
32
+
33
+ # API Key Validation and LLM Initialization
34
+ groq_api_key = os.getenv("GROQ_API_KEY")
35
+ openai_api_key = os.getenv("OPENAI_API_KEY")
36
+
37
+ if model_choice == "llama-3.3-70b":
38
+ if not groq_api_key:
39
+ st.error("Groq API key is missing. Please set the GROQ_API_KEY environment variable.")
40
+ llm = None
41
+ else:
42
+ llm = ChatGroq(groq_api_key=groq_api_key, model="groq/llama-3.3-70b-versatile")
43
+ elif model_choice == "GPT-4o":
44
+ if not openai_api_key:
45
+ st.error("OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable.")
46
+ llm = None
47
+ else:
48
+ llm = ChatOpenAI(api_key=openai_api_key, model="gpt-4o")
49
+
50
+ # Initialize session state for data persistence
51
+ if "df" not in st.session_state:
52
+ st.session_state.df = None
53
+ if "show_preview" not in st.session_state:
54
+ st.session_state.show_preview = False
55
+
56
+ # Dataset Input
57
+ input_option = st.radio("Select Dataset Input:", ["Use Hugging Face Dataset", "Upload CSV File"])
58
+
59
+ if input_option == "Use Hugging Face Dataset":
60
+ dataset_name = st.text_input("Enter Hugging Face Dataset Name:", value="Einstellung/demo-salaries")
61
+ if st.button("Load Dataset"):
62
+ try:
63
+ with st.spinner("Loading dataset..."):
64
+ dataset = load_dataset(dataset_name, split="train")
65
+ st.session_state.df = pd.DataFrame(dataset)
66
+ st.session_state.show_preview = True # Show preview after loading
67
+ st.success(f"Dataset '{dataset_name}' loaded successfully!")
68
+ except Exception as e:
69
+ st.error(f"Error: {e}")
70
+
71
+ elif input_option == "Upload CSV File":
72
+ uploaded_file = st.file_uploader("Upload CSV File:", type=["csv"])
73
+ if uploaded_file:
74
+ try:
75
+ st.session_state.df = pd.read_csv(uploaded_file)
76
+ st.session_state.show_preview = True # Show preview after loading
77
+ st.success("File uploaded successfully!")
78
+ except Exception as e:
79
+ st.error(f"Error loading file: {e}")
80
+
81
+ # Show Dataset Preview Only After Loading
82
+ if st.session_state.df is not None and st.session_state.show_preview:
83
+ st.subheader("πŸ“‚ Dataset Preview")
84
+ st.dataframe(st.session_state.df.head())
85
+
86
+ # SQL-RAG Analysis
87
+ if st.session_state.df is not None:
88
+ temp_dir = tempfile.TemporaryDirectory()
89
+ db_path = os.path.join(temp_dir.name, "data.db")
90
+ connection = sqlite3.connect(db_path)
91
+ st.session_state.df.to_sql("salaries", connection, if_exists="replace", index=False)
92
+ db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
93
+
94
+ @tool("list_tables")
95
+ def list_tables() -> str:
96
+ """List all tables in the database."""
97
+ return ListSQLDatabaseTool(db=db).invoke("")
98
+
99
+ @tool("tables_schema")
100
+ def tables_schema(tables: str) -> str:
101
+ """Get the schema and sample rows for the specified tables."""
102
+ return InfoSQLDatabaseTool(db=db).invoke(tables)
103
+
104
+ @tool("execute_sql")
105
+ def execute_sql(sql_query: str) -> str:
106
+ """Execute a SQL query against the database and return the results."""
107
+ return QuerySQLDataBaseTool(db=db).invoke(sql_query)
108
+
109
+ @tool("check_sql")
110
+ def check_sql(sql_query: str) -> str:
111
+ """Validate the SQL query syntax and structure before execution."""
112
+ return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
113
+
114
+ # Agent for SQL data extraction
115
+ sql_dev = Agent(
116
+ role="Senior Database Developer",
117
+ goal="Extract data using optimized SQL queries.",
118
+ backstory="An expert in writing optimized SQL queries for complex databases.",
119
+ llm=llm,
120
+ tools=[list_tables, tables_schema, execute_sql, check_sql],
121
+ )
122
+
123
+ # Agent for data analysis
124
+ data_analyst = Agent(
125
+ role="Senior Data Analyst",
126
+ goal="Analyze the data and produce insights.",
127
+ backstory="A seasoned analyst who identifies trends and patterns in datasets.",
128
+ llm=llm,
129
+ )
130
+
131
+ # Agent for generating the main report (without Conclusion)
132
+ report_writer = Agent(
133
+ role="Technical Report Writer",
134
+ goal="Summarize the analysis into a structured report with Introduction, Key Insights, and Analysis. DO NOT include any conclusion or summary.",
135
+ backstory="Markdown report excluding Conclusion and Summary.",
136
+ llm=llm,
137
+ )
138
+
139
+ # New Agent for generating ONLY the Conclusion
140
+ conclusion_writer = Agent(
141
+ role="Conclusion Specialist",
142
+ goal="Summarize findings into a clear and concise Conclusion/Summary section.",
143
+ backstory="An expert in crafting well-structured and insightful conclusions.",
144
+ llm=llm,
145
+ )
146
+
147
+ # Tasks for each agent
148
+ extract_data = Task(
149
+ description="Extract data based on the query: {query}.",
150
+ expected_output="Database results matching the query.",
151
+ agent=sql_dev,
152
+ )
153
+
154
+ analyze_data = Task(
155
+ description="Analyze the extracted data for query: {query}.",
156
+ expected_output="Provide ONLY Key Insights and Analysis. Exclude Introduction and Conclusion.",
157
+ agent=data_analyst,
158
+ context=[extract_data],
159
+ )
160
+
161
+ write_report = Task(
162
+ description="Write the report with ONLY Key Insights and Analysis. DO NOT include Introduction or Conclusion.",
163
+ expected_output="Markdown report excluding Introduction and Conclusion.",
164
+ agent=report_writer,
165
+ context=[analyze_data],
166
+ )
167
+
168
+ write_conclusion = Task(
169
+ description="Summarize the findings into a concise Conclusion.",
170
+ expected_output="Markdown-formatted Conclusion section.",
171
+ agent=conclusion_writer,
172
+ context=[analyze_data],
173
+ )
174
+
175
+ # Crew setup
176
+ crew = Crew(
177
+ agents=[sql_dev, data_analyst, report_writer, conclusion_writer],
178
+ tasks=[extract_data, analyze_data, write_report, write_conclusion],
179
+ process=Process.sequential,
180
+ verbose=True,
181
+ )
182
+
183
+ # Tabs for Query Results and General Insights
184
+ tab1, tab2 = st.tabs(["πŸ” Query Insights + Viz", "πŸ“Š Full Data Viz"])
185
+
186
+ # Tab 1: Query-Insights + Visualization
187
+ with tab1:
188
+ query = st.text_area("Enter Query:", value="Provide insights into the salary of a Principal Data Scientist.")
189
+ if st.button("Submit Query"):
190
+ with st.spinner("Processing query..."):
191
+ # Step 1: Generate Report without Conclusion
192
+ report_inputs = {"query": query + " Provide a detailed analysis but DO NOT include a Conclusion."}
193
+ report_result = crew.kickoff(inputs=report_inputs)
194
+
195
+ # Step 2: Generate only the Conclusion
196
+ conclusion_inputs = {"query": query + " Now, provide only the Conclusion for this analysis."}
197
+ conclusion_result = crew.kickoff(inputs=conclusion_inputs)
198
+
199
+ # Directly use the outputs
200
+ main_report = report_result if report_result else "⚠️ No Report Generated."
201
+ conclusion = conclusion_result if conclusion_result else "⚠️ No Conclusion Generated."
202
+
203
+ st.markdown("### Analysis Report:")
204
+ st.markdown(main_report)
205
+
206
+ # Step 3: Generate relevant visualizations
207
+ visualizations = []
208
+
209
+ fig_salary = px.box(st.session_state.df, x="job_title", y="salary_in_usd",
210
+ title="Salary Distribution by Job Title")
211
+ visualizations.append(fig_salary)
212
+
213
+ fig_experience = px.bar(
214
+ st.session_state.df.groupby("experience_level")["salary_in_usd"].mean().reset_index(),
215
+ x="experience_level", y="salary_in_usd",
216
+ title="Average Salary by Experience Level"
217
+ )
218
+ visualizations.append(fig_experience)
219
+
220
+ fig_employment = px.box(st.session_state.df, x="employment_type", y="salary_in_usd",
221
+ title="Salary Distribution by Employment Type")
222
+ visualizations.append(fig_employment)
223
+
224
+ # Step 4: Insert Visual Insights
225
+ st.markdown("## πŸ“Š Visual Insights")
226
+ for fig in visualizations:
227
+ st.plotly_chart(fig, use_container_width=True)
228
+
229
+ # Step 5: Append the Conclusion
230
+ st.markdown("## Conclusion")
231
+ st.markdown(conclusion)
232
+
233
+ # Tab 2: Full Data Visualization
234
+ with tab2:
235
+ st.subheader("πŸ“Š Comprehensive Data Visualizations")
236
+
237
+ fig1 = px.histogram(st.session_state.df, x="job_title", title="Job Title Frequency")
238
+ st.plotly_chart(fig1)
239
+
240
+ fig2 = px.bar(
241
+ st.session_state.df.groupby("experience_level")["salary_in_usd"].mean().reset_index(),
242
+ x="experience_level", y="salary_in_usd",
243
+ title="Average Salary by Experience Level"
244
+ )
245
+ st.plotly_chart(fig2)
246
+
247
+ fig3 = px.box(st.session_state.df, x="employment_type", y="salary_in_usd",
248
+ title="Salary Distribution by Employment Type")
249
+ st.plotly_chart(fig3)
250
+
251
+ temp_dir.cleanup()
252
+ else:
253
+ st.info("Please load a dataset to proceed.")
254
+
255
+
256
+ # Sidebar Reference
257
+ with st.sidebar:
258
+ st.header("πŸ“š Reference:")
259
+ 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)")
260
+