Shivanshutripathi commited on
Commit
cec3c97
·
verified ·
1 Parent(s): 7d8e162

Update gradio1final.py

Browse files
Files changed (1) hide show
  1. gradio1final.py +684 -684
gradio1final.py CHANGED
@@ -1,685 +1,685 @@
1
- import os
2
- import re
3
- import json
4
- import openai
5
- import psycopg2
6
- import google.generativeai as genai
7
- import gradio as gr
8
- from langchain_community.document_loaders.csv_loader import CSVLoader
9
- from langchain.vectorstores import FAISS
10
- from langchain.embeddings.base import Embeddings
11
- from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
12
- from langchain_core.prompts import ChatPromptTemplate
13
- from langchain.output_parsers.json import SimpleJsonOutputParser
14
- from langchain.memory import ConversationBufferMemory
15
- from langchain.chains import LLMChain
16
- from langchain_core.prompts import (
17
- ChatPromptTemplate,
18
- MessagesPlaceholder,
19
- SystemMessagePromptTemplate,
20
- HumanMessagePromptTemplate,
21
- )
22
- from langchain import OpenAI
23
-
24
-
25
-
26
-
27
- os.environ['GOOGLE_API_KEY'] = 'AIzaSyDLwJAr5iXL2Weaw1XphFNSeijytqOSbDg'
28
- os.environ['OPENAI_API_KEY'] = 'sk-proj-Kh4UIWkfDxSGppQpooxXT3BlbkFJATohXqhpkJE6MqliIkmU'
29
- # Set your API keys
30
-
31
- OPENAI_API_KEY = 'sk-proj-Kh4UIWkfDxSGppQpooxXT3BlbkFJATohXqhpkJE6MqliIkmU'
32
- GOOGLE_API_KEY = 'AIzaSyDLwJAr5iXL2Weaw1XphFNSeijytqOSbDg'
33
- openai.api_key = OPENAI_API_KEY
34
- genai.configure(api_key=GOOGLE_API_KEY)
35
-
36
-
37
-
38
-
39
- class OpenAIEmbeddings(Embeddings):
40
- def embed_documents(self, texts):
41
- response = openai.Embedding.create(
42
- model="text-embedding-ada-002",
43
- api_key=OPENAI_API_KEY,
44
- input=texts
45
- )
46
- embeddings = [e["embedding"] for e in response["data"]]
47
- return embeddings
48
-
49
-
50
-
51
-
52
- def embed_query(self, text):
53
- response = openai.Embedding.create(
54
- model="text-embedding-ada-002",
55
- api_key=OPENAI_API_KEY,
56
- input=[text]
57
- )
58
- embedding = response["data"][0]["embedding"]
59
- return embedding
60
-
61
-
62
-
63
-
64
- class GeminiEmbeddings(GoogleGenerativeAIEmbeddings):
65
- def __init__(self, api_key):
66
- super().__init__(model="models/text-embedding-004", google_api_key=GOOGLE_API_KEY)
67
-
68
-
69
-
70
-
71
- def extract_entities_openai(query):
72
- prompt = f"""
73
- Find the entities from the query given below enclosed in triple quotes. Make sure to ONLY return response in JSON format, with the key as "KPI" and extracted entities as list. Example Output JSON:
74
- {{
75
- "KPI": ["Extracted Entity 1", "Extracted Entity 2", ....]
76
- }}
77
-
78
-
79
- Query begins here:
80
- \"\"\"{query}\"\"\"
81
- """
82
- response = openai.ChatCompletion.create(
83
- model="gpt-4",
84
- messages=[
85
- {"role": "user", "content": prompt}
86
- ],
87
- temperature=0
88
- )
89
- return response['choices'][0]['message']['content'].strip()
90
-
91
-
92
-
93
- def extract_entities_gemini(query):
94
- try:
95
- llm_content_summary = ChatGoogleGenerativeAI(
96
- model="gemini-1.5-pro",
97
- temperature=0,
98
- max_tokens=250,
99
- timeout=None,
100
- max_retries=2,
101
- google_api_key=GOOGLE_API_KEY,
102
- )
103
-
104
-
105
-
106
-
107
- prompt = ChatPromptTemplate.from_messages(
108
- [
109
- (
110
- "system", """Use the instructions below to generate responses based on user inputs. Return the answer as a JSON object.""",
111
- ),
112
- ("user", f"""Find the entities from the query given below enclosed in triple quotes. Make sure to ONLY return response in JSON format, with the key as "KPI" and extracted entities as list. Example Output JSON:
113
- "KPI": ["Extracted Entity 1", "Extracted Entity 2", ....]
114
- Query begins here:
115
- \"\"\"{query}\"\"\"
116
- """),
117
- ]
118
- )
119
-
120
-
121
-
122
-
123
- json_parser = SimpleJsonOutputParser()
124
- chain = prompt | llm_content_summary | json_parser
125
- response = chain.invoke({"input": query})
126
-
127
- if isinstance(response, dict):
128
- response = json.dumps(response)
129
-
130
- return response
131
- except Exception as e:
132
- print(f"Error generating content summary: {e}")
133
- return None
134
-
135
-
136
-
137
-
138
- def fetch_table_schema():
139
- try:
140
- conn = psycopg2.connect(
141
- dbname='postgres',
142
- user='shivanshu',
143
- password='root',
144
- host='34.170.181.105',
145
- port='5432'
146
- )
147
- cursor = conn.cursor()
148
- table_name = 'network'
149
- query = f"""
150
- SELECT
151
- column_name,
152
- data_type,
153
- character_maximum_length,
154
- is_nullable
155
- FROM
156
- information_schema.columns
157
- WHERE
158
- table_name = '{table_name}';
159
- """
160
- cursor.execute(query)
161
- rows = cursor.fetchall()
162
- cursor.close()
163
- schema_dict = {
164
- row[0]: {
165
- 'data_type': row[1],
166
- 'character_maximum_length': row[2],
167
- 'is_nullable': row[3]
168
- }
169
- for row in rows
170
- }
171
- return schema_dict
172
- except Exception as e:
173
- print(f"Error fetching table schema: {e}")
174
- return {}
175
-
176
-
177
-
178
-
179
- column_names=[]
180
-
181
- def extract_column_names(sql_query):
182
- # Use a regular expression to extract the part of the query between SELECT and FROM
183
- pattern = r'SELECT\s+(.*?)\s+FROM'
184
- match = re.search(pattern, sql_query, re.IGNORECASE | re.DOTALL)
185
- if not match:
186
- return []
187
-
188
-
189
- columns_part = match.group(1).strip()
190
-
191
- # Split columns based on commas that are not within parentheses
192
- column_names = re.split(r',\s*(?![^()]*\))', columns_part)
193
-
194
- # Process each column to handle aliases and functions
195
- clean_column_names = []
196
- for col in column_names:
197
- # Remove any function wrappers (e.g., TRIM, COUNT, etc.)
198
- col = re.sub(r'\b\w+\((.*?)\)', r'\1', col)
199
-
200
- # Remove any aliases (i.e., words following 'AS')
201
- col = re.split(r'\s+AS\s+', col, flags=re.IGNORECASE)[-1]
202
-
203
- # Strip any remaining whitespace or backticks/quotes
204
- col = col.strip(' `"[]')
205
- clean_column_names.append(col)
206
- return clean_column_names
207
-
208
-
209
- def process_sublist(sublist,similarity_threshold):
210
- processed_list = sublist[0:3]
211
- for index in range(3, len(sublist)):
212
- if sublist[index]['similarity'] >= similarity_threshold:
213
- processed_list.append(sublist[index])
214
- else:
215
- break
216
- return processed_list
217
-
218
-
219
- from langchain_community.chat_models import ChatOpenAI
220
- # Initialize the OpenAI model and memory
221
- openai_model = ChatOpenAI(model='gpt-4', temperature=0, api_key=OPENAI_API_KEY)
222
- openai_memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
223
-
224
- def generate_sql_query_openai(description, table_schema, vector_store, og_table_schema):
225
- global openai_model
226
- global openai_memory
227
- global column_names
228
- try:
229
- user_input = description
230
- print(user_input)
231
- entities = extract_entities_openai(user_input)
232
- entities_obj = json.loads(entities)
233
- kpis = entities_obj['KPI']
234
-
235
- # Fetch similar documents
236
- final_results = []
237
- similar_kpis = []
238
- for kpi in kpis:
239
- docs = vector_store.similarity_search_with_score(kpi, k=6)
240
- results = []
241
- count = 1
242
- for doc, distance in docs:
243
- name_desc = doc.page_content.split("\nDescription: ")
244
- name = name_desc[0].replace("Name: ", "")
245
- description = name_desc[1] if len(name_desc) > 1 else "No description available."
246
- similarity_score = round((1 - distance) * 100, 2) # Convert distance to similarity score in percent
247
- results.append({"name": name, "description": description, "similarity": similarity_score, "Index": count})
248
- similar_kpis.append({"name": name, "similarity": similarity_score})
249
- count += 1 # Increment the count for each result
250
- final_results.append(results)
251
-
252
- # Process results
253
- similarity_threshold = 75.0
254
-
255
- processed_sublists = [process_sublist(sublist,similarity_threshold) for sublist in final_results]
256
- flattened_results = [item for sublist in processed_sublists for item in sublist]
257
-
258
- user_input_entities = [item['name'] for item in flattened_results]
259
- print("BYE1",user_input_entities)
260
-
261
- try:
262
- # Strip whitespace and ensure case matches for comparison
263
- user_input_entities = [key.strip() for key in user_input_entities]
264
- og_table_schema_keys = [key.strip() for key in og_table_schema.keys()]
265
-
266
- # Check and create user_input_table_schema
267
- table_schema = {key: og_table_schema[key] for key in user_input_entities if key in og_table_schema_keys}
268
- print("BYE3",table_schema)
269
- except Exception as e:
270
- print(f"An error occurred: {e}")
271
-
272
-
273
- table_schema = json.dumps(table_schema)
274
- table_schema = table_schema.replace('{', '[')
275
- table_schema = table_schema.replace('}', ']')
276
- print("GG123")
277
- system_message_template1 = f"""Generate the PostgreSQL query for the following task: {description}.
278
- The connection with the database is already setup and the table is called network.
279
- Enclose column names in double quotes ("), but do not use escape characters (e.g., "\").
280
- Do not assign aliases to the columns.
281
- Do not calculate new columns, unless specifically called to.
282
- Return only the PostgreSQL query, nothing else.
283
- The list of all the columns is as follows: {table_schema}
284
- Make sure the response should strictly follow JSON format. The key should be "Query" and the value should be the Postgresql query.
285
- Example Output JSON:
286
- ["Query": PostgreSQL Executable query]"""
287
-
288
- system_message_template = system_message_template1
289
- print(system_message_template)
290
- # Create the ChatPromptTemplate
291
- print("GG1234")
292
- prompt = ChatPromptTemplate(
293
- messages=[
294
- SystemMessagePromptTemplate.from_template(system_message_template),
295
- # Placeholder for chat history
296
- MessagesPlaceholder(variable_name="chat_history"),
297
- # User's question will be dynamically inserted
298
- HumanMessagePromptTemplate.from_template("""
299
- {question}
300
- """)
301
- ]
302
- )
303
-
304
-
305
-
306
- print("GG12345")
307
- conversation = LLMChain(
308
- llm=openai_model,
309
- prompt=prompt,
310
- verbose=True,
311
- memory=openai_memory
312
- )
313
-
314
-
315
-
316
-
317
- print(prompt)
318
- response = conversation.invoke({'question': user_input})
319
- response = response['text']
320
- response = response.replace('\\', '')
321
- print(response)
322
- print("************************************************")
323
- print(type(response))
324
-
325
- # Regular expression pattern to extract the query string
326
- pattern = r'{"Query":\s*"(.*?)"\s*}'
327
- # Extract the content
328
-
329
- sql_query = None
330
- match = re.search(pattern, response)
331
- if match:
332
- sql_query = match.group(1)
333
- print(sql_query)
334
-
335
- print("jiji1")
336
- if sql_query:
337
- # Fetch data from database
338
- results = fetch_data_from_db(sql_query)
339
- print(results)
340
- column_names1 = extract_column_names(sql_query)
341
- column_names=column_names1
342
- print("jiji",column_names)
343
-
344
- else:
345
- column_names=[]
346
- results=[]
347
-
348
- pattern = r'```.*?```(.*)'
349
- match = re.search(pattern, response, re.DOTALL)
350
- print("GG",match)
351
- if match:
352
- response = match.group(1).strip()
353
- print("GG1",response)
354
-
355
- print(type(user_input_entities))
356
- print(type(response))
357
- print(type(sql_query))
358
- print(type(results))
359
- print("Process completed.")
360
- return user_input_entities, response, sql_query, results
361
-
362
- except Exception as e:
363
- print(f"Error generating SQL query: {e}")
364
-
365
-
366
-
367
- gemini_model = ChatGoogleGenerativeAI(model='gemini-1.5-pro-001',temperature=0,google_api_key = GOOGLE_API_KEY)
368
- gemini_memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
369
-
370
- def generate_sql_query_gemini(description, table_schema,vector_store,og_table_schema):
371
- global gemini_model
372
- global gemini_memory
373
- global column_names
374
- try:
375
- user_input = description
376
- print(user_input)
377
- entities = extract_entities_gemini(user_input)
378
- entities_obj = json.loads(entities)
379
- kpis = entities_obj['KPI']
380
-
381
- # Fetch similar documents
382
- final_results = []
383
- similar_kpis = []
384
- for kpi in kpis:
385
- docs = vector_store.similarity_search_with_score(kpi, k=6)
386
- results = []
387
- count = 1
388
- for doc, distance in docs:
389
- name_desc = doc.page_content.split("\nDescription: ")
390
- name = name_desc[0].replace("Name: ", "")
391
- description = name_desc[1] if len(name_desc) > 1 else "No description available."
392
- similarity_score = round((1 - distance) * 100, 2) # Convert distance to similarity score in percent
393
- results.append({"name": name, "description": description, "similarity": similarity_score, "Index": count})
394
- similar_kpis.append({"name": name, "similarity": similarity_score})
395
- count += 1 # Increment the count for each result
396
- final_results.append(results)
397
-
398
- # Process results
399
- similarity_threshold = 75.0
400
-
401
- processed_sublists = [process_sublist(sublist,similarity_threshold) for sublist in final_results]
402
- flattened_results = [item for sublist in processed_sublists for item in sublist]
403
-
404
- user_input_entities = [item['name'] for item in flattened_results]
405
- print("BYE1",user_input_entities)
406
-
407
- try:
408
- # Strip whitespace and ensure case matches for comparison
409
- user_input_entities = [key.strip() for key in user_input_entities]
410
- og_table_schema_keys = [key.strip() for key in og_table_schema.keys()]
411
-
412
- # Check and create user_input_table_schema
413
- table_schema = {key: og_table_schema[key] for key in user_input_entities if key in og_table_schema_keys}
414
- print("BYE3",table_schema)
415
- except Exception as e:
416
- print(f"An error occurred: {e}")
417
-
418
-
419
- table_schema = json.dumps(table_schema)
420
- table_schema = table_schema.replace('{', '[')
421
- table_schema = table_schema.replace('}', ']')
422
- system_message_template1 = f"""Generate the PostgreSQL query for the following task: {description}.
423
- The connection with the database is already setup and the table is called network.
424
- Enclose column names in double quotes ("), but do not use escape characters (e.g., "\").
425
- Do not assign aliases to the columns.
426
- Do not calculate new columns, unless specifically called to.
427
- Return only the PostgreSQL query, nothing else.
428
- The list of all the columns is as follows: {table_schema}
429
- Make sure the response should strictly follow JSON format. The key should be "Query" and the value should be the Postgresql query.
430
- Example Output JSON:
431
- ["Query": PostgreSQL Executable query]"""
432
-
433
- system_message_template = system_message_template1
434
- print(system_message_template)
435
- # Create the ChatPromptTemplate
436
- prompt = ChatPromptTemplate(
437
- messages=[
438
- SystemMessagePromptTemplate.from_template(system_message_template),
439
- # Placeholder for chat history
440
- MessagesPlaceholder(variable_name="chat_history"),
441
- # User's question will be dynamically inserted
442
- HumanMessagePromptTemplate.from_template("""
443
- {question}
444
- """)
445
- ]
446
- )
447
-
448
- conversation = LLMChain(
449
- llm=gemini_model,
450
- prompt=prompt,
451
- verbose=True,
452
- memory=gemini_memory
453
- )
454
-
455
-
456
- print(prompt)
457
- response = conversation.invoke({'question': user_input})
458
- response = response['text']
459
- response = response.replace('\\', '')
460
- print(response)
461
-
462
- # Pattern to extract SQL query from the response
463
- patterns = [
464
- r"""```json\n{\s*"Query":\s*"(.*?)"}\n```""",
465
- r"""```json\n{\s*"Query":\s*"(.*?)"}\s*```""",
466
- r"""```json\s*{\s*"Query":\s*"(.*?)"\s*}\s*```""",
467
- r"""```json\s*{\s*"Query":\s*"(.*?)"\s*}```""",
468
- r"""```json\n{\n\s*"Query":\s*"(.*?)"\n}\n```""",
469
- r"""```json\s*\{\s*['"]Query['"]:\s*['"](.*?)['"]\s*\}\s*```""",
470
- r"""```json\s*\{\s*['"]Query['"]\s*:\s*['"](.*?)['"]\s*\}\s*```""",
471
- r"""```json\s*{\s*"Query"\s*:\s*"(.*?)"\s*}\s*```""",
472
- r"""```json\s*{\s*"Query"\s*:\s*\"(.*?)\"\s*}\s*```""",
473
- r"""\"Query\"\s*:\s*\"(.*?)\"""",
474
- r"""```json\s*\{\s*\"Query\":\s*\"(.*?)\"\s*\}\s*```""",
475
- r"""['"]Query['"]\s*:\s*['"](.*?)['"]""",
476
- r"""```json\s*{\s*"Query":\s*"(.*?)"}\s*```""",
477
- ]
478
- sql_query = None
479
- for pattern in patterns:
480
- matches = re.findall(pattern, response, re.DOTALL)
481
- if matches:
482
- sql_query = matches[0]
483
-
484
- print("jiji1")
485
- if sql_query:
486
- # Fetch data from database
487
- results = fetch_data_from_db(sql_query)
488
- print(results)
489
- column_names1 = extract_column_names(sql_query)
490
- column_names=column_names1
491
- print("jiji",column_names)
492
-
493
- else:
494
- column_names=[]
495
- results=[]
496
-
497
- pattern = r'```.*?```(.*)'
498
- match = re.search(pattern, response, re.DOTALL)
499
- print("GG",match)
500
- if match:
501
- response = match.group(1).strip()
502
- print("GG1",response)
503
-
504
- print(type(user_input_entities))
505
- print(type(response))
506
- print(type(sql_query))
507
- print(type(results))
508
- print("Process completed.")
509
- return user_input_entities, response, sql_query, results
510
-
511
- except Exception as e:
512
- print(f"Error generating SQL query: {e}")
513
-
514
-
515
-
516
-
517
- def fetch_data_from_db(query):
518
- try:
519
- conn = psycopg2.connect(
520
- dbname='postgres',
521
- user='shivanshu',
522
- password='root',
523
- host='34.170.181.105',
524
- port='5432'
525
- )
526
- cursor = conn.cursor()
527
- cursor.execute(query)
528
- results = cursor.fetchall()
529
- cursor.close()
530
- conn.close()
531
- print(results)
532
- return results
533
- except Exception as e:
534
- print(f"Error fetching data from database: {e}")
535
- return []
536
-
537
-
538
-
539
-
540
- def process_gradio(query, model_type):
541
- try:
542
- # Load the CSV file
543
- csv_loader = CSVLoader(file_path='des.csv')
544
- documents = csv_loader.load()
545
-
546
- # Define the vector DB paths
547
- vector_db_path_gemini = "faiss_index_gemini"
548
- vector_db_path_openai = "faiss_index_openai"
549
-
550
- # Check if the directory paths exist, if not, create them
551
- os.makedirs(vector_db_path_gemini, exist_ok=True)
552
- os.makedirs(vector_db_path_openai, exist_ok=True)
553
-
554
- # Determine the model to use
555
- if model_type == 'gemini':
556
- vector_db_path = vector_db_path_gemini
557
- embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004", api_key=GOOGLE_API_KEY)
558
- else:
559
- vector_db_path = vector_db_path_openai
560
- embeddings = OpenAIEmbeddings()
561
-
562
- # Check if the FAISS index already exists
563
- index_file_path = os.path.join(vector_db_path, "index")
564
- if os.path.exists(index_file_path):
565
- vector_store = FAISS.load_local(vector_db_path, embeddings, allow_dangerous_deserialization=True)
566
- else:
567
- texts = [doc.page_content for doc in documents]
568
- vector_store = FAISS.from_texts(texts, embeddings)
569
- vector_store.save_local(vector_db_path)
570
-
571
-
572
- og_table_schema = fetch_table_schema()
573
- new_table_schema = {}
574
-
575
-
576
- # Generate SQL query
577
- if model_type == 'gemini':
578
- user_input_entities, response, sql_query, results = generate_sql_query_gemini(query, new_table_schema, vector_store, og_table_schema)
579
- else:
580
- user_input_entities, response, sql_query, results = generate_sql_query_openai(query, new_table_schema, vector_store, og_table_schema)
581
-
582
-
583
- return user_input_entities or {}, response or "", sql_query or "", results or {}
584
-
585
-
586
-
587
-
588
- except Exception as e:
589
- # Ensure the function still returns four values, even in case of an error
590
- return {}, str(e), "", []
591
-
592
-
593
-
594
- with gr.Blocks() as demo:
595
- with gr.Row():
596
- with gr.Column(scale=1):
597
- # Add the image in the left corner
598
- # gr.Image(value=image_path, show_label=False, height=45, width=45)
599
- # gr.HTML(f'<img src="{image_link}" alt="Logo" height="50" width="50">')
600
- gr.Image(value=image_path, show_label=False, height=50, width=50)
601
- # gr.HTML(f'<img src="{image_path}" alt="Logo" height="50" width="100" style="display: block; margin-left: auto; margin-right: auto;">')
602
-
603
- gr.Markdown(
604
- """
605
- # Natural Language Query for Network Data
606
- <p style="font-size: 16px;">
607
- This app generates SQL queries from user queries using Google Gemini or OpenAI models.
608
- </p>
609
- <p style="font-size: 16px;">
610
- Click here to view the data:
611
- <a href="https://docs.google.com/spreadsheets/d/1uYeHbqzz1NKL8e4tlzbIk8K5qgLfY_To-pjRjOGjWQg/edit?usp=sharing" target="_blank" style="color: #0066cc; text-decoration: none;">
612
- View Spreadsheet
613
- </a>
614
- </p>
615
- """
616
- )
617
-
618
- with gr.Row():
619
- with gr.Column(scale=1):
620
- query_input = gr.Textbox(label="Enter your query")
621
- model_input = gr.Radio(choices=["gemini", "openai"], label="Model Type", value="gemini")
622
- temperature_slider = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.7, label="Temperature", interactive=True)
623
- submit_button = gr.Button("Submit")
624
-
625
- gr.Examples(
626
- examples=[
627
- ["What is the average latency for each network engineer?", "openai"],
628
- ["Can you tell me what is the average RRC setup attempts, how is it distributed across time of the day? Can you also show me this distribution both for weekdays as well as weekends. Show me the data sorted by time of the day.", "openai"],
629
- ["What is the average PRB utilization for each Network engineer, and give me this average both for the weekends as well for the weekdays. Show this for each network engineer averaged across four time periods, 12 midnight - 6am , 6am -12 noon , 12 noon - 6pm , 6pm - 12 midnight. Finally show me this data sorted by network engineer as well time periods.", "openai"]
630
- ],
631
- inputs=[query_input, model_input]
632
- )
633
-
634
- with gr.Column(scale=2):
635
- output_results = gr.DataFrame(label="Query Results")
636
- output_sql_query = gr.Textbox(label="Generated SQL Query")
637
- output_response = gr.Textbox(label="Similar Entities")
638
- # output_user_input_schema = gr.DataFrame(label="User Input Schema")
639
- output_user_input_schema = gr.JSON(label="Retrived KPIs")
640
-
641
-
642
-
643
- # Define the button click action
644
- def update_dataframe(query_input, model_input):
645
- global column_names
646
-
647
- # Process the query and model input
648
- user_input_entities, response, sql_query, results = process_gradio(query_input, model_input)
649
-
650
- # Check if column_names is not empty
651
- if column_names:
652
- output_results.headers = column_names # Set headers with dynamic column names
653
- else:
654
- output_results.headers = [] # Set headers to an empty list for an empty DataFrame
655
-
656
- # Return the processed results
657
- return user_input_entities, response, sql_query, results
658
-
659
-
660
-
661
-
662
- def update_dataframe(query_input, model_input):
663
- global column_names
664
-
665
- # Process the query and model input
666
- user_input_entities, response, sql_query, results = process_gradio(query_input, model_input)
667
-
668
- # Check if column_names is not empty
669
- if column_names:
670
- output_results.headers = column_names # Set headers with dynamic column names
671
- else:
672
- output_results.headers = [] # Set headers to an empty list for an empty DataFrame
673
-
674
- # Return the processed results
675
- return user_input_entities, response, sql_query, results
676
-
677
-
678
- submit_button.click(
679
- fn=update_dataframe,
680
- inputs=[query_input, model_input],
681
- outputs=[output_user_input_schema, output_response, output_sql_query, output_results]
682
- )
683
-
684
- # Launch the app
685
  demo.launch(debug=True)
 
1
+ import os
2
+ import re
3
+ import json
4
+ import openai
5
+ import psycopg2
6
+ import google.generativeai as genai
7
+ import gradio as gr
8
+ from langchain_community.document_loaders.csv_loader import CSVLoader
9
+ from langchain.vectorstores import FAISS
10
+ from langchain.embeddings.base import Embeddings
11
+ from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
12
+ from langchain_core.prompts import ChatPromptTemplate
13
+ from langchain.output_parsers.json import SimpleJsonOutputParser
14
+ from langchain.memory import ConversationBufferMemory
15
+ from langchain.chains import LLMChain
16
+ from langchain_core.prompts import (
17
+ ChatPromptTemplate,
18
+ MessagesPlaceholder,
19
+ SystemMessagePromptTemplate,
20
+ HumanMessagePromptTemplate,
21
+ )
22
+ from langchain import OpenAI
23
+
24
+
25
+
26
+
27
+ os.environ['GOOGLE_API_KEY'] = 'AIzaSyDLwJAr5iXL2Weaw1XphFNSeijytqOSbDg'
28
+ os.environ['OPENAI_API_KEY'] = 'sk-proj-Kh4UIWkfDxSGppQpooxXT3BlbkFJATohXqhpkJE6MqliIkmU'
29
+ # Set your API keys
30
+
31
+ OPENAI_API_KEY = 'sk-proj-Kh4UIWkfDxSGppQpooxXT3BlbkFJATohXqhpkJE6MqliIkmU'
32
+ GOOGLE_API_KEY = 'AIzaSyDLwJAr5iXL2Weaw1XphFNSeijytqOSbDg'
33
+ openai.api_key = OPENAI_API_KEY
34
+ genai.configure(api_key=GOOGLE_API_KEY)
35
+
36
+
37
+
38
+
39
+ class OpenAIEmbeddings(Embeddings):
40
+ def embed_documents(self, texts):
41
+ response = openai.Embedding.create(
42
+ model="text-embedding-ada-002",
43
+ api_key=OPENAI_API_KEY,
44
+ input=texts
45
+ )
46
+ embeddings = [e["embedding"] for e in response["data"]]
47
+ return embeddings
48
+
49
+
50
+
51
+
52
+ def embed_query(self, text):
53
+ response = openai.Embedding.create(
54
+ model="text-embedding-ada-002",
55
+ api_key=OPENAI_API_KEY,
56
+ input=[text]
57
+ )
58
+ embedding = response["data"][0]["embedding"]
59
+ return embedding
60
+
61
+
62
+
63
+
64
+ class GeminiEmbeddings(GoogleGenerativeAIEmbeddings):
65
+ def __init__(self, api_key):
66
+ super().__init__(model="models/text-embedding-004", google_api_key=GOOGLE_API_KEY)
67
+
68
+
69
+
70
+
71
+ def extract_entities_openai(query):
72
+ prompt = f"""
73
+ Find the entities from the query given below enclosed in triple quotes. Make sure to ONLY return response in JSON format, with the key as "KPI" and extracted entities as list. Example Output JSON:
74
+ {{
75
+ "KPI": ["Extracted Entity 1", "Extracted Entity 2", ....]
76
+ }}
77
+
78
+
79
+ Query begins here:
80
+ \"\"\"{query}\"\"\"
81
+ """
82
+ response = openai.ChatCompletion.create(
83
+ model="gpt-4",
84
+ messages=[
85
+ {"role": "user", "content": prompt}
86
+ ],
87
+ temperature=0
88
+ )
89
+ return response['choices'][0]['message']['content'].strip()
90
+
91
+
92
+
93
+ def extract_entities_gemini(query):
94
+ try:
95
+ llm_content_summary = ChatGoogleGenerativeAI(
96
+ model="gemini-1.5-pro",
97
+ temperature=0,
98
+ max_tokens=250,
99
+ timeout=None,
100
+ max_retries=2,
101
+ google_api_key=GOOGLE_API_KEY,
102
+ )
103
+
104
+
105
+
106
+
107
+ prompt = ChatPromptTemplate.from_messages(
108
+ [
109
+ (
110
+ "system", """Use the instructions below to generate responses based on user inputs. Return the answer as a JSON object.""",
111
+ ),
112
+ ("user", f"""Find the entities from the query given below enclosed in triple quotes. Make sure to ONLY return response in JSON format, with the key as "KPI" and extracted entities as list. Example Output JSON:
113
+ "KPI": ["Extracted Entity 1", "Extracted Entity 2", ....]
114
+ Query begins here:
115
+ \"\"\"{query}\"\"\"
116
+ """),
117
+ ]
118
+ )
119
+
120
+
121
+
122
+
123
+ json_parser = SimpleJsonOutputParser()
124
+ chain = prompt | llm_content_summary | json_parser
125
+ response = chain.invoke({"input": query})
126
+
127
+ if isinstance(response, dict):
128
+ response = json.dumps(response)
129
+
130
+ return response
131
+ except Exception as e:
132
+ print(f"Error generating content summary: {e}")
133
+ return None
134
+
135
+
136
+
137
+
138
+ def fetch_table_schema():
139
+ try:
140
+ conn = psycopg2.connect(
141
+ dbname='postgres',
142
+ user='shivanshu',
143
+ password='root',
144
+ host='34.170.181.105',
145
+ port='5432'
146
+ )
147
+ cursor = conn.cursor()
148
+ table_name = 'network'
149
+ query = f"""
150
+ SELECT
151
+ column_name,
152
+ data_type,
153
+ character_maximum_length,
154
+ is_nullable
155
+ FROM
156
+ information_schema.columns
157
+ WHERE
158
+ table_name = '{table_name}';
159
+ """
160
+ cursor.execute(query)
161
+ rows = cursor.fetchall()
162
+ cursor.close()
163
+ schema_dict = {
164
+ row[0]: {
165
+ 'data_type': row[1],
166
+ 'character_maximum_length': row[2],
167
+ 'is_nullable': row[3]
168
+ }
169
+ for row in rows
170
+ }
171
+ return schema_dict
172
+ except Exception as e:
173
+ print(f"Error fetching table schema: {e}")
174
+ return {}
175
+
176
+
177
+
178
+
179
+ column_names=[]
180
+
181
+ def extract_column_names(sql_query):
182
+ # Use a regular expression to extract the part of the query between SELECT and FROM
183
+ pattern = r'SELECT\s+(.*?)\s+FROM'
184
+ match = re.search(pattern, sql_query, re.IGNORECASE | re.DOTALL)
185
+ if not match:
186
+ return []
187
+
188
+
189
+ columns_part = match.group(1).strip()
190
+
191
+ # Split columns based on commas that are not within parentheses
192
+ column_names = re.split(r',\s*(?![^()]*\))', columns_part)
193
+
194
+ # Process each column to handle aliases and functions
195
+ clean_column_names = []
196
+ for col in column_names:
197
+ # Remove any function wrappers (e.g., TRIM, COUNT, etc.)
198
+ col = re.sub(r'\b\w+\((.*?)\)', r'\1', col)
199
+
200
+ # Remove any aliases (i.e., words following 'AS')
201
+ col = re.split(r'\s+AS\s+', col, flags=re.IGNORECASE)[-1]
202
+
203
+ # Strip any remaining whitespace or backticks/quotes
204
+ col = col.strip(' `"[]')
205
+ clean_column_names.append(col)
206
+ return clean_column_names
207
+
208
+
209
+ def process_sublist(sublist,similarity_threshold):
210
+ processed_list = sublist[0:3]
211
+ for index in range(3, len(sublist)):
212
+ if sublist[index]['similarity'] >= similarity_threshold:
213
+ processed_list.append(sublist[index])
214
+ else:
215
+ break
216
+ return processed_list
217
+
218
+
219
+ from langchain_community.chat_models import ChatOpenAI
220
+ # Initialize the OpenAI model and memory
221
+ openai_model = ChatOpenAI(model='gpt-4', temperature=0, api_key=OPENAI_API_KEY)
222
+ openai_memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
223
+
224
+ def generate_sql_query_openai(description, table_schema, vector_store, og_table_schema):
225
+ global openai_model
226
+ global openai_memory
227
+ global column_names
228
+ try:
229
+ user_input = description
230
+ print(user_input)
231
+ entities = extract_entities_openai(user_input)
232
+ entities_obj = json.loads(entities)
233
+ kpis = entities_obj['KPI']
234
+
235
+ # Fetch similar documents
236
+ final_results = []
237
+ similar_kpis = []
238
+ for kpi in kpis:
239
+ docs = vector_store.similarity_search_with_score(kpi, k=6)
240
+ results = []
241
+ count = 1
242
+ for doc, distance in docs:
243
+ name_desc = doc.page_content.split("\nDescription: ")
244
+ name = name_desc[0].replace("Name: ", "")
245
+ description = name_desc[1] if len(name_desc) > 1 else "No description available."
246
+ similarity_score = round((1 - distance) * 100, 2) # Convert distance to similarity score in percent
247
+ results.append({"name": name, "description": description, "similarity": similarity_score, "Index": count})
248
+ similar_kpis.append({"name": name, "similarity": similarity_score})
249
+ count += 1 # Increment the count for each result
250
+ final_results.append(results)
251
+
252
+ # Process results
253
+ similarity_threshold = 75.0
254
+
255
+ processed_sublists = [process_sublist(sublist,similarity_threshold) for sublist in final_results]
256
+ flattened_results = [item for sublist in processed_sublists for item in sublist]
257
+
258
+ user_input_entities = [item['name'] for item in flattened_results]
259
+ print("BYE1",user_input_entities)
260
+
261
+ try:
262
+ # Strip whitespace and ensure case matches for comparison
263
+ user_input_entities = [key.strip() for key in user_input_entities]
264
+ og_table_schema_keys = [key.strip() for key in og_table_schema.keys()]
265
+
266
+ # Check and create user_input_table_schema
267
+ table_schema = {key: og_table_schema[key] for key in user_input_entities if key in og_table_schema_keys}
268
+ print("BYE3",table_schema)
269
+ except Exception as e:
270
+ print(f"An error occurred: {e}")
271
+
272
+
273
+ table_schema = json.dumps(table_schema)
274
+ table_schema = table_schema.replace('{', '[')
275
+ table_schema = table_schema.replace('}', ']')
276
+ print("GG123")
277
+ system_message_template1 = f"""Generate the PostgreSQL query for the following task: {description}.
278
+ The connection with the database is already setup and the table is called network.
279
+ Enclose column names in double quotes ("), but do not use escape characters (e.g., "\").
280
+ Do not assign aliases to the columns.
281
+ Do not calculate new columns, unless specifically called to.
282
+ Return only the PostgreSQL query, nothing else.
283
+ The list of all the columns is as follows: {table_schema}
284
+ Make sure the response should strictly follow JSON format. The key should be "Query" and the value should be the Postgresql query.
285
+ Example Output JSON:
286
+ ["Query": PostgreSQL Executable query]"""
287
+
288
+ system_message_template = system_message_template1
289
+ print(system_message_template)
290
+ # Create the ChatPromptTemplate
291
+ print("GG1234")
292
+ prompt = ChatPromptTemplate(
293
+ messages=[
294
+ SystemMessagePromptTemplate.from_template(system_message_template),
295
+ # Placeholder for chat history
296
+ MessagesPlaceholder(variable_name="chat_history"),
297
+ # User's question will be dynamically inserted
298
+ HumanMessagePromptTemplate.from_template("""
299
+ {question}
300
+ """)
301
+ ]
302
+ )
303
+
304
+
305
+
306
+ print("GG12345")
307
+ conversation = LLMChain(
308
+ llm=openai_model,
309
+ prompt=prompt,
310
+ verbose=True,
311
+ memory=openai_memory
312
+ )
313
+
314
+
315
+
316
+
317
+ print(prompt)
318
+ response = conversation.invoke({'question': user_input})
319
+ response = response['text']
320
+ response = response.replace('\\', '')
321
+ print(response)
322
+ print("************************************************")
323
+ print(type(response))
324
+
325
+ # Regular expression pattern to extract the query string
326
+ pattern = r'{"Query":\s*"(.*?)"\s*}'
327
+ # Extract the content
328
+
329
+ sql_query = None
330
+ match = re.search(pattern, response)
331
+ if match:
332
+ sql_query = match.group(1)
333
+ print(sql_query)
334
+
335
+ print("jiji1")
336
+ if sql_query:
337
+ # Fetch data from database
338
+ results = fetch_data_from_db(sql_query)
339
+ print(results)
340
+ column_names1 = extract_column_names(sql_query)
341
+ column_names=column_names1
342
+ print("jiji",column_names)
343
+
344
+ else:
345
+ column_names=[]
346
+ results=[]
347
+
348
+ pattern = r'```.*?```(.*)'
349
+ match = re.search(pattern, response, re.DOTALL)
350
+ print("GG",match)
351
+ if match:
352
+ response = match.group(1).strip()
353
+ print("GG1",response)
354
+
355
+ print(type(user_input_entities))
356
+ print(type(response))
357
+ print(type(sql_query))
358
+ print(type(results))
359
+ print("Process completed.")
360
+ return user_input_entities, response, sql_query, results
361
+
362
+ except Exception as e:
363
+ print(f"Error generating SQL query: {e}")
364
+
365
+
366
+
367
+ gemini_model = ChatGoogleGenerativeAI(model='gemini-1.5-pro-001',temperature=0,google_api_key = GOOGLE_API_KEY)
368
+ gemini_memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
369
+
370
+ def generate_sql_query_gemini(description, table_schema,vector_store,og_table_schema):
371
+ global gemini_model
372
+ global gemini_memory
373
+ global column_names
374
+ try:
375
+ user_input = description
376
+ print(user_input)
377
+ entities = extract_entities_gemini(user_input)
378
+ entities_obj = json.loads(entities)
379
+ kpis = entities_obj['KPI']
380
+
381
+ # Fetch similar documents
382
+ final_results = []
383
+ similar_kpis = []
384
+ for kpi in kpis:
385
+ docs = vector_store.similarity_search_with_score(kpi, k=6)
386
+ results = []
387
+ count = 1
388
+ for doc, distance in docs:
389
+ name_desc = doc.page_content.split("\nDescription: ")
390
+ name = name_desc[0].replace("Name: ", "")
391
+ description = name_desc[1] if len(name_desc) > 1 else "No description available."
392
+ similarity_score = round((1 - distance) * 100, 2) # Convert distance to similarity score in percent
393
+ results.append({"name": name, "description": description, "similarity": similarity_score, "Index": count})
394
+ similar_kpis.append({"name": name, "similarity": similarity_score})
395
+ count += 1 # Increment the count for each result
396
+ final_results.append(results)
397
+
398
+ # Process results
399
+ similarity_threshold = 75.0
400
+
401
+ processed_sublists = [process_sublist(sublist,similarity_threshold) for sublist in final_results]
402
+ flattened_results = [item for sublist in processed_sublists for item in sublist]
403
+
404
+ user_input_entities = [item['name'] for item in flattened_results]
405
+ print("BYE1",user_input_entities)
406
+
407
+ try:
408
+ # Strip whitespace and ensure case matches for comparison
409
+ user_input_entities = [key.strip() for key in user_input_entities]
410
+ og_table_schema_keys = [key.strip() for key in og_table_schema.keys()]
411
+
412
+ # Check and create user_input_table_schema
413
+ table_schema = {key: og_table_schema[key] for key in user_input_entities if key in og_table_schema_keys}
414
+ print("BYE3",table_schema)
415
+ except Exception as e:
416
+ print(f"An error occurred: {e}")
417
+
418
+
419
+ table_schema = json.dumps(table_schema)
420
+ table_schema = table_schema.replace('{', '[')
421
+ table_schema = table_schema.replace('}', ']')
422
+ system_message_template1 = f"""Generate the PostgreSQL query for the following task: {description}.
423
+ The connection with the database is already setup and the table is called network.
424
+ Enclose column names in double quotes ("), but do not use escape characters (e.g., "\").
425
+ Do not assign aliases to the columns.
426
+ Do not calculate new columns, unless specifically called to.
427
+ Return only the PostgreSQL query, nothing else.
428
+ The list of all the columns is as follows: {table_schema}
429
+ Make sure the response should strictly follow JSON format. The key should be "Query" and the value should be the Postgresql query.
430
+ Example Output JSON:
431
+ ["Query": PostgreSQL Executable query]"""
432
+
433
+ system_message_template = system_message_template1
434
+ print(system_message_template)
435
+ # Create the ChatPromptTemplate
436
+ prompt = ChatPromptTemplate(
437
+ messages=[
438
+ SystemMessagePromptTemplate.from_template(system_message_template),
439
+ # Placeholder for chat history
440
+ MessagesPlaceholder(variable_name="chat_history"),
441
+ # User's question will be dynamically inserted
442
+ HumanMessagePromptTemplate.from_template("""
443
+ {question}
444
+ """)
445
+ ]
446
+ )
447
+
448
+ conversation = LLMChain(
449
+ llm=gemini_model,
450
+ prompt=prompt,
451
+ verbose=True,
452
+ memory=gemini_memory
453
+ )
454
+
455
+
456
+ print(prompt)
457
+ response = conversation.invoke({'question': user_input})
458
+ response = response['text']
459
+ response = response.replace('\\', '')
460
+ print(response)
461
+
462
+ # Pattern to extract SQL query from the response
463
+ patterns = [
464
+ r"""```json\n{\s*"Query":\s*"(.*?)"}\n```""",
465
+ r"""```json\n{\s*"Query":\s*"(.*?)"}\s*```""",
466
+ r"""```json\s*{\s*"Query":\s*"(.*?)"\s*}\s*```""",
467
+ r"""```json\s*{\s*"Query":\s*"(.*?)"\s*}```""",
468
+ r"""```json\n{\n\s*"Query":\s*"(.*?)"\n}\n```""",
469
+ r"""```json\s*\{\s*['"]Query['"]:\s*['"](.*?)['"]\s*\}\s*```""",
470
+ r"""```json\s*\{\s*['"]Query['"]\s*:\s*['"](.*?)['"]\s*\}\s*```""",
471
+ r"""```json\s*{\s*"Query"\s*:\s*"(.*?)"\s*}\s*```""",
472
+ r"""```json\s*{\s*"Query"\s*:\s*\"(.*?)\"\s*}\s*```""",
473
+ r"""\"Query\"\s*:\s*\"(.*?)\"""",
474
+ r"""```json\s*\{\s*\"Query\":\s*\"(.*?)\"\s*\}\s*```""",
475
+ r"""['"]Query['"]\s*:\s*['"](.*?)['"]""",
476
+ r"""```json\s*{\s*"Query":\s*"(.*?)"}\s*```""",
477
+ ]
478
+ sql_query = None
479
+ for pattern in patterns:
480
+ matches = re.findall(pattern, response, re.DOTALL)
481
+ if matches:
482
+ sql_query = matches[0]
483
+
484
+ print("jiji1")
485
+ if sql_query:
486
+ # Fetch data from database
487
+ results = fetch_data_from_db(sql_query)
488
+ print(results)
489
+ column_names1 = extract_column_names(sql_query)
490
+ column_names=column_names1
491
+ print("jiji",column_names)
492
+
493
+ else:
494
+ column_names=[]
495
+ results=[]
496
+
497
+ pattern = r'```.*?```(.*)'
498
+ match = re.search(pattern, response, re.DOTALL)
499
+ print("GG",match)
500
+ if match:
501
+ response = match.group(1).strip()
502
+ print("GG1",response)
503
+
504
+ print(type(user_input_entities))
505
+ print(type(response))
506
+ print(type(sql_query))
507
+ print(type(results))
508
+ print("Process completed.")
509
+ return user_input_entities, response, sql_query, results
510
+
511
+ except Exception as e:
512
+ print(f"Error generating SQL query: {e}")
513
+
514
+
515
+
516
+
517
+ def fetch_data_from_db(query):
518
+ try:
519
+ conn = psycopg2.connect(
520
+ dbname='postgres',
521
+ user='shivanshu',
522
+ password='root',
523
+ host='34.170.181.105',
524
+ port='5432'
525
+ )
526
+ cursor = conn.cursor()
527
+ cursor.execute(query)
528
+ results = cursor.fetchall()
529
+ cursor.close()
530
+ conn.close()
531
+ print(results)
532
+ return results
533
+ except Exception as e:
534
+ print(f"Error fetching data from database: {e}")
535
+ return []
536
+
537
+
538
+
539
+
540
+ def process_gradio(query, model_type):
541
+ try:
542
+ # Load the CSV file
543
+ csv_loader = CSVLoader(file_path='des.csv')
544
+ documents = csv_loader.load()
545
+
546
+ # Define the vector DB paths
547
+ vector_db_path_gemini = "faiss_index_gemini"
548
+ vector_db_path_openai = "faiss_index_openai"
549
+
550
+ # Check if the directory paths exist, if not, create them
551
+ os.makedirs(vector_db_path_gemini, exist_ok=True)
552
+ os.makedirs(vector_db_path_openai, exist_ok=True)
553
+
554
+ # Determine the model to use
555
+ if model_type == 'gemini':
556
+ vector_db_path = vector_db_path_gemini
557
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/text-embedding-004", api_key=GOOGLE_API_KEY)
558
+ else:
559
+ vector_db_path = vector_db_path_openai
560
+ embeddings = OpenAIEmbeddings()
561
+
562
+ # Check if the FAISS index already exists
563
+ index_file_path = os.path.join(vector_db_path, "index")
564
+ if os.path.exists(index_file_path):
565
+ vector_store = FAISS.load_local(vector_db_path, embeddings, allow_dangerous_deserialization=True)
566
+ else:
567
+ texts = [doc.page_content for doc in documents]
568
+ vector_store = FAISS.from_texts(texts, embeddings)
569
+ vector_store.save_local(vector_db_path)
570
+
571
+
572
+ og_table_schema = fetch_table_schema()
573
+ new_table_schema = {}
574
+
575
+
576
+ # Generate SQL query
577
+ if model_type == 'gemini':
578
+ user_input_entities, response, sql_query, results = generate_sql_query_gemini(query, new_table_schema, vector_store, og_table_schema)
579
+ else:
580
+ user_input_entities, response, sql_query, results = generate_sql_query_openai(query, new_table_schema, vector_store, og_table_schema)
581
+
582
+
583
+ return user_input_entities or {}, response or "", sql_query or "", results or {}
584
+
585
+
586
+
587
+
588
+ except Exception as e:
589
+ # Ensure the function still returns four values, even in case of an error
590
+ return {}, str(e), "", []
591
+
592
+ image_path = r"C:\Users\shivanshu.t\Downloads\incedo-logo.png"
593
+
594
+ with gr.Blocks() as demo:
595
+ with gr.Row():
596
+ with gr.Column(scale=1):
597
+ # Add the image in the left corner
598
+ # gr.Image(value=image_path, show_label=False, height=45, width=45)
599
+ # gr.HTML(f'<img src="{image_link}" alt="Logo" height="50" width="50">')
600
+ gr.Image(value=image_path, show_label=False, height=50, width=50)
601
+ # gr.HTML(f'<img src="{image_path}" alt="Logo" height="50" width="100" style="display: block; margin-left: auto; margin-right: auto;">')
602
+
603
+ gr.Markdown(
604
+ """
605
+ # Natural Language Query for Network Data
606
+ <p style="font-size: 16px;">
607
+ This app generates SQL queries from user queries using Google Gemini or OpenAI models.
608
+ </p>
609
+ <p style="font-size: 16px;">
610
+ Click here to view the data:
611
+ <a href="https://docs.google.com/spreadsheets/d/1uYeHbqzz1NKL8e4tlzbIk8K5qgLfY_To-pjRjOGjWQg/edit?usp=sharing" target="_blank" style="color: #0066cc; text-decoration: none;">
612
+ View Spreadsheet
613
+ </a>
614
+ </p>
615
+ """
616
+ )
617
+
618
+ with gr.Row():
619
+ with gr.Column(scale=1):
620
+ query_input = gr.Textbox(label="Enter your query")
621
+ model_input = gr.Radio(choices=["gemini", "openai"], label="Model Type", value="gemini")
622
+ temperature_slider = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.7, label="Temperature", interactive=True)
623
+ submit_button = gr.Button("Submit")
624
+
625
+ gr.Examples(
626
+ examples=[
627
+ ["What is the average latency for each network engineer?", "openai"],
628
+ ["Can you tell me what is the average RRC setup attempts, how is it distributed across time of the day? Can you also show me this distribution both for weekdays as well as weekends. Show me the data sorted by time of the day.", "openai"],
629
+ ["What is the average PRB utilization for each Network engineer, and give me this average both for the weekends as well for the weekdays. Show this for each network engineer averaged across four time periods, 12 midnight - 6am , 6am -12 noon , 12 noon - 6pm , 6pm - 12 midnight. Finally show me this data sorted by network engineer as well time periods.", "openai"]
630
+ ],
631
+ inputs=[query_input, model_input]
632
+ )
633
+
634
+ with gr.Column(scale=2):
635
+ output_results = gr.DataFrame(label="Query Results")
636
+ output_sql_query = gr.Textbox(label="Generated SQL Query")
637
+ output_response = gr.Textbox(label="Similar Entities")
638
+ # output_user_input_schema = gr.DataFrame(label="User Input Schema")
639
+ output_user_input_schema = gr.JSON(label="Retrived KPIs")
640
+
641
+
642
+
643
+ # Define the button click action
644
+ def update_dataframe(query_input, model_input):
645
+ global column_names
646
+
647
+ # Process the query and model input
648
+ user_input_entities, response, sql_query, results = process_gradio(query_input, model_input)
649
+
650
+ # Check if column_names is not empty
651
+ if column_names:
652
+ output_results.headers = column_names # Set headers with dynamic column names
653
+ else:
654
+ output_results.headers = [] # Set headers to an empty list for an empty DataFrame
655
+
656
+ # Return the processed results
657
+ return user_input_entities, response, sql_query, results
658
+
659
+
660
+
661
+
662
+ def update_dataframe(query_input, model_input):
663
+ global column_names
664
+
665
+ # Process the query and model input
666
+ user_input_entities, response, sql_query, results = process_gradio(query_input, model_input)
667
+
668
+ # Check if column_names is not empty
669
+ if column_names:
670
+ output_results.headers = column_names # Set headers with dynamic column names
671
+ else:
672
+ output_results.headers = [] # Set headers to an empty list for an empty DataFrame
673
+
674
+ # Return the processed results
675
+ return user_input_entities, response, sql_query, results
676
+
677
+
678
+ submit_button.click(
679
+ fn=update_dataframe,
680
+ inputs=[query_input, model_input],
681
+ outputs=[output_user_input_schema, output_response, output_sql_query, output_results]
682
+ )
683
+
684
+ # Launch the app
685
  demo.launch(debug=True)