NLP-SQL is a schema-aware, safety-oriented natural-language query engine for turning natural-language questions into validated, parameterized SQL.
The central contract is still QueryAST. Natural language never becomes SQL
directly. Every query must pass through structured parsing, AST validation,
parameterized compilation, and SQL safety validation before execution.
The project has evolved into a hybrid semantic query system:
- deterministic rule-based parsing as a fast fallback;
- schema retrieval over datasets, tables, columns, aliases, descriptions, relational metadata, profiles, and representative values;
- local embedding retrieval for schema matching only, never SQL generation;
- adaptive vector search telemetry and interpretable search-budget policy;
- SQLite-backed embedding storage with a bounded in-memory LRU cache;
- ambiguity-aware Text-to-SQL evaluation utilities;
- multi-dataset registry and lightweight schema graph expansion;
- registry-aware dataset routing with ambiguity clarification;
- optional MCP-style facade that wraps the same safe engine.
NLP-SQL is not an LLM-to-SQL demo and does not ask a model to write SQL. The
optional embedding layer is used only to retrieve relevant schema concepts. SQL
is generated only from validated QueryAST objects.
The research-inspired modules are technically honest approximations. They are
inspired by systems and evaluation ideas, but they do not claim to reproduce the
full algorithms from those papers. See PAPER_MAPPING.md.
Natural-language query
-> dataset/schema retrieval
-> lexical retrieval
-> local embedding retrieval
-> hybrid ranking
-> optional schema graph expansion
-> LLM semantic planner or deterministic fallback
-> typed QueryAST and boolean filter tree
-> AST validation
-> parameterized SQL compilation
-> SQL safety validation
-> EXPLAIN and guarded read-only SQLite execution
Retrieval and telemetry can inform explanations and future adaptive ranking, but they must not bypass validation.
Prerequisites: Python 3.11+ with pip/venv support and internet access for the
first dependency installation and Kaggle dataset download. On systems where
python is unavailable, use python3 in the commands below. Linux distributions
may require their python3-venv package.
Clone once and enter the checkout:
git clone https://github.com/rashidiff/NLP-SQL.git
cd NLP-SQLThen, on Windows, macOS, or Linux, run this same command on every visit:
python start.pyIt creates/reuses .venv, installs the core package, prepares data/housing.sqlite
only if absent, and starts the HTTP API at http://127.0.0.1:8000.
No environment activation is needed. Send JSON POST requests to /parse,
/explain, or /execute (for example {"query":"show top 5 properties by sale price"}).
The root URL is not a browser UI. Stop with Ctrl+C.
Existing databases and environment variables are preserved. A failed initial
build is discarded so the same command can retry safely. Dependency installation
is repeated when pyproject.toml or the selected extras change; use --refresh
to repair or reinstall dependencies explicitly. Repeat runs with unchanged setup
skip installation and dataset preparation. Run only one bootstrap process per checkout.
Options (also available through python start.py --help):
python start.py --port 8080
python start.py --extras dev,mcp
python start.py --setup-only
python start.py --refresh
python start.py --db data/my-housing.sqliteRelative database paths are resolved from the checkout, even when the script is
invoked from another directory. A supplied existing database must use the housing
schema. Optional semantic extras install sentence-transformers and may download
a model on first use; the default core setup uses local hash embeddings.
--setup-only prepares the same environment and database without starting a server.
For subsequent CLI work without activation, use .venv/Scripts/python -m nlp_sql
on Windows or .venv/bin/python -m nlp_sql on macOS/Linux, followed by a CLI command.
The launcher starts the HTTP API; the optional MCP server still uses its separate
entry point documented below.
git clone https://github.com/rashidiff/NLP-SQL.git
cd NLP-SQL
python -m venv .venvActivate the environment:
# Windows PowerShell
.venv\Scripts\Activate.ps1
# macOS / Linux
source .venv/bin/activateInstall the core package:
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"Optional local sentence-transformers support:
python -m pip install -e ".[semantic]"The default semantic backend is a deterministic local hash embedding backend, so the project works without downloading a transformer model.
The default engine path is local and non-LLM. When sentence-transformers is
installed, the engine prefers all-MiniLM-L6-v2 for CPU-friendly schema
embeddings; otherwise it uses the explicit degraded hash-embedding fallback.
The semantic planner generates a beam of local AST candidates, ranks them with
schema evidence and query memory, and explores close candidates probabilistically.
SQL is still compiled only from validated QueryAST objects.
Useful controls:
$env:NLP_SQL_EMBEDDING_BACKEND = "auto"
$env:NLP_SQL_SEMANTIC_TEMPERATURE = "0.18"
$env:NLP_SQL_SEMANTIC_BEAM_WIDTH = "6"
$env:NLP_SQL_ENABLE_LLM = "0"The optional LLM planner is disabled by default and can only be enabled
explicitly with NLP_SQL_ENABLE_LLM=1.
Install the MCP extras and run the stdio server:
python -m pip install -e ".[mcp,semantic]"
nlp-sql-mcp --db data/housing.sqliteThe server exposes inspect_schema, search_schema, plan_query,
validate_plan, explain_query, execute_query, and record_feedback. All
tools use the same AST validation, parameterized compiler, and read-only safety
layer.
Optional LLM semantic parsing can be enabled with an OpenAI-compatible chat completion endpoint. The model returns a structured query plan, never SQL:
# PowerShell
$env:NLP_SQL_LLM_API_KEY = "..."
$env:NLP_SQL_LLM_MODEL = "gpt-4o-mini"
$env:NLP_SQL_LLM_BASE_URL = "https://api.openai.com/v1"
nlp-sql parse "show expensive homes with at least four bedrooms"NLP_SQL_LLM_BASE_URL may point to a compatible local or hosted endpoint. The
existing deterministic parser remains the fallback when the LLM is disabled,
unavailable, ambiguous, or produces an invalid plan. Both paths use the same
AST validator, parameterized compiler, and SQL safety checks.
When a SQLite housing database is opened, the engine profiles whitelisted
columns (null ratio, distinct count, min/max, and sample values) and attaches
that evidence to schema retrieval documents. Execution results can include the
SQLite query plan under execution_plan.
For multiple registered datasets, RegistryQueryEngine first selects a
dataset using registry metadata and routes the query to that dataset's schema,
retriever, LLM planner, and executor. Close dataset scores result in an
explicit clarification instead of a silent cross-dataset guess.
Prepare the Nashville Housing SQLite database:
nlp-sql prepare-dataParse a query and show generated AST/SQL:
nlp-sql parse "show properties with bedrooms at least 4"Parse against your own schema JSON without preparing a demo database:
nlp-sql parse "show all tickets" --schema ./schema.jsonExplain without execution:
nlp-sql explain "show expensive homes"Execute against SQLite:
nlp-sql query "show top 5 properties by sale price"Run the HTTP API:
nlp-sql serveSchema retrieval without SQL generation:
from nlp_sql.engine import NlpSqlEngine
engine = NlpSqlEngine.for_housing_dataset()
print(engine.explain_schema_match("show houses with large lots"))Safe parse with retrieval evidence and adaptive decision:
result = engine.parse("show expensive homes")
print(result.to_dict()["schema_candidates"])
print(result.to_dict()["adaptive_decision"])Smart-city demo registry:
from pathlib import Path
from nlp_sql.dataset_registry import build_smart_city_demo_registry
from nlp_sql.schema_graph import SchemaGraph
registry = build_smart_city_demo_registry(Path("data/demo"))
graph = SchemaGraph.from_registry(registry)- Only structured
QueryASTobjects are compiled. - Tables, columns, operators, aggregations, ordering, and limits are validated.
- Join tables and join keys are validated against the configured schema.
- User values are passed as SQL parameters.
- SQL safety checks reject write operations and stacked statements.
- Retrieval evidence cannot directly produce SQL.
- Nested boolean filter expressions support AND/OR/NOT and operators such as IN, LIKE, and IS NULL.
- Typed subqueries support IN/NOT IN/EXISTS, and CTEs preserve parameterized compilation and nested validation.
- Window expressions support whitelisted ranking and analytic functions.
- Joins are represented in the AST and validated before compilation.
- Benchmark cases can compare ordered or unordered execution results with a configurable floating-point tolerance.
- SQLite execution is read-only and guarded by a row limit and timeout.
- Workload benchmarks can optionally execute each query and report LLM, repair, clarification, and database-failure telemetry.
- MCP-style tools call the same engine methods and cannot bypass validation.
Useful commands:
python -m pytest
python -m ruff check .
python -m mypyBenchmark utilities are documented in BENCHMARKS.md.
src/nlp_sql/engine.py orchestration and safe pipeline
src/nlp_sql/parser.py deterministic semantic parser
src/nlp_sql/query_ast.py typed semantic query model
src/nlp_sql/retrieval/ hybrid retrieval, vector index, store, telemetry
src/nlp_sql/dataset_registry.py multi-dataset metadata registry
src/nlp_sql/schema_graph.py transparent schema metadata graph
src/nlp_sql/evaluation/ ambiguity-aware evaluation framework
src/nlp_sql/benchmarks.py workload and ablation utilities
src/nlp_sql/mcp_interface.py optional MCP-style facade
ARCHITECTURE.md: original deterministic designARCHITECTURE_V2.md: hybrid semantic architectureSYSTEM_DESIGN.md: implementation overviewPAPER_MAPPING.md: research inspiration and non-reproduction boundariesBENCHMARKS.md: workload and ablation guidance