Parthiban97 commited on
Commit
dca9fb6
·
verified ·
1 Parent(s): b4182e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -71
app.py CHANGED
@@ -8,6 +8,9 @@ from langchain_community.utilities import SQLDatabase
8
  from langchain_core.output_parsers import StrOutputParser
9
  from langchain_openai import ChatOpenAI
10
  from langchain_groq import ChatGroq
 
 
 
11
 
12
  # Function to update config.toml file
13
  def update_secrets_file(user, data):
@@ -23,11 +26,8 @@ def update_secrets_file(user, data):
23
  secrets_data = {}
24
 
25
  # Update user-specific secrets data
26
- if user not in secrets_data:
27
- secrets_data[user] = {}
28
-
29
- secrets_data[user].update(data)
30
-
31
  # Write updated data back to config.toml
32
  with open(secrets_file_path, "w") as file:
33
  toml.dump(secrets_data, file)
@@ -66,80 +66,82 @@ def get_sql_chain(dbs, llm):
66
  Write the SQL queries for each relevant database, prefixed by the database name (e.g., DB1: SELECT * FROM ...; DB2: SELECT * FROM ...).
67
  Do not wrap the SQL queries in any other text, not even backticks.
68
 
 
69
  For example:
70
- Question: which 3 artists have the most tracks?
 
71
  SQL Query: SELECT ArtistId, COUNT(*) as track_count FROM Track GROUP BY ArtistId ORDER BY track_count DESC LIMIT 3;
 
72
  Question: Name 10 artists
73
  SQL Query: SELECT Name FROM Artist LIMIT 10;
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  Question: How much is the price of the inventory for all small size t-shirts?
75
  SQL Query: SELECT SUM(price * stock_quantity) FROM t_shirts WHERE size = 'S';
76
- Question: If we have to sell all the Levi's T-shirts today with discounts applied. How much revenue our store will generate (post discounts)?
77
- SQL Query: SELECT SUM(a.total_amount * ((100 - COALESCE(discounts.pct_discount, 0)) / 100)) AS total_revenue
78
- FROM (SELECT SUM(price * stock_quantity) AS total_amount, t_shirt_id
79
- FROM t_shirts
80
- WHERE brand = 'Levi' GROUP BY t_shirt_id) a
81
- LEFT JOIN discounts ON a.t_shirt_id = discounts.t_shirt_id;
82
  Question: For each brand, find the total revenue generated from t-shirts with a discount applied, grouped by the discount percentage.
83
- SQL Query: SELECT brand, COALESCE(discounts.pct_discount, 0) AS discount_pct, SUM(t.price * t.stock_quantity * (1 - COALESCE(discounts.pct_discount, 0) / 100)) AS total_revenue
84
- FROM t_shirts t
85
- LEFT JOIN discounts ON t.t_shirt_id = discounts.t_shirt_id
86
- GROUP BY brand, COALESCE(discounts.pct_discount, 0);
87
  Question: Find the top 3 most popular colors for each brand, based on the total stock quantity.
88
- SQL Query: SELECT brand, color, SUM(stock_quantity) AS total_stock
89
- FROM t_shirts
90
- GROUP BY brand, color
91
- ORDER BY brand, total_stock DESC;
92
-
93
  Question: Calculate the average price per size for each brand, excluding sizes with less than 10 t-shirts in stock.
94
- SQL Query: SELECT brand, size, AVG(price) AS avg_price
95
- FROM t_shirts
96
- WHERE stock_quantity >= 10
97
- GROUP BY brand, size
98
- HAVING COUNT(*) >= 10;
99
-
100
  Question: Find the brand and color combination with the highest total revenue, considering discounts.
101
- SQL Query: SELECT brand, color, SUM(t.price * t.stock_quantity * (1 - COALESCE(d.pct_discount, 0) / 100)) AS total_revenue
102
- FROM t_shirts t
103
- LEFT JOIN discounts d ON t.t_shirt_id = d.t_shirt_id
104
- GROUP BY brand, color
105
- ORDER BY total_revenue DESC
106
- LIMIT 1;
107
-
108
  Question: Create a view that shows the total stock quantity and revenue for each brand, size, and color combination.
109
- SQL Query: CREATE VIEW brand_size_color_stats AS
110
- SELECT brand, size, color, SUM(stock_quantity) AS total_stock, SUM(price * stock_quantity) AS total_revenue
111
- FROM t_shirts
112
- GROUP BY brand, size, color;
113
-
114
- Question: How much is the price of the inventory for all varients t-shirts and group them y brands?
115
  SQL Query: SELECT brand, SUM(price * stock_quantity) FROM t_shirts GROUP BY brand;
116
-
117
- Question: List the total revenue of t-shirts of L size for all brands
118
- SQL Query: SELECT brand, SUM(price * stock_quantity) AS total_revenue FROM t_shirts WHERE size = 'L' GROUP BY brand;
119
-
120
  Question: How many shirts are available in stock grouped by colours from each size and finally show me all brands?
121
- SQL Query: SELECT brand, color, size, SUM(stock_quantity) AS total_stock FROM t_shirts GROUP BY brand, color, size
122
-
123
  Question: select all the movies with minimum and maximum release_year. Note that there can be more than one movies in min and max year hence output rows can be more than 2?
124
- SQL Query: select * from movies where release_year in (
125
- (select min(release_year) from movies),
126
- (select max(release_year) from movies));
127
 
128
  Question: Generate a yearly report for Croma India where there are two columns 1. Fiscal Year and 2. Total Gross Sales amount In that year from Croma
129
- SQL Query: select
130
- get_fiscal_year(date) as fiscal_year,
131
- sum(round(sold_quantity*g.gross_price,2)) as yearly_sales
132
- from fact_sales_monthly s
133
- join fact_gross_price g
134
- on
135
- g.fiscal_year=get_fiscal_year(s.date) and
136
- g.product_code=s.product_code
137
- where
138
- customer_code=90002002
139
- group by get_fiscal_year(date)
140
- order by fiscal_year;
141
-
142
-
 
 
 
 
 
 
 
143
  Your turn:
144
 
145
  Question: {question}
@@ -153,12 +155,31 @@ def get_sql_chain(dbs, llm):
153
  schemas = {db_name: db.get_table_info() for db_name, db in dbs.items()}
154
  return schemas
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  return (
157
  RunnablePassthrough.assign(schemas=get_schema)
158
  | prompt
159
  | llm
160
  | StrOutputParser()
161
- | (lambda result: {line.split(":")[0]: line.split(":")[1].strip() for line in result.strip().split("\n") if ":" in line and line.strip()})
162
  )
163
 
164
  # Function to get response
@@ -172,11 +193,13 @@ def get_response(user_query, dbs, chat_history, llm):
172
  accurate natural language response so that the end user can understand things
173
  and make sure do not include words like "Based on the SQL queries I ran".
174
  Just provide only the answer with some text that the user expects.
 
175
  <SCHEMAS>{schemas}</SCHEMAS>
176
  Conversation History: {chat_history}
177
  SQL Queries: <SQL>{queries}</SQL>
178
  User question: {question}
179
- SQL Responses: {responses}"""
 
180
 
181
  prompt = ChatPromptTemplate.from_template(template)
182
  llm = llm
@@ -185,12 +208,14 @@ def get_response(user_query, dbs, chat_history, llm):
185
  responses = {}
186
  for db_name, query in var["queries"].items():
187
  responses[db_name] = dbs[db_name].run(query)
 
 
188
  return responses
189
 
190
  chain = (
191
  RunnablePassthrough.assign(queries=sql_chain).assign(
192
  schemas=lambda _: {db_name: db.get_table_info() for db_name, db in dbs.items()},
193
- responses=run_queries) # The comma at the end of the assign() method call is used to indicate that there may be more keyword arguments or method calls following it
194
  | prompt
195
  | llm
196
  | StrOutputParser()
@@ -210,23 +235,43 @@ if "chat_history" not in st.session_state:
210
  st.set_page_config(page_title="Chat with MySQL", page_icon="🛢️")
211
  st.title("Chat with MySQL")
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  with st.sidebar:
214
  st.subheader("Settings")
215
  st.write("This is a simple chat application using MySQL. Connect to the database and start chatting.")
216
 
217
  if "db" not in st.session_state:
218
- st.session_state.user_id = st.text_input("User ID")
219
  st.session_state.Host = st.text_input("Host")
220
  st.session_state.Port = st.text_input("Port")
221
  st.session_state.User = st.text_input("User")
222
  st.session_state.Password = st.text_input("Password", type="password")
223
  st.session_state.Databases = st.text_input("Databases", placeholder="Enter DB's separated by (,)")
224
  st.session_state.openai_api_key = st.text_input("OpenAI API Key", type="password", help="Get your API key from [OpenAI Website](https://platform.openai.com/api-keys)")
 
225
  st.session_state.groq_api_key = st.text_input("Groq API Key", type="password", help="Get your API key from [GROQ Console](https://console.groq.com/keys)")
226
-
227
- st.info("Note: For interacting multiple databases, GPT-4 Model is recommended for accurate results else proceed with Groq Model")
228
 
 
229
  os.environ["OPENAI_API_KEY"] = str(st.session_state.openai_api_key)
 
230
 
231
  if st.button("Connect"):
232
  with st.spinner("Connecting to databases..."):
@@ -253,9 +298,9 @@ with st.sidebar:
253
  if st.session_state.openai_api_key == "" and st.session_state.groq_api_key == "":
254
  st.error("Enter one API Key At least")
255
  elif st.session_state.openai_api_key:
256
- st.session_state.llm = ChatOpenAI(model="gpt-4-turbo", api_key=st.session_state.openai_api_key)
257
  elif st.session_state.groq_api_key:
258
- st.session_state.llm = ChatGroq(model="llama3-70b-8192", temperature=0.4, api_key=st.session_state.groq_api_key)
259
  else:
260
  pass
261
 
 
8
  from langchain_core.output_parsers import StrOutputParser
9
  from langchain_openai import ChatOpenAI
10
  from langchain_groq import ChatGroq
11
+ #from dotenv import load_dotenv
12
+
13
+ #load_dotenv()
14
 
15
  # Function to update config.toml file
16
  def update_secrets_file(user, data):
 
26
  secrets_data = {}
27
 
28
  # Update user-specific secrets data
29
+ secrets_data[user] = data
30
+
 
 
 
31
  # Write updated data back to config.toml
32
  with open(secrets_file_path, "w") as file:
33
  toml.dump(secrets_data, file)
 
66
  Write the SQL queries for each relevant database, prefixed by the database name (e.g., DB1: SELECT * FROM ...; DB2: SELECT * FROM ...).
67
  Do not wrap the SQL queries in any other text, not even backticks.
68
 
69
+
70
  For example:
71
+
72
+ Question: Which 3 artists have the most tracks?
73
  SQL Query: SELECT ArtistId, COUNT(*) as track_count FROM Track GROUP BY ArtistId ORDER BY track_count DESC LIMIT 3;
74
+
75
  Question: Name 10 artists
76
  SQL Query: SELECT Name FROM Artist LIMIT 10;
77
+
78
+ Question:can you show SRK( a.k.a Shah Rukh Khan) movies where the imdb rating is greater than average rating of all movies and also show which movie had highest revenue in millions (INR)
79
+ SQL Query: SELECT m.title, m.imdb_rating, f.revenue
80
+ FROM movies m
81
+ JOIN financials f ON m.movie_id = f.movie_id
82
+ JOIN movie_actor ma ON m.movie_id = ma.movie_id
83
+ JOIN actors a ON ma.actor_id = a.actor_id
84
+ WHERE a.name = 'Shah Rukh Khan' AND m.imdb_rating > (SELECT AVG(imdb_rating) FROM movies)
85
+ ORDER BY f.revenue DESC;
86
+
87
+ Question: How many Van huesen black medium t shirts are available in stock?
88
+ SQL Query: SELECT SUM(stock_quantity) FROM t_shirts WHERE brand = 'Van Huesen' AND color = 'Black' AND size = 'M';
89
+
90
  Question: How much is the price of the inventory for all small size t-shirts?
91
  SQL Query: SELECT SUM(price * stock_quantity) FROM t_shirts WHERE size = 'S';
92
+
93
+ Question: If we have to sell all the Levi's T-shirts today with discounts applied, how much revenue our store will generate (post discounts)?
94
+ SQL Query: SELECT SUM(a.total_amount * ((100 - COALESCE(discounts.pct_discount, 0)) / 100)) AS total_revenue FROM (SELECT SUM(price * stock_quantity) AS total_amount, t_shirt_id FROM t_shirts WHERE brand = 'Levi' GROUP BY t_shirt_id) a LEFT JOIN discounts ON a.t_shirt_id = discounts.t_shirt_id;
95
+
 
 
96
  Question: For each brand, find the total revenue generated from t-shirts with a discount applied, grouped by the discount percentage.
97
+ SQL Query: SELECT brand, COALESCE(discounts.pct_discount, 0) AS discount_pct, SUM(t.price * t.stock_quantity * (1 - COALESCE(discounts.pct_discount, 0) / 100)) AS total_revenue FROM t_shirts t LEFT JOIN discounts ON t.t_shirt_id = discounts.t_shirt_id GROUP BY brand, COALESCE(discounts.pct_discount, 0);
98
+
 
 
99
  Question: Find the top 3 most popular colors for each brand, based on the total stock quantity.
100
+ SQL Query: SELECT brand, color, SUM(stock_quantity) AS total_stock FROM t_shirts GROUP BY brand, color ORDER BY brand, total_stock DESC;
101
+
 
 
 
102
  Question: Calculate the average price per size for each brand, excluding sizes with less than 10 t-shirts in stock.
103
+ SQL Query: SELECT brand, size, AVG(price) AS avg_price FROM t_shirts WHERE stock_quantity >= 10 GROUP BY brand, size HAVING COUNT(*) >= 10;
104
+
 
 
 
 
105
  Question: Find the brand and color combination with the highest total revenue, considering discounts.
106
+ SQL Query: SELECT brand, color, SUM(t.price * t.stock_quantity * (1 - COALESCE(d.pct_discount, 0) / 100)) AS total_revenue FROM t_shirts t LEFT JOIN discounts d ON t.t_shirt_id = d.t_shirt_id GROUP BY brand, color ORDER BY total_revenue DESC LIMIT 1;
107
+
 
 
 
 
 
108
  Question: Create a view that shows the total stock quantity and revenue for each brand, size, and color combination.
109
+ SQL Query: CREATE VIEW brand_size_color_stats AS SELECT brand, size, color, SUM(stock_quantity) AS total_stock, SUM(price * stock_quantity) AS total_revenue FROM t_shirts GROUP BY brand, size, color;
110
+
111
+ Question: How much is the price of the inventory for all variants of t-shirts and group them by brands?
 
 
 
112
  SQL Query: SELECT brand, SUM(price * stock_quantity) FROM t_shirts GROUP BY brand;
113
+
114
+ Question: List the total revenue of t-shirts of L size for all brands.
115
+ SQL Query: SELECT brand, SUM(price * stock_quantity) AS total_revenue FROM t_shirts WHERE size = 'L' GROUP BY brand;
116
+
117
  Question: How many shirts are available in stock grouped by colours from each size and finally show me all brands?
118
+ SQL Query: SELECT brand, color, size, SUM(stock_quantity) AS total_stock FROM t_shirts GROUP BY brand, color, size;
119
+
120
  Question: select all the movies with minimum and maximum release_year. Note that there can be more than one movies in min and max year hence output rows can be more than 2?
121
+ SQL Query: select * from movies where release_year in (select min(release_year) from movies, select max(release_year) from movies);
 
 
122
 
123
  Question: Generate a yearly report for Croma India where there are two columns 1. Fiscal Year and 2. Total Gross Sales amount In that year from Croma
124
+ SQL Query: select get_fiscal_year(date) as fiscal_year, sum(round(sold_quantity*g.gross_price,2)) as yearly_sales from fact_sales_monthly s join fact_gross_price g on g.fiscal_year=get_fiscal_year(s.date) and g.product_code=s.product_code where customer_code=90002002 group by get_fiscal_year(date) order by fiscal_year;
125
+
126
+ Question: What is the total freight cost incurred by each customer in the month of May 2024?
127
+ SQL Query: SELECT s.customer_name, SUM(f.freight_cost) AS total_freight_cost FROM gdb0041.sales_monthly s JOIN gdb056.freight_cost f ON s.customer_id = f.customer_id WHERE s.month = 'May 2024' GROUP BY s.customer_id;
128
+
129
+ Question: Which market has the highest gross price sales in the last quarter?
130
+ SQL Query: SELECT s.market, SUM(g.gross_price) AS total_gross_price FROM gdb041.sales_monthly s JOIN gdb056.gross_price g ON s.market_id = g.market_id WHERE s.quarter = 'Q2 2024' GROUP BY s.market_id ORDER BY total_gross_price DESC LIMIT 1;
131
+
132
+ Question: What is the manufacturing cost of products sold in each region last year?
133
+ SQL Query: SELECT s.region, SUM(m.manufacturing_cost) AS total_manufacturing_cost FROM gdb0041.sales_monthly s JOIN gdb056.manufacturing_cost m ON s.product_id = m.product_id WHERE s.year = 2023 GROUP BY s.region;
134
+
135
+ Question: How many pre-invoice deductions were applied to each customer's sales in the last six months?
136
+ SQL Query: SELECT s.customer_name, COUNT(p.pre_invoice_deduction_id) AS total_pre_invoice_deductions FROM gdb041.sales_monthly s JOIN gdb056.pre_invoice_deductions p ON s.sales_id = p.sales_id WHERE s.date BETWEEN DATE_SUB(NOW(), INTERVAL 6 MONTH) AND NOW() GROUP BY s.customer_id;
137
+
138
+ Question: What are the post-invoice deductions for each product in the current year?
139
+ SQL Query: SELECT f.product_name, SUM(p.amount) AS total_post_invoice_deductions FROM gdb0041.forecast_monthly f JOIN gdb056.post_invoice_deductions p ON f.product_id = p.product_id WHERE YEAR(f.date) = YEAR(NOW()) GROUP BY f.product_id;
140
+
141
+ Question: How many movies did Sanjay Dutt act in, and which film gained the most revenue, ordered from highest to lowest revenue?
142
+ SQL Query: SELECT m.title, SUM(b.revenue) AS total_revenue FROM movies m JOIN box_office b ON m.movie_id = b.movie_id JOIN movie_actor ma ON m.movie_id = ma.movie_id JOIN actors a ON ma.actor_id = a.actor_id WHERE a.name = 'Sanjay Dutt' GROUP BY m.title ORDER BY total_revenue DESC;
143
+
144
+
145
  Your turn:
146
 
147
  Question: {question}
 
155
  schemas = {db_name: db.get_table_info() for db_name, db in dbs.items()}
156
  return schemas
157
 
158
+ def parse_multi_line_queries(result):
159
+ queries = {}
160
+ lines = result.strip().split("\n")
161
+ current_db = None
162
+ current_query = []
163
+
164
+ for line in lines:
165
+ if ":" in line and not current_db: # Only split on colon for the database name
166
+ current_db, query_start = line.split(":", 1)
167
+ current_db = current_db.strip()
168
+ current_query.append(query_start.strip())
169
+ else:
170
+ current_query.append(line.strip())
171
+
172
+ if current_db:
173
+ queries[current_db] = " ".join(current_query).strip()
174
+
175
+ return queries
176
+
177
  return (
178
  RunnablePassthrough.assign(schemas=get_schema)
179
  | prompt
180
  | llm
181
  | StrOutputParser()
182
+ | parse_multi_line_queries
183
  )
184
 
185
  # Function to get response
 
193
  accurate natural language response so that the end user can understand things
194
  and make sure do not include words like "Based on the SQL queries I ran".
195
  Just provide only the answer with some text that the user expects.
196
+
197
  <SCHEMAS>{schemas}</SCHEMAS>
198
  Conversation History: {chat_history}
199
  SQL Queries: <SQL>{queries}</SQL>
200
  User question: {question}
201
+ SQL Responses: {responses}
202
+ """
203
 
204
  prompt = ChatPromptTemplate.from_template(template)
205
  llm = llm
 
208
  responses = {}
209
  for db_name, query in var["queries"].items():
210
  responses[db_name] = dbs[db_name].run(query)
211
+ print(dbs.keys())
212
+ print(var["queries"].keys())
213
  return responses
214
 
215
  chain = (
216
  RunnablePassthrough.assign(queries=sql_chain).assign(
217
  schemas=lambda _: {db_name: db.get_table_info() for db_name, db in dbs.items()},
218
+ responses=run_queries,) # The comma at the end of the assign() method call is used to indicate that there may be more keyword arguments or method calls following it
219
  | prompt
220
  | llm
221
  | StrOutputParser()
 
235
  st.set_page_config(page_title="Chat with MySQL", page_icon="🛢️")
236
  st.title("Chat with MySQL")
237
 
238
+ # Define model options
239
+ model_options_groq = [
240
+ "llama-3.1-70b-versatile",
241
+ "llama-3.1-8b-instant",
242
+ "llama3-70b-8192",
243
+ "llama3-8b-8192",
244
+ "mixtral-8x7b-32768",
245
+ "gemma2-9b-it"
246
+ ]
247
+
248
+ model_options_openai = [
249
+ "gpt-4o",
250
+ "gpt-4o-mini",
251
+ "gpt-4-turbo",
252
+ "gpt-3.5-turbo-0125"
253
+ ]
254
+
255
  with st.sidebar:
256
  st.subheader("Settings")
257
  st.write("This is a simple chat application using MySQL. Connect to the database and start chatting.")
258
 
259
  if "db" not in st.session_state:
260
+ st.session_state.user_id = st.text_input("User ID",placeholder="Enter any random numbers")
261
  st.session_state.Host = st.text_input("Host")
262
  st.session_state.Port = st.text_input("Port")
263
  st.session_state.User = st.text_input("User")
264
  st.session_state.Password = st.text_input("Password", type="password")
265
  st.session_state.Databases = st.text_input("Databases", placeholder="Enter DB's separated by (,)")
266
  st.session_state.openai_api_key = st.text_input("OpenAI API Key", type="password", help="Get your API key from [OpenAI Website](https://platform.openai.com/api-keys)")
267
+ selected_model_openai = st.selectbox("Select any OpenAI Model", model_options_openai)
268
  st.session_state.groq_api_key = st.text_input("Groq API Key", type="password", help="Get your API key from [GROQ Console](https://console.groq.com/keys)")
269
+ selected_model_groq = st.selectbox("Select any Groq Model", model_options_groq)
270
+ st.info("Note: For interacting multiple databases and dealing with complex queries, GPT-4 Model is recommended for accurate results else proceed with Groq Model")
271
 
272
+
273
  os.environ["OPENAI_API_KEY"] = str(st.session_state.openai_api_key)
274
+
275
 
276
  if st.button("Connect"):
277
  with st.spinner("Connecting to databases..."):
 
298
  if st.session_state.openai_api_key == "" and st.session_state.groq_api_key == "":
299
  st.error("Enter one API Key At least")
300
  elif st.session_state.openai_api_key:
301
+ st.session_state.llm = ChatOpenAI(model=selected_model_openai, api_key=st.session_state.openai_api_key)
302
  elif st.session_state.groq_api_key:
303
+ st.session_state.llm = ChatGroq(model_name=selected_model_groq, temperature=0.5, api_key=st.session_state.groq_api_key)
304
  else:
305
  pass
306