Skip to content

About

Convert natural language into SQL queries using Google's Gemini LLM with a simple Python Program.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

English-to-SQL Query Generator

An AI-powered Natural Language Interface for Relational Databases (NLIDB) that translates plain English queries into executable, standards-compliant SQL using Google's Gemini Large Language Model.

Python Google Gemini API License: MIT Maintenance


Table of Contents


Overview

The English-to-SQL Query Generator bridges the gap between natural language comprehension and relational database querying. By leveraging Google's state-of-the-art Gemini LLM through the official google-genai SDK, this application converts everyday English requests into structured SQL syntax in real time.

Built with a focus on clean software design, strict output formatting, and prompt engineering, the project provides a responsive, interactive Command-Line Interface (CLI) that enables both technical and non-technical stakeholders to formulate database queries seamlessly.


Why It Matters

Relational databases power modern enterprise applications, but extracting insights typically demands familiarity with SQL dialects, clause structures (JOIN, GROUP BY, HAVING), and filtering syntax.

  • For Business & Operations Teams: Eliminates dependence on data engineering teams for routine ad-hoc queries, accelerating decision-making.
  • For Developers & Analysts: Reduces context switching and boilerplate query drafting, serving as an intelligent query-authoring assistant.
  • For AI/Data Engineering: Demonstrates foundational concepts of Natural Language to SQL (NL-to-SQL), a cornerstone capability in modern Agentic RAG pipelines and conversational analytics architectures.

Key Features

  • Zero-Shot NL-to-SQL Translation: Direct mapping from intent-rich natural language expressions to ANSI SQL queries.
  • Strict Format Enforcement: Multi-tier sanitization combining negative constraint prompting with deterministic string cleaning to strip Markdown wrappers (sql ... ).
  • Interactive Session Loop: Persistent CLI session supporting consecutive query generations without process re-initialization.
  • Defensive Error Handling: Input validation against empty queries and resilient handling of upstream API connection timeouts and exceptions.
  • Environment Isolation: Zero-hardcoding security architecture isolating API credentials and configurable model identifiers via .env.

Tech Stack

Domain Technology Role / Purpose
Language Python 3.10+ Core application logic and CLI runtime
AI / LLM SDK Google Gen AI SDK (google-genai) Modern client interface for Google Gemini API models
Foundation Model Google Gemini Flash High-speed, cost-effective inference for code & structured generation
Configuration python-dotenv Secure runtime environment variable injection
Version Control Git & GitHub Source control, issue tracking, and repository management

Architecture & Workflow

The following sequence outlines the end-to-end data lifecycle from user prompt entry to sanitized SQL output:

sequenceDiagram
    autonumber
    actor User
    participant CLI as CLI Interface (main.py)
    participant Engine as Prompt Engine
    participant GenAI as Google GenAI Client
    participant Model as Gemini LLM
    participant Sanitizer as Output Sanitizer

    User->>CLI: Enters English instruction
    CLI->>CLI: Validate input (check non-empty)
    CLI->>Engine: Construct constrained prompt
    Engine->>GenAI: Dispatch generate_content request
    GenAI->>Model: Run inference (Zero-Shot SQL generation)
    Model-->>GenAI: Return raw model response
    GenAI-->>Sanitizer: Stream response payload
    Sanitizer->>Sanitizer: Strip markdown backticks & leading/trailing whitespace
    Sanitizer-->>CLI: Return clean SQL string
    CLI-->>User: Display formatted SQL query
Loading

Workflow Steps

  1. Input Ingestion & Validation: Captures string input via standard input; strips whitespace and guards against null/empty payloads.
  2. Constrained Prompt Assembly: Wraps input with directive rules restricting natural language pleasantries, explanations, or code-block formatting.
  3. Inference Execution: Sends the payload to Gemini using client.models.generate_content with configurable model targets.
  4. Post-Processing & Output Scrubbing: Normalizes output by removing accidental markdown code blocks (```sql / ```) to ensure terminal-ready query text.
  5. Interactive Lifecycle: Prompts the user to continue or terminate gracefully.

AI/ML Implementation & Prompt Engineering

Model Strategy

  • Selected Model Family: Google Gemini (e.g., gemini-2.5-flash or gemini-1.5-flash).
  • Rationale: Optimized for sub-second latency, high instruction fidelity, and structural token generation (SQL/JSON), providing cost-effective generation suitable for real-time developer tooling.

Prompt Engineering Architecture

Large language models frequently default to conversational filler ("Sure! Here is your query:") and Markdown code formatting. To guarantee consistent query output for downstream consumption:

contents = f"""
Convert the following English sentence into an SQL query.

Rules:
- Return only the SQL query.
- Do not explain anything.
- Do not use Markdown.
- Do not use code blocks.

English:
{query}
"""

Sanitization Pipeline

Because generative models may occasionally include markdown fences despite negative constraints, the application implements a defense-in-depth sanitization layer:

sql = response.text.strip()
sql = sql.replace("```sql", "")
sql = sql.replace("```", "").strip()

Known Technical Limitations

  • Schema Agnosticism: Currently operates without database schema context (DDL); table names and column attributes are inferred from user wording rather than actual database catalogs.
  • Dialect Specificity: Defaults to standard ANSI SQL. Advanced dialect-specific extensions (e.g., PostgreSQL JSONB, BigQuery arrays, SQLite-specific pragmas) require explicit mention in the prompt.

Practical Applications

  • Self-Service Analytics: Embedded into internal slackbots or dashboards to assist non-technical team members in querying read-replicas.
  • Database Exploration: Helps junior developers quickly formulate multi-table JOIN conditions and window functions (ROW_NUMBER(), RANK()).
  • Data Pipeline Ingestion: Serves as a modular subsystem for automated natural-language ETL filters.

Project Structure

English-to-SQL-Query-Generator/
│
├── main.py              # Application entry point, CLI loop, LLM call, and sanitizer
├── requirements.txt     # Locked production dependencies
├── .env                 # Local secrets (API keys, model configuration) - excluded from git
├── .gitignore           # Git ignore file for venv, caches, and .env
└── README.md            # Comprehensive project documentation

Installation & Setup

Prerequisites

  • Python: Version 3.10 or higher
  • Gemini API Key: Obtainable from Google AI Studio

Step 1: Clone the Repository

git clone https://github.com/soumyadip-das-dev/English-to-SQL-Query-Generator.git
cd English-to-SQL-Query-Generator

Step 2: Set Up Virtual Environment

On Windows (PowerShell):

python -m venv venv
.\venv\Scripts\Activate.ps1

On macOS / Linux:

python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

Step 4: Configure Environment Variables

Create a .env file in the root directory:

GEMINI_API_KEY=your_google_gemini_api_key_here
MODEL_NAME=gemini-2.5-flash

Note: Ensure .env is listed in your .gitignore to prevent committing sensitive credentials.


Usage & Sample Scenarios

Run the main application:

python main.py

Sample Session

==================================================
        English to SQL Generator
==================================================
 Convert English into SQL using Gemini LLM
==================================================

Enter Your English Query: Find the top 5 highest-earning employees in the Engineering department hired after 2022

Generated SQL:

SELECT *
FROM employees
WHERE department = 'Engineering' 
  AND hire_date > '2022-12-31'
ORDER BY salary DESC
LIMIT 5;

Generate another SQL query? (y/n): y

Enter Your English Query: Calculate the average order amount per customer for completed orders in 2023

Generated SQL:

SELECT customer_id, AVG(order_amount) AS average_order_amount
FROM orders
WHERE status = 'Completed' 
  AND order_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY customer_id;

Generate another SQL query? (y/n): n

Thank you for using English to SQL Generator!

Engineering Decisions & Technical Depth

1. Migration to Modern google-genai SDK

Instead of deprecated legacy libraries (google-generativeai), this project adopts the modern Google Gen AI SDK (google-genai v2.x), ensuring long-term API support, structured response models, and compatibility with Google's latest Gemini models.

2. Dual-Layer Output Cleaning

Relying solely on LLM instruction following can result in sporadic formatting issues. Combining negative prompt constraints with deterministic string normalization ensures the output can be directly redirected or piped into SQL query runners without syntax errors.

3. Separation of Concerns & State Decoupling

The architecture decouples the generation logic (generate_sql()) from the control loop (main()), making it straightforward to refactor the core translation function into a REST API endpoint (e.g., FastAPI) or a GUI component (e.g., Streamlit).


Roadmap & Future Enhancements

  • Schema-Aware Generation (DDL Grounding): Ingest database schemas or sqlite3/PostgreSQL table catalogs to eliminate column/table hallucination.
  • Direct Execution Engine: Add an optional read-only execution module to run generated queries against connected databases and return formatted tabular results.
  • Dialect Selector: Add support for explicit target dialects (PostgreSQL, MySQL, SQLite, Snowflake, BigQuery).
  • Web & API Interfaces: Develop a Streamlit web interface and a FastAPI microservice wrapper with OpenAPI documentation.
  • SQL Validation & Syntax Highlighting: Integrate sqlparse for syntax validation, auto-formatting, and ANSI terminal syntax colorization.

Learning Outcomes

  • AI/LLM Engineering: Hands-on experience with LLM API orchestration, system prompting, negative constraint formulation, and output sanitization.
  • Python Engineering: Designing robust CLI applications, virtual environment management, clean dependency resolution, and defensive error handling.
  • Relational Data Modeling: Translating diverse relational algebra requirements (projections, selections, aggregations, joins) into standardized SQL syntax.

Contributing

Contributions are welcome! If you'd like to improve the prompt design, add tests, or introduce new features:

  1. Fork the repository (https://github.com/soumyadip-das-dev/English-to-SQL-Query-Generator).
  2. Create a feature branch (git checkout -b feature/schema-grounding).
  3. Commit your changes (git commit -m "feat: add schema-aware SQL translation").
  4. Push to the branch (git push origin feature/schema-grounding).
  5. Open a Pull Request.

License

This project is licensed under the MIT License. See the LICENSE file for details.


Author & Connect

Soumyadip Das
Aspiring Software Engineer & AI/ML Engineer
B.Tech in Computer Science & Engineering (AI & ML)

About

Convert natural language into SQL queries using Google's Gemini LLM with a simple Python Program.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages