added vectorstore and src folders, dockerfile requirements dockerignore files
Browse filesFiles changed (13)
- .dockerignoreAdded+5
- DockerfileAdded+34
- README.md+143-12
- requirements.txtAdded+17
- src/app.pyAdded+146
- src/gemini_flash_beta_llm.pyAdded+61
- src/langchain_sql_pipeline.pyAdded+86
- src/utils/embeddings.pyAdded+41
- src/utils/er_diagram.pyAdded+8
- src/utils/llm_sql_generator.pyAdded+164
- src/utils/schema_extractor.pyAdded+24
- vectorstore/schema_index.faissAdded
- vectorstore/schema_meta.pklAdded+3
12345__pycache__/
*.pyc
*.pkl # if you want to rebuild vectorstore inside container
.env
venv/12345678910111213141516171819202122232425262728293031323334# syntax=docker/dockerfile:1
FROM python:3.10-slim AS builder
RUN apt-get update && apt-get install -y --no-install-recommends \
curl build-essential sqlite3 libpq-dev default-libmysqlclient-dev gnupg \
gcc python3-dev libpq-dev \
&& curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
&& apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt
COPY . .
FROM python:3.10-slim
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY . .
ENV STREAMLIT_SERVER_HEADLESS=true \
STREAMLIT_SERVER_PORT=10000 \
STREAMLIT_SERVER_ADDRESS=0.0.0.0 \
STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
EXPOSE 10000
CMD ["sh", "-c", "streamlit run src/app.py --server.port=${PORT:-10000} --server.address=0.0.0.0"]123456789101112---title: Nl2sqlemoji: 🏃colorFrom: pinkcolorTo: graysdk: dockerpinned: falselicense: cc-by-nc-4.0short_description: Natural language to SQL---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# Text-to-SQL RAG AppThis application leverages **Retrieval-Augmented Generation (RAG)** to convert natural language queries into SQL statements. It integrates the **Gemini LLM** for SQL generation and supports various databases including **SQLite, PostgreSQL, and MySQL**.## Features* **Multi-Database Support:** SQLite, PostgreSQL, and MySQL.* **Flexible Query Modes:*** **LangChain RAG**: Uses LangChain for SQL generation.* **Manual FAISS RAG**: Uses FAISS index for retrieval.* **Schema Only**: Direct SQL generation from schema.* **Schema Visualization:** Automatically generates ER diagrams for uploaded databases.* **Real-Time Execution:** Runs generated SQL queries and displays the results.---## 📂 Project Structure```Text-to-SQL RAG App/├── app.py # Main Streamlit app├── requirements.txt # Dependencies list├── utils/ # Utility scripts│ ├── er_diagram.py # ER diagram generator│ ├── llm_sql_generator.py # SQL generation using Gemini│ ├── schema_extractor.py # Extracts schema from databases│ └── vector_store.py # FAISS-based vector store└── vectorstore/ # Stores FAISS index and metadata```---## Installation1. **Clone the Repository:**```bashgit clone https://github.com/Bindhu-T-Devidas/Natural-Language-to-SQL.gitcd Natural-Language-to-SQL```2. **Install Dependencies:**```bashpip install -r requirements.txt```3. **Set Up Environment Variables:**Create a `.env` file:```GEMINI_API_KEY=your_gemini_api_key```Replace `your_gemini_api_key` with your actual API key.---## Usage1. **Run the Streamlit App:**```bashstreamlit run app.py```2. **Upload a Database:*** Choose between **SQLite**, **PostgreSQL**, or **MySQL**.* Upload the file or enter database credentials.3. **Generate SQL Query:*** Enter your natural language query.* Choose the query mode:* 🔁 **LangChain RAG*** 🛠️ **Manual FAISS RAG*** 📄 **No RAG (schema only)*** Click **"🚀 Generate SQL"**.4. **View Results:*** The generated SQL query will be displayed.* If the query executes successfully, the result table will be shown.---## Technologies Used* **Python**: Core programming language.* **Streamlit**: Frontend for interactive query generation.* **LangChain**: RAG pipeline for SQL generation.* **Gemini LLM**: SQL generation engine.* **FAISS**: Vector store for semantic retrieval.* **SQLAlchemy**: Database connection handling.* **Graphviz**: Visualizes ER diagrams.---## ER Diagram GenerationThe application uses the `Graphviz` library to generate ER diagrams from the uploaded database schemas.---## 🌐 Supported Database Types1. **SQLite (.db, .sqlite, .sql)**2. **PostgreSQL**3. **MySQL**---## Query Modes* **LangChain RAG**: Uses LangChain to efficiently retrieve top-k schema elements via FAISS and generate SQL using an LLM (Gemini), providing modularity, prompt flexibility, and easier experimentation.* **Manual FAISS RAG**: Directly uses FAISS for top-k retrieval and constructs a prompt for Gemini manually, offering control but requiring more code.* **No RAG (Schema Only)**: Generates SQL using the full schema directly, without any retrieval, which can cause hallucination and irrelevant joins in complex schemas.---## 📊 Output Example* **SQL Query:**```sqlSELECT * FROM tracks WHERE genre = 'Rock';```* **Results:**| TrackID | Name | Genre || ------- | ------------- | ----- || 1 | Thunderstruck | Rock || 2 | Back in Black | Rock |---
1234567891011121314151617streamlit>=1.45.0
python-dotenv>=1.0.0
sqlalchemy>=2.0.0
pymysql>=1.0.0
psycopg2-binary>=2.9.0
faiss-cpu>=1.7.0
sentence-transformers>=4.0.0
langchain>=0.3.0
langchain-community>=0.3.0
langchain-core>=0.3.0
requests>=2.0.0
hf_xet>=1.1.0
numpy>=1.21.0
pandas>=2.0.0
graphviz>=0.20.0
tqdm>=4.0.0
pydantic>=2.0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146import streamlit as st
import pandas as pd
import sqlite3
import tempfile
from sqlalchemy import create_engine
import os
import re
# --- Ensure vectorstore directory exists relative to src/app.py ---
vectorstore_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../vectorstore"))
os.makedirs(vectorstore_dir, exist_ok=True)
# If you need the FAISS index path, use:
index_path = os.path.join(vectorstore_dir, "schema_index.faiss")
from utils.schema_extractor import extract_schema_sqlite, extract_schema_rdbms
from utils.embeddings import build_or_load_index
from utils.llm_sql_generator import (
generate_sql_from_prompt,
generate_sql_schema_only,
)
from langchain_sql_pipeline import generate_sql_with_langchain
from utils.er_diagram import render_er_diagram
# --- SQL cleaning utility ---
def clean_sql(raw_sql):
"""
Removes markdown code block markers from the generated SQL.
Handles ```sql ... ```
"""
# Remove ```sql or ``` from start
sql = re.sub(r"^```(?:sql)?\s*", "", raw_sql)
# Remove trailing ```
sql = re.sub(r"```$", "", sql)
return sql.strip()
# --- Page setup ---
st.set_page_config(
page_title="Text-to-SQL RAG Demo",
layout="wide",
)
# Hide Streamlit chrome
st.markdown(
"""
<style>
#MainMenu, header, footer { visibility: hidden; }
.css-12oz5g7, .block-container { background: #000 !important; }
</style>
""",
unsafe_allow_html=True,
)
# --- Sidebar for DB setup ---
with st.sidebar:
st.header("Database Setup")
db_type = st.selectbox("Type", ["SQLite", "PostgreSQL", "MySQL"])
schema_data = None
db_connector = None
if db_type == "SQLite":
uploaded = st.file_uploader("Upload .db/.sqlite/.sql", type=["db", "sqlite", "sql"])
if uploaded:
tf = tempfile.NamedTemporaryFile(delete=False, suffix=".sqlite")
tf.write(uploaded.read())
tf.close()
schema_data = extract_schema_sqlite(tf.name)
db_connector = lambda q: pd.read_sql_query(q, sqlite3.connect(tf.name))
else:
with st.expander("Enter credentials"):
host = st.text_input("Host", key="host")
port = st.text_input("Port", "5432" if db_type == "PostgreSQL" else "3306", key="port")
user = st.text_input("User", key="user")
pwd = st.text_input("Password", type="password", key="pwd")
name = st.text_input("Database", key="dbname")
if st.button("Connect", key="connect_btn"):
uri = (
f"postgresql://{user}:{pwd}@{host}:{port}/{name}"
if db_type == "PostgreSQL"
else f"mysql+pymysql://{user}:{pwd}@{host}:{port}/{name}"
)
try:
schema_data = extract_schema_rdbms(uri)
engine = create_engine(uri)
db_connector = lambda q: pd.read_sql_query(q, engine)
st.success("Connected")
except Exception as e:
st.error(f"{e}")
# --- Main panel ---
st.title("Text-to-SQL Generator")
if schema_data:
# Schema diagram
st.subheader("Schema Diagram")
st.graphviz_chart(render_er_diagram(schema_data))
# Question + mode
st.subheader("Ask Your Database")
q_col, m_col = st.columns((3, 1))
with q_col:
question = st.text_input(
"Your Question",
placeholder="e.g. List rock-genre tracks",
key="user_question",
label_visibility="collapsed"
)
with m_col:
mode = st.selectbox(
"Mode",
["LangChain RAG", "Manual FAISS", "Schema Only"],
help="How to generate the SQL",
key="mode_select"
)
# Generate button
generate = st.button("Generate SQL", use_container_width=True, key="generate_btn")
if generate and question:
with st.spinner("Generating…"):
if mode == "LangChain RAG":
raw = generate_sql_with_langchain(question, schema_data)
elif mode == "Manual FAISS":
idx, meta = build_or_load_index(schema_data)
raw = generate_sql_from_prompt(question, idx, meta, schema_data)
else:
raw = generate_sql_schema_only(question, schema_data)
sql = clean_sql(raw)
# Show SQL
st.subheader("Generated SQL")
st.code(sql, language="sql")
# Show results
if db_connector:
st.subheader("Results")
try:
df = db_connector(sql)
st.metric("Rows returned", len(df))
st.dataframe(df, use_container_width=True)
except Exception as e:
st.error(f"Execution failed: {e}")
else:
st.info("Use the sidebar to upload or connect to a database.")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# gemini_flash_beta_llm.py
import os
import requests
from dotenv import load_dotenv
from langchain.llms.base import LLM
from typing import Optional, List
load_dotenv()
# Default settings for the Flash endpoint
API_KEY = os.getenv("GEMINI_API_KEY")
BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
DEFAULT_MODEL_NAME = "gemini-2.0-flash"
class GeminiFlashBetaLLM(LLM):
"""LangChain LLM wrapper around the v1beta Flash endpoint."""
# Pydantic fields for BaseModel compatibility
model_name: str = DEFAULT_MODEL_NAME
api_key: str = API_KEY
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
# Ensure API key
key = self.api_key or API_KEY
if not key:
raise ValueError("Set your GEMINI_API_KEY in .env")
url = f"{BASE_URL}/models/{self.model_name}:generateContent"
params = {"key": key}
body = {"contents": [{"parts": [{"text": prompt}]}]}
r = requests.post(url, params=params, json=body)
r.raise_for_status()
data = r.json()
# Extract the first candidate
candidates = data.get("candidates") or []
if not candidates:
return ""
first = candidates[0]
# Handle content vs output fields
content = first.get("content") if "content" in first else first.get("output")
text = ""
if isinstance(content, dict):
# Some models return nested parts
parts = content.get("parts") or []
for part in parts:
# support dict or plain text
fragment = part.get("text") if isinstance(part, dict) else part
if fragment:
text += fragment
elif isinstance(content, str):
text = content
return text.strip()
@property
def _llm_type(self) -> str:
return f"gemini-flash-v1beta-{self.model_name}"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# langchain_sql_pipeline.py
import pickle
from pathlib import Path
from dotenv import load_dotenv
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from gemini_flash_beta_llm import GeminiFlashBetaLLM
# Load environment variables (for GEMINI_API_KEY, etc.)
load_dotenv()
# Compute project root (one level above src/)
ROOT_DIR = Path(__file__).resolve().parent.parent
VECTORSTORE_DIR = ROOT_DIR / "vectorstore"
META_PATH = VECTORSTORE_DIR / "schema_meta.pkl"
def load_faiss_retriever():
"""
Load FAISS index with HuggingFace embeddings for column-level retrieval.
"""
if not META_PATH.exists():
raise FileNotFoundError(f"FAISS metadata not found at {META_PATH}")
with open(META_PATH, "rb") as f:
metadata = pickle.load(f)
texts = [f"{m['table']} - {m['column']}" for m in metadata]
embedder = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
db = FAISS.from_texts(texts, embedder)
return db.as_retriever(search_type="similarity", k=5), metadata
def generate_sql_with_langchain(user_query: str, schema_dict: dict) -> str:
"""
RAG pipeline: uses FAISS for retrieval of relevant columns,
then Gemini-Flash (v1beta) to generate a SQL query.
"""
# 1) Retrieve relevant columns
retriever, metadata = load_faiss_retriever()
docs = retriever.get_relevant_documents(user_query)
semantic_context = "\n".join(d.page_content for d in docs)
# 2) Format full schema for grounding
schema_text = "\n".join(
f"Table: {t} — Columns: {', '.join(cols)}"
for t, cols in schema_dict.items()
)
# 3) Build prompt template
prompt_template = PromptTemplate.from_template("""
You are a SQL expert. Given the database schema and relevant columns, write a SQL query for the user question.
### DATABASE SCHEMA
{schema}
### RELEVANT COLUMNS
{context}
### USER QUESTION
{question}
Only use valid table and column names. Do not hallucinate.
SQL:
""")
# 4) Instantiate the Flash-beta LLM wrapper
llm = GeminiFlashBetaLLM()
# 5) Create and run the chain
chain = LLMChain(llm=llm, prompt=prompt_template)
return chain.run(schema=schema_text, context=semantic_context, question=user_query)
# ----------------------------------------
# Optional CLI test
# ----------------------------------------
if __name__ == "__main__":
example_schema = {
"users": ["id", "name", "age"],
"orders": ["order_id", "user_id", "amount", "created_at"]
}
question = "Find all users older than 30 who placed orders over 100"
print(generate_sql_with_langchain(question, example_schema))1234567891011121314151617181920212223242526272829303132333435363738394041import faiss
import os
import pickle
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer("all-MiniLM-L6-v2")
# Always compute the vectorstore directory relative to this file
vectorstore_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../vectorstore"))
os.makedirs(vectorstore_dir, exist_ok=True)
index_path = os.path.join(vectorstore_dir, "schema_index.faiss")
meta_path = os.path.join(vectorstore_dir, "schema_meta.pkl")
def build_or_load_index(schema_dict):
if os.path.exists(index_path) and os.path.exists(meta_path):
print("🔄 Loading FAISS index and metadata from disk...")
index = faiss.read_index(index_path)
with open(meta_path, "rb") as f:
metadata = pickle.load(f)
return index, metadata
print("⚡ Building new FAISS index and metadata (cold start)...")
texts, metadata = [], []
for table, cols in schema_dict.items():
for col in cols:
desc = f"{table} - {col}"
texts.append(desc)
metadata.append({"table": table, "column": col})
embeddings = model.encode(texts)
index = faiss.IndexFlatL2(len(embeddings[0]))
index.add(np.array(embeddings).astype("float32"))
# Directory is already ensured above
faiss.write_index(index, index_path)
with open(meta_path, "wb") as f:
pickle.dump(metadata, f)
return index, metadata12345678from graphviz import Digraph
def render_er_diagram(schema_dict):
dot = Digraph()
for table, cols in schema_dict.items():
col_str = "\n".join(cols)
dot.node(table, f"{table}\n{col_str}", shape="box")
return dot.source123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164# 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))123456789101112131415161718192021222324from sqlalchemy import create_engine, inspect
import sqlite3
def extract_schema_sqlite(db_path):
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});")
schema[table] = [col[1] for col in cursor.fetchall()]
conn.close()
return schema
def extract_schema_rdbms(db_uri):
engine = create_engine(db_uri)
inspector = inspect(engine)
schema = {}
for table in inspector.get_table_names():
columns = [col["name"] for col in inspector.get_columns(table)]
schema[table] = columns
return schema123version https://git-lfs.github.com/spec/v1oid sha256:bb94b95293f0b15fca870760a5006240f120473318e0b6867e92af6486f84ee3size 392.dockerignoreAdded+5
DockerfileAdded+34
README.md+143-12
requirements.txtAdded+17
src/app.pyAdded+146
src/gemini_flash_beta_llm.pyAdded+61
src/langchain_sql_pipeline.pyAdded+86
src/utils/embeddings.pyAdded+41
src/utils/er_diagram.pyAdded+8
src/utils/llm_sql_generator.pyAdded+164
src/utils/schema_extractor.pyAdded+24
vectorstore/schema_index.faissAdded
vectorstore/schema_meta.pklAdded+3