-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_langC.py
More file actions
199 lines (161 loc) · 4.91 KB
/
app_langC.py
File metadata and controls
199 lines (161 loc) · 4.91 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
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
import os
import streamlit as st
import pandas as pd
from dotenv import load_dotenv
from sqlalchemy import create_engine, text
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import PromptTemplate
# =====================
# ENV
# =====================
load_dotenv()
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
DB_URL = os.getenv("DB_URL")
# =====================
# Streamlit Config
# =====================
st.set_page_config(page_title="Postgres SQL Chatbot", layout="wide")
st.title("💬 Chat with PostgreSQL DB")
# =====================
# LLM (LangChain + Gemini)
# =====================
llm = ChatGoogleGenerativeAI(
model="gemini-2.5-flash",
temperature=0,
google_api_key=GOOGLE_API_KEY
)
# =====================
# DB Engine
# =====================
@st.cache_resource
def get_engine():
return create_engine(DB_URL)
# =====================
# Load DB Schema
# =====================
@st.cache_data
def get_schema():
engine = get_engine()
query = text("""
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY table_name, ordinal_position;
""")
schema = ""
with engine.connect() as conn:
result = conn.execute(query)
current_table = None
for table, column in result:
if table != current_table:
schema += f'\nTable: "{table}"\nColumns: '
current_table = table
schema += f'"{column}", '
return schema
schema_info = get_schema()
# =====================
# Prompt Templates
# =====================
sql_prompt = PromptTemplate(
input_variables=["schema", "question"],
template="""
You are an expert SQL generator.
Database schema:
{schema}
User request:
{question}
Rules:
- Generate a valid PostgreSQL SELECT query
- Table and column names are CASE-SENSITIVE
- Always use double quotes for table and column names
- Output ONLY the SQL query
- Do NOT return anything except SQL
SQL Query:
"""
)
answer_prompt = PromptTemplate(
input_variables=["question", "sql", "data"],
template="""
You are an expert data analyst.
User question:
{question}
SQL query:
{sql}
Query result:
{data}
Rules:
- Answer in natural language
- Be concise and clear
- If data is empty say: "No data found for the given query."
Final Answer:
"""
)
# =====================
# Functions
# =====================
def generate_sql(question):
chain = sql_prompt | llm
response = chain.invoke({
"schema": schema_info,
"question": question
})
return response.content.strip().replace("```sql", "").replace("```", "")
def run_query(sql):
engine = get_engine()
with engine.connect() as conn:
result = conn.execute(text(sql))
# Check if query returns rows
if not result.returns_rows:
return pd.DataFrame()
df = pd.DataFrame(result.fetchall(), columns=result.keys())
return df
def generate_answer(question, sql, df):
chain = answer_prompt | llm
response = chain.invoke({
"question": question,
"sql": sql,
"data": df.to_string(index=False) if not df.empty else "EMPTY"
})
return response.content.strip()
# =====================
# Relevance Check
# =====================
def is_question_relevant(question, schema):
"""
Check if the user question can be answered using the database schema.
Returns True if relevant, False otherwise.
"""
question_lower = question.lower()
# Flatten schema to a list of tables and columns
schema_items = [item.lower() for item in schema.replace('"', '').replace('\n', ' ').split()]
for word in schema_items:
if word in question_lower:
return True
return False
# =====================
# UI
# =====================
question = st.text_input("Ask a question about your database")
if st.button("Run"):
if not question:
st.warning("Please enter a question")
else:
# 1️⃣ Relevance check
if not is_question_relevant(question, schema_info):
st.error("⚠️ This question is not relevant to your database. Cannot generate SQL.")
st.stop()
# 2️⃣ Generate SQL safely
with st.spinner("Generating SQL..."):
sql = generate_sql(question)
st.subheader("🧾 Generated SQL")
st.code(sql, language="sql")
# 3️⃣ Run query
with st.spinner("Running query..."):
df = run_query(sql)
st.subheader("📊 Query Result")
st.dataframe(df)
# 4️⃣ Generate answer
with st.spinner("Generating answer..."):
answer = generate_answer(question, sql, df)
st.subheader("✅ Answer")
st.write(answer)