File size: 4,376 Bytes
f1eaad5 | 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 | # llm_sql_generator.py
import os
import re
import sqlite3
from functools import lru_cache
import numpy as np
from dotenv import load_dotenv
from sentence_transformers import SentenceTransformer
from gemini_flash_beta_llm import GeminiFlashBetaLLM
# ----------------------------------------
# Initialization
# ----------------------------------------
load_dotenv()
# Instantiate the Gemini Flash-beta wrapper (LangChain LLM)
llm = GeminiFlashBetaLLM()
# Embedding model for semantic search
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
# ----------------------------------------
# Utility Functions
# ----------------------------------------
def clean_sql_output(llm_text: str) -> str:
"""
Remove markdown-style SQL blocks and clean whitespace.
"""
return re.sub(r"```sql|```", "", llm_text, flags=re.IGNORECASE).strip()
def extract_schema_from_db(db_path: str) -> dict:
"""
Extracts table and column metadata from a SQLite DB file.
"""
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall()]
schema = {}
for table in tables:
cursor.execute(f"PRAGMA table_info({table});")
cols = [col_info[1] for col_info in cursor.fetchall()]
schema[table] = cols
conn.close()
return schema
def format_schema_for_prompt(schema: dict) -> str:
"""
Formats schema into a prompt-friendly string.
"""
return "\n".join([
f"Table: {table} — Columns: {', '.join(columns)}"
for table, columns in schema.items()
])
@lru_cache(maxsize=1000)
def get_query_embedding(text: str):
"""
Cacheable embedding for semantic search via SentenceTransformer.
"""
return embed_model.encode([text])[0]
# ----------------------------------------
# SQL Generation Functions
# ----------------------------------------
def generate_sql_from_prompt(
user_query: str,
index,
metadata,
schema_dict: dict,
top_k: int = 5
) -> str:
"""
Generate SQL using Gemini Flash-beta + semantic retrieval + schema.
"""
# 1) Semantic retrieval
query_emb = [get_query_embedding(user_query)]
D, I = index.search(np.array(query_emb).astype("float32"), top_k)
semantic_context = []
for idx in I[0]:
item = metadata[idx]
semantic_context.append(f"Table: {item['table']} | Column: {item['column']}")
semantic_text = "\n".join(semantic_context)
# 2) Schema context
schema_text = format_schema_for_prompt(schema_dict)
# 3) Build prompt
prompt = f"""
You are a SQL expert.
Use only the following schema and column names when generating SQL.
### DATABASE SCHEMA
{schema_text}
### RELEVANT COLUMNS
{semantic_text}
### USER QUESTION
{user_query}
Generate valid SQL using only the exact schema and column names provided.
Do not hallucinate table or column names.
SQL:
"""
# 4) Call the LLM wrapper
try:
response = llm._call(prompt)
return clean_sql_output(response)
except Exception as e:
print(f"[Flash LLM Error] {e}")
return "-- LLM failed to respond --"
def generate_sql_schema_only(
user_query: str,
schema_dict: dict
) -> str:
"""
Fallback generation using only full schema, no retrieval.
"""
schema_text = format_schema_for_prompt(schema_dict)
prompt = f"""
You are a SQL expert.
Below is the full schema of the database:
{schema_text}
User question:
{user_query}
Write a valid SQL query using only the tables and columns from the schema above.
Do not hallucinate table or column names.
SQL:
"""
try:
response = llm._call(prompt)
return clean_sql_output(response)
except Exception as e:
print(f"[Flash LLM Error] {e}")
return "-- LLM failed to respond --"
# ----------------------------------------
# Local Test CLI
# ----------------------------------------
if __name__ == "__main__":
# Example SQLite schema extraction
schema = extract_schema_from_db("your.db")
question = "List all customers with purchases after 2023"
print(generate_sql_schema_only(question, schema)) |