Repository navigation
Expand file tree
/
Copy pathsql_engine.py
More file actions
99 lines (80 loc) · 2.96 KB
/
Copy pathsql_engine.py
File metadata and controls
99 lines (80 loc) · 2.96 KB
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
import os
import re
import pandas as pd
from urllib.parse import quote_plus
from dotenv import load_dotenv
from langchain_community.utilities import SQLDatabase
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_google_genai import ChatGoogleGenerativeAI
load_dotenv()
def get_db_connection():
"""Initializes and returns the SQL database connection."""
host = os.getenv("DB_HOST")
port = os.getenv("DB_PORT")
username = os.getenv("DB_USER")
password = quote_plus(os.getenv("DB_PASSWORD", ""))
database_schema = os.getenv("DB_NAME")
mysql_uri = f"mysql+pymysql://{username}:{password}@{host}:{port}/{database_schema}"
return SQLDatabase.from_uri(mysql_uri, sample_rows_in_table_info=2)
def get_sql_chain(db):
"""Creates the LangChain SQL generation chain."""
template = """Based on the table schema below, write a SQL query that would answer the user's question:
Remember : Only provide me the sql query dont include anything else.
Provide me sql query in a single line dont add line breaks.
Table Schema:
{schema}
Question: {question}
SQL Query:
"""
prompt = ChatPromptTemplate.from_template(template)
llm = ChatGoogleGenerativeAI(
model="gemini-2.5-flash",
api_key=os.getenv("GOOGLE_API_KEY")
)
def get_schema(_):
return db.get_table_info()
sql_chain = (
RunnablePassthrough.assign(schema=get_schema)
| prompt
| llm.bind(stop=["\nSQLResult:"])
| StrOutputParser()
)
return sql_chain
def run_text_to_sql(question, db, sql_chain):
"""Processes the natural language query, extracts SQL, and executes it via Pandas."""
raw_response = sql_chain.invoke({"question": question})
# Clean output using your regex pattern
match = re.search(r"```sql\s*(.*?)\s*```", raw_response, re.DOTALL | re.IGNORECASE)
query = match.group(1).strip() if match else raw_response.strip()
try:
# ADVANCEMENT: Read the SQL query directly into a Pandas DataFrame
df_result = pd.read_sql_query(query, db._engine)
return query, df_result, None
except Exception as e:
return query, None, str(e)
def generate_summary(question, result_df):
"""
Generates an AI summary of the SQL output.
"""
if result_df is None or result_df.empty:
return "No data was returned for this query."
llm = ChatGoogleGenerativeAI(
model="gemini-2.5-flash",
api_key=os.getenv("GOOGLE_API_KEY")
)
prompt = f"""
You are an expert business analyst.
User Question:
{question}
Query Result:
{result_df.head(20).to_string(index=False)}
Write a concise summary (5-7 sentences).
Rules:
- Do not mention SQL.
- Explain the important insight.
- Mention important trends if visible.
- Keep the language simple and professional.
"""
return llm.invoke(prompt).content