Skip to content
thisismayureshPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

NL2SQL

Ask a database a question in plain English; get the SQL, live results and a chart.

Everything runs locally. No question, schema or value leaves the machine — SQL is written by a local model in Docker via Ollama, and the vector index lives in a local Chroma folder.

The target database is never modified. The backend holds a read-only connection and refuses anything that is not a single SELECT, at four independent layers.

PostgreSQL target. The database NL2SQL reads is whatever TARGET_DATABASE_URL points at. PostgreSQL is the supported dialect today; other vendors can be added later behind the same engine/app/db/dialects/ seam.

Models are pluggable. Run local LLMs and local embedding models through Ollama (the default), or any OpenAI-compatible /v1 endpoint — hosted or a local server such as llama.cpp, LM Studio or vLLM. The LLM and the embedding model are chosen independently. If the embedding model's vector width does not match the index, startup fails with a message telling you how to fix it, rather than silently returning wrong matches.

ARCHITECTURE.md — how it works and why: request lifecycle, module map, the four-layer safety model, the dialect contract, the performance model with measurements, and a decision log.


Architecture

One backend process, not three. The FastAPI backend also does the jobs the old NestJS gateway used to do (the /api prefix, CORS, strict body validation, rate limiting, and the health envelope), so there is one thing to start and one place where a request is understood.

Browser  :3000   Next.js   UI, streaming SQL, result grid, charts
   |
   |  /api/*   (Next.js rewrite -> http://localhost:8000, same origin, no CORS)
   v
Backend  :8000   FastAPI
   |             /api/health  /api/schema  /api/schema/refresh
   |             /api/chat/ask (SSE)  /api/chat/feedback  /api/chat/sessions
   |
   |  retrieve -> generate -> guard -> validate -> execute -> chart
   |
   +--> target database   READ-ONLY, external, any SQL vendor
   +--> app_db   :5433    ours: chat history, examples, audit log
   +--> Chroma   in-process, engine/data/chroma   schema / value / example vectors
   +--> Redis    :6379    question -> SQL cache
   +--> Ollama   :11434   local LLM + local embedding model

engine/app/main.py assembles the app; engine/app/api/ holds the routes grouped by concern. engine/app/services.py builds every long-lived component once.

Models and providers

Two provider categories, selected per role with LLM_PROVIDER and EMBEDDING_PROVIDER:

Provider Runs Works for
ollama local models on your machine (default) local LLM and local embeddings
openai any OpenAI-compatible /v1 API hosted APIs and local servers (llama.cpp, LM Studio, vLLM, Ollama's /v1)

Because the two roles are independent you can, for example, run the LLM on Ollama and the embedding model on a local OpenAI-compatible server, or point the LLM at a hosted model while keeping embeddings local.

Every provider implements the same two small interfaces — LanguageModel (complete, stream, health) and EmbeddingModel (embed, probe_vector_size, health) — in engine/app/llm/. A new provider is one class plus a branch in registry.py.

The compatibility check. The embedding model's vector width is probed at startup (or taken from EMBEDDING_DIMENSION). If it disagrees with the width the Chroma collections were built with, the backend refuses to boot: a mismatched index returns nonsense that looks like a real answer. The message tells you to restore the previous model or clear the vector store and refresh.

API reference

Every route is served by the one backend, under /api. The React app consumes these exact shapes (web/lib/types.ts is the client-side twin of the wire format).

Method Path Body / query Returns Used by web
GET /api/health — { gateway: { ok }, engine: EngineHealth } readiness panel, status badge
GET /api/schema — SchemaSnapshot —
POST /api/schema/refresh { indexValues?: boolean } SchemaRefreshReport "Read the database structure"
POST /api/chat/ask { question, sessionId? } SSE stream the chat
POST /api/chat/feedback { question, sql, wasHelpful? } { storedAsExample, cacheCleared } thumbs up/down
GET /api/chat/sessions ?limit= ChatSession[] —
GET /api/chat/sessions/{id}/messages — ChatMessage[] —

The health envelope keeps the name gateway for compatibility with the web client, even though the gateway and the engine are now one process. /api/health is exempt from rate limiting; /api/chat/ask is capped per minute and everything else per hour.


PostgreSQL and the dialect seam

PostgreSQL is the only supported target database. Vendor-specific SQL lives behind a small seam in engine/app/db/dialects/; application code asks the dialect rather than testing for a vendor, so adding another database later is one module plus one registry entry.

Each dialect answers a small contract: identifier quoting, the statements that make a session read-only, an optional row-estimate query, and how to translate a driver error into a portable ErrorKind. The one catalog query in the codebase (pg_class, for row estimates) lives in postgres.py; structure otherwise comes from SQLAlchemy's cross-dialect Inspector.

NoSQL is planned, not implemented. engine/app/db/nosql/ holds the NoSqlDatabase interface and a MongoDB stub; it is deliberately not wired into the engine yet.

SQLite is implemented too, but only so the test suite can run without a live server — it is not offered as a target database. engine/tests/test_sqlite_end_to_end.py runs the whole data path — connect, introspect, value-index, guard, validate, execute, block writes — against a real SQLite database. If a PostgreSQL assumption creeps back into application code, that test is what fails.


Running it

Prerequisites: Docker, Python 3.12, Node 20+.

# 1. Containers: Redis, app_db, Ollama. Chroma runs in-process, so there is no vector
#    container. (core_db in docker-compose notes is external and read-only.)
docker compose up -d
docker compose ps                      # redis, app_db, ollama should report healthy

# 2. Models (one time). A local LLM and a local embedding model.
docker compose exec ollama ollama pull llama3.1
docker compose exec ollama ollama pull nomic-embed-text

# 3. Backend (from the repo root; copy .env.example to .env first and set TARGET_DATABASE_URL)
cd engine
python3 -m venv .venv
./.venv/bin/python -m pip install -r requirements.txt
./.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000

# 4. First-time setup, in another shell
curl http://127.0.0.1:8000/api/health                # expect "ok": true
curl -X POST http://127.0.0.1:8000/api/schema/refresh \
     -H 'content-type: application/json' -d '{"indexValues":true}'
cd engine && ./.venv/bin/python scripts/load_exemplars.py

# 5. Web
cd web && npm install && npm run dev                 # :3000

POST /api/schema/refresh is required before the first question and after any schema change. It reads every table, samples the distinct values of every categorical column, then builds the vector indexes. Point the browser at http://localhost:3000; the Next.js rewrite forwards /api/* to the backend.


How it gets good answers from a small local model

A small model on CPU with no GPU is the weakest part of this system. Accuracy comes from shrinking what the model has to get right.

Value indexing — the biggest win. A status column holds 'DISBURSED', not 'disbursed'. A model that has never seen the real literals writes the lowercase form, gets zero rows, and looks like it answered — silently wrong rather than visibly wrong. The refresh samples the distinct values of every categorical column and indexes them, so the question's wording can be matched to the column that actually holds it.

Schema retrieval. Retrieval keeps the prompt small: question embedding against table-name vectors and value-column vectors, plus foreign-key targets, so the right handful of tables reach the model. Below INLINE_SCHEMA_TABLE_THRESHOLD tables the whole schema is inlined, because retrieval can only lose information at that size.

Compact prompt. One line per table, capped column lists, one example. Prompt length is linear in cost, so every token saved is time saved.

Few-shot examples. Confirmed question/SQL pairs are stored and re-indexed as examples; the seed set is validated against the live database before loading so a broken example can never be learned.

Repair, don't re-roll. A query that fails to parse or validate is shown the real database error and asked to fix it. A query that contains a write is refused and never retried — see the safety model.


Safety: the four layers

  1. Guard (static). engine/app/sql/guard.py parses the statement with sqlglot and rejects anything that is not a single read-only SELECT. The guard walks the whole AST, not just the root, so a DELETE tucked inside a CTE is still caught.
  2. Read-only session. The connection is put into a read-only mode at the database level (SET TRANSACTION READ ONLY on PostgreSQL, PRAGMA query_only on SQLite), so even a query that somehow passed the guard cannot write.
  3. Limits. A statement timeout, a ${MAX_ROWS} row cap injected when the query has none, and a deliberately tiny connection pool (TARGET_DB_POOL_SIZE=2).
  4. Audit. Every attempt, including rejections, is written to query_audit in app_db.

The guard's job is to reject; the read-only session's job is to make rejection unnecessary. Neither is trusted alone.


Layout

docker-compose.yml            Redis, app_db, Ollama (Chroma runs in-process)
db/app_schema.sql             our tables (auto-applied on first boot)
db/create_readonly_role.sql   run against PostgreSQL when ready

engine/                       the one backend (FastAPI)
  app/main.py                 app assembly: lifespan, CORS, routers
  app/api/                    routes grouped by concern (health, schema, chat, rate limit)
  app/config.py               all settings, from the repo-root .env
  app/services.py             wiring: build every component once
  app/llm/                    LanguageModel / EmbeddingModel + Ollama and OpenAI providers
  app/retrieval/              VectorStore interface + Chroma implementation
  app/errors.py               portable ErrorKind + domain errors
  app/db/dialects/            THE only vendor-specific code
  app/db/connection.py        engine factory, read-only session hook
  app/db/introspection.py     SQLAlchemy Inspector -> snapshot
  app/db/value_index.py       enum-value discovery
  app/db/read_only_database.py    guarded execution
  app/schema/                 models, prompt rendering, snapshot persistence
  app/sql/guard.py            AST gate            <- security core
  app/sql/extraction.py       pulling SQL out of a model reply
  app/pipeline/               table selection, refresh, orchestration, events
  app/chart_spec.py           result shape -> chart choice
  seeds/exemplars.json        verified examples (data, not code)
  tests/                      guard, dialects, charts, SQLite end-to-end

web/                          Next.js: chat, streaming SQL, grid, charts
  lib/                        wire types, SSE parsing, conversation reducer
  app/                        panels: readiness, status badge, refresh progress
.claude/skills/maintainable-code/   the code standards this repo follows

Run the test suite any time — it needs no database and no model:

cd engine && ./.venv/bin/python -m pytest -q

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages