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