Skip to main content

Offline, schema-aware Text-to-SQL engine with optional LLM backends

Project description

🧠 Intelligent Text-to-SQL

An offline-first, schema-aware engine that safeguards your database while unlocking natural language queries.

Python License Status

FeaturesInstallationQuick StartArchitectureLLM Backends


Intelligent Text-to-SQL is a robust Python library designed to convert natural language questions into safe, executable SQL queries. It bridges the gap between human language and database schemas without relying on expensive cloud APIs, prioritizing correctness, security, and privacy.

Why use this?

  • 🚀 Zero Cost: Runs entirely offline or with local LLMs.
  • 🔒 Safe: Strict read-only enforcement; no accidental DROP TABLE.
  • 🧠 Smart: Understands your schema and detects ambiguity.

✨ Features

Feature Description
🔌 Offline & Zero-Cost Designed to work without paid APIs. Complete privacy for your data.
🏗️ Schema-Aware Intelligently builds queries based on your actual database structure.
🤖 Optional LLM Support Plug in local LLMs (like Ollama) for enhanced natural language understanding.
🛡️ Safety First Strictly prohibits INSERT, UPDATE, DELETE, and other destructive commands.
🔍 Smart Detection Identifies ambiguous queries and potential hallucinations.
📦 Easy Integration Pip-installable and backend-agnostic. Works with SQLite (PostgreSQL exp.).

📦 Installation

Install the package directly from PyPI:

pip install intelligent-text2sql

For development usage:

git clone https://github.com/vatsaPatel0097/intelligent_text2sql
cd intelligent_text2sql
pip install -e .

🚀 Quick Start

Get running in seconds with a SQLite database.

from intelligent_text2sql import Text2SQL

# Initialize the engine with your database URI
engine = Text2SQL("sqlite:///data/sales.db")

# Run a natural language query
result = engine.run("Show total sales per customer")

# Access the results
print(f"SQL: {result['sql']}")
print(f"Data:\n{result['data']}")

Example Output

{
  "sql": "SELECT customer_id, SUM(total_amount) AS total_sales FROM orders GROUP BY customer_id;",
  "data": "   customer_id  total_sales\n0          101       500.00\n1          102       750.50",
  "confidence": 0.9,
  "explanation": "Aggregates total sales per customer."
}

🛠️ How the System Works

The engine follows a multi-step pipeline to ensure accuracy and safety:

graph TD
    A["User Query"] --> B{"Ambiguity Check"}
    B -- Ambiguous --> C["Request Clarification"]
    B -- Clear --> D["Schema Extraction"]
    D --> E["Table Selection via Embeddings"]
    E --> F["SQL Generation"]
    F --> G["Validation (Table/Column Check)"]
    G --> H{"Safety Check"}
    H -- Unsafe --> I["Block Execution"]
    H -- Safe --> J["Execute SQL"]
    J --> K["Return Result"]
  1. Schema Extraction: Analyzes the database structure.
  2. Ambiguity Detection: Checks if the user's intent is clear.
  3. Table Selection: Uses embeddings to find relevant tables (vector search).
  4. Generation: Constructs SQL (Rule-based or LLM).
  5. Validation: Ensures tables and columns actually exist.
  6. Safety: Blocks any write/destructive operations.
  7. Execution: Runs the query and returns results.

🧠 LLM Backends

You can choose between a deterministic rule-based mode or an AI-enhanced mode.

1. Default Mode (No LLM)

Best for rigid schemas and simple queries. Fast and distinct.

engine = Text2SQL("sqlite:///data/sales.db")

2. Local LLM (via Ollama)

Best for complex queries and natural language flexibility.

Prerequisites:

  1. Install Ollama
  2. Pull a model (e.g., phi, mistral, llama3):
    ollama run phi
    

Usage:

engine = Text2SQL(
    "sqlite:///data/sales.db",
    llm_backend="ollama"
)

🖥️ Streamlit Demo

Visualize the engine in action with the built-in demo.

streamlit run app.py

The demo provides a UI to:

  • Input queries.
  • View generated SQL.
  • See the resulting data table.
  • Understand confidence scores and errors.

⚖️ License

Distributed under the MIT License. See LICENSE for more information.


Created by Vatsal Patel

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

intelligent_text2sql-0.1.1.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

intelligent_text2sql-0.1.1-py3-none-any.whl (13.9 kB view details)

Uploaded Python 3

File details

Details for the file intelligent_text2sql-0.1.1.tar.gz.

File metadata

  • Download URL: intelligent_text2sql-0.1.1.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for intelligent_text2sql-0.1.1.tar.gz
Algorithm Hash digest
SHA256 973e6d463102d1403ee90e63d684d23b978efc487d4531e956184e8e5694cd36
MD5 de0ad68d49c4b7dad8895a106f53d6c9
BLAKE2b-256 6e292dbcfffaa2e2fac46e4fbfee2b1b7d50f74aa9966271c90c3d30f9ec6fe1

See more details on using hashes here.

File details

Details for the file intelligent_text2sql-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for intelligent_text2sql-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8a334748bf2f5584157a746403de0649aeceeecbd3daff2cea61c9850b60497a
MD5 dd83b09636624245f46d273cf86c9490
BLAKE2b-256 7d7d81d295de00a2c525dcd1233104cfc6981512f97c8e388046ed1125dc5f58

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page