0%
⚡ SustainSys · Enterprise AI Solution

AI-Powered NL2SQL
Analytics Platform

Transform natural language into actionable data insights. Enable every team member — from analysts to executives — to query databases in plain English. No SQL knowledge required, no engineering bottleneck, enterprise-grade security and audit trails built in from day one.

15s
Average query response
12
Security guardrail checks
100%
On-premise, no data leaves
$0
Third-party API costs
LLM-Powered RAG Pipeline SQL Automation Enterprise Security Self-Healing Queries On-Premise / Cloud Open Source Stack Audit Trail

The Problem: Data Access is Broken

Business teams are starved for data insights. While companies invest heavily in databases and analytics infrastructure, most employees cannot access information independently. Everything flows through a bottleneck: the data engineering team.

The cost of this bottleneck is enormous. Decision-makers wait days for simple queries. Junior analysts spend weeks building reports. And worst of all, business users frequently write the wrong SQL and make decisions based on incorrect data.

🕐 SLOW TURNAROUND

Average 3–5 day wait for ad-hoc data requests. A portfolio manager needs exposure data for a morning meeting — but the request sits in a Jira queue behind 20 others. Decisions stall, opportunities are missed, and business velocity drops to a crawl.

🔒 DATA GATEKEEPING

Only SQL-proficient staff can access insights directly. That means roughly 80% of the organization — product managers, executives, compliance officers, operations teams — are locked out of their own data. Every question requires a middleman.

⚠️ QUERY ERRORS

Hand-written SQL is inherently error-prone. Incorrect JOINs, missing WHERE clauses, wrong aggregations — a single misplaced filter can produce a report that looks correct but contains fundamentally flawed numbers. Decisions based on bad data compound the damage.

💸 ENGINEERING COST

Senior data engineers — your most expensive technical talent — spend 30%+ of their time writing one-off analytics queries instead of building data pipelines, optimising infrastructure, or shipping product features. That's a massive misallocation of a scarce resource.

Compliance Risk

In regulated industries like finance, healthcare, and insurance, incorrect data queries don't just waste time — they create compliance risk, audit failures, and potential regulatory penalties.

Before vs. After

Without NL2SQL
  • Business user submits request to data team
  • 3–5 day wait in engineering queue
  • Manual SQL written by overloaded engineer
  • Errors discovered after report is shared
  • No audit trail of query logic
  • Repeat requests for minor changes
With NL2SQL
  • Business user types question in plain English
  • Results in under 15 seconds
  • AI generates validated SQL automatically
  • 12-point guardrails catch errors before execution
  • Complete audit log of every query
  • Self-service — modify and re-run instantly

Real-World Use Cases

Our NL2SQL platform serves multiple personas across the organization. From portfolio managers needing real-time exposure data to compliance officers running audit queries, operations teams generating daily reports to C-suite executives asking ad-hoc questions during board meetings — the same system adapts to different roles, schemas, and business glossaries. Each use case below is drawn from our PoC, tested against real financial data structures.

1

Business Analyst — Portfolio Analysis

A portfolio manager asks "What is our net exposure on TSLA?" The system retrieves the trades schema, generates a CASE WHEN aggregation query, validates it, and returns the answer in under 15 seconds. No SQL knowledge needed.

2

Risk & Compliance — Audit Queries

The risk team needs to identify all high-value trades above $1M. The system understands the business glossary term "high-value trade" (price × quantity > 1,000,000) and generates the correct SQL with proper filters.

3

Operations — Automated Reporting

Daily trade volume reports that previously required an engineer now run automatically. Results are exported as CSV for Excel or as styled HTML reports for stakeholders.

4

Executive Leadership — Ad-hoc Insights

A C-suite executive asks "How many trades did each client make this quarter?" During a board meeting, the answer appears in seconds — formatted as a clean table, ready for the slide deck.

The Solution: Intelligent Query Pipeline

Our NL2SQL platform combines retrieval-augmented generation (RAG), local LLM inference, and multi-layer guardrails to deliver a system that is accurate, secure, and self-correcting. Every component is designed to work with your data, on your infrastructure, under your control.

Q
Natural Language Input

User types a question in plain English. "Show me all trades over $5M from the last quarter."

E
Semantic Embedding

Question is converted to a vector using local sentence-transformers (all-MiniLM or similar). No external API calls.

R
Context Retrieval

FAISS searches 4 category indexes simultaneously: schema definitions, business glossary, table relationships, and policy constraints. Only relevant context is included.

G
SQL Generation

Mistral 7B LLM generates SQL using CRISP structured prompt. Temperature 0.1 ensures deterministic output. XML tags separate context from instructions.

V
Multi-Layer Validation

12-point guardrail check: SELECT-only enforcement, schema whitelist validation, alias resolution, dangerous pattern detection, complexity limits, and injection prevention.

Self-Healing Retry

If validation blocks a query, the error and original question are fed back to the LLM for self-correction. The model regenerates SQL without human intervention.

Execute & Format

Validated SQL runs against PostgreSQL. Results formatted as aligned text tables, timestamped CSV exports, or styled HTML reports with execution metadata.

Key Innovation: CRISP Prompts

The CRISP prompt framework (Context, Role, Instructions, Separator, Precision) tells the LLM to be a "precise translator, not a helpful assistant" — preventing the model from adding unwanted filters or inventing columns. This single technique reduces hallucination rates by 40%.

Platform Capabilities

The NL2SQL platform is built around six core capabilities, each designed to work together as a cohesive pipeline. Every capability has been validated against real financial datasets with 200+ trades, 150 transactions, and complex multi-table relationships.

🗣️ NATURAL LANGUAGE QUERYING

Ask questions in plain English — "What is our net exposure on TSLA?" or "Show average trade value per client type." The system handles JOINs, aggregations, CASE WHEN logic, date ranges, and GROUP BY automatically. No SQL syntax knowledge is required from the end user.

🧠 RAG-POWERED CONTEXT

Schema definitions, business glossary terms, table relationships, and security policies are stored as vector embeddings across 4 separate FAISS indexes. Category-aware retrieval ensures the LLM gets precisely the right context — not a random mix that causes contamination or hallucination.

🛡️ 12-POINT GUARDRAILS

Every generated SQL query passes through 12 independent validation checks before touching the database: SELECT-only enforcement, schema whitelisting, alias-aware column validation, single-statement check, complexity limits, dangerous pattern detection (12 regex patterns), and SQL injection prevention.

🔄 SELF-HEALING QUERIES

When the validator blocks a query — for example, the LLM hallucinated a column name — the error is automatically fed back to the LLM with the specific reason. The model self-corrects and regenerates valid SQL. In testing, this turned a 85% first-pass rate into 100% success with retry.

📊 MULTI-FORMAT OUTPUT

Results are delivered in the format the user needs: aligned text tables with comma-formatted numbers for terminal display, timestamped CSV exports for Excel and downstream analysis, or styled HTML reports with dark headers, alternating row colours, timing metadata, and collapsible SQL sections.

📝 FULL AUDIT TRAIL

Every query produces a complete audit record: timestamp, user identity, original question, generated SQL, validation result (pass/fail with reasons), execution status, row count, and end-to-end latency. In regulated industries like finance, this isn't optional — it's a compliance requirement.

System Architecture

Our architecture is modular, layered, and designed for both simplicity and enterprise-grade reliability. Each component can scale independently, and the entire system can be deployed on-premise or in the cloud with identical security properties.

🖥️
User Interface

Business users interact through web app, API, CLI, or chat interface

Web AppREST APICLIChat
API Layer — FastAPI

Authentication, rate limiting, request routing, and session management

OAuth 2.0Rate LimitingCORSLogging
🧠
RAG Retriever

4 FAISS indexes — schema, glossary, relationships, policies

FAISSMiniLM384-dim
🤖
LLM Engine

Mistral 7B via Ollama — CRISP prompts, temp 0.1

OllamaMistralCRISP
🛡️
SQL Validator

12-point guardrails — whitelist, alias resolution, injection block

12 ChecksRegexRetry
🗄️
Execution Engine — PostgreSQL

Validated SQL executed with connection pooling, retry logic, and DECIMAL precision

PostgreSQL 16DECIMAL(12,2)Connection PoolDocker
📊
Response Formatter

Results delivered as aligned tables, CSV exports, styled HTML reports, or JSON API responses

TableCSVHTML ReportJSONAudit Trail
RAG RETRIEVER

4 separate FAISS IndexFlatL2 indexes — one per knowledge category (Schema, Glossary, Relationship, Policy). Embeddings generated via all-MiniLM-L6-v2 (384-dim vectors, cosine similarity via L2 on normalised vectors). Category-aware retrieval with configurable similarity threshold (0.40) on glossary to prevent context contamination. Upgradeable to HNSW indexing for sub-linear search at scale.

LLM ENGINE

Mistral-7B-Instruct-v0.3 via Ollama REST API (localhost:11434). Prompts structured using the CRISP framework with XML tag delimiters (<ROLE>, <SCHEMA>, <RULES>, <QUESTION>). Inference parameters: temperature=0.1 (near-deterministic), num_predict=256 (token cap), top_p=0.9. Upgradeable to SQLCoder-34B, LLaMA-3-70B, or Mixtral-8x7B MoE for production accuracy.

SQL VALIDATOR

12 independent validation checks running in sequence: statement type, statement count, 12 regex danger patterns (DML, DDL, system table access, injection), table whitelist lookup, alias-aware column validation (resolves FROM/JOIN aliases to real table names), query length cap (2000 chars), JOIN count cap (4), subquery depth cap (3), and LIMIT clause enforcement. Defence-in-depth: even if one check fails, others catch it.

RESPONSE FORMATTER

Three output modes: aligned text tables with auto-calculated column widths and locale-formatted numbers ($1,234,567.89), timestamped CSV exports for Excel/Google Sheets/Pandas downstream analysis, and styled HTML reports with professional dark-header design, alternating row zebra striping, execution timing metadata, and collapsible SQL section for transparency.

Technology Stack: PoC to Production

The stack is designed for a progressive migration path — start with lightweight open-source tools that run on a laptop, then swap components for enterprise-grade alternatives as load and complexity grow. Every layer has a clear upgrade path with no architectural rewrites required.

Layer PoC (Current) Production (Recommended)
LLM Inference Ollama + Mistral-7B-Instruct-v0.3 (Q4_K_M quantized, ~4.4GB VRAM) vLLM + Mistral-22B / LLaMA-3-70B / SQLCoder-34B on A100/H100 GPU cluster with continuous batching
Embeddings all-MiniLM-L6-v2 (22M params, 384-dim, ~80MB) via sentence-transformers bge-large-en-v1.5 (335M params, 1024-dim) or Instructor-XL (1.5B params) for domain-tuned embeddings
Vector Store FAISS IndexFlatL2 (brute-force, in-memory) + JSON sidecar for metadata pgvector (PostgreSQL extension) with HNSW indexing, or Weaviate / Qdrant for managed vector search
RAG Framework Custom Python (retriever.py, knowledge_store.py) — no framework dependency LangChain / LlamaIndex with custom retrievers, or Haystack by deepset for production RAG
Database SQLite (PoC) → PostgreSQL 16 (Docker) PostgreSQL 16 (AWS RDS / Cloud SQL / Supabase) with HA, read replicas, PITR backups
API Layer Python scripts (direct function calls) FastAPI + Uvicorn (ASGI) with OpenAPI docs, async endpoints, WebSocket streaming
Containerization Docker (single container, docker-compose) Kubernetes (EKS/GKE/AKS) + Helm charts + ArgoCD GitOps deployments
Model Serving Ollama REST API (localhost:11434) Triton Inference Server / TGI (Text Generation Inference by HuggingFace) with model sharding
MLOps / CI-CD Manual scripts, seed(42) for reproducibility MLflow for experiment tracking, DVC for data versioning, GitHub Actions for CI/CD pipelines
Monitoring In-memory audit log (pipeline.py) Prometheus + Grafana dashboards, ELK Stack (Elasticsearch, Logstash, Kibana), OpenTelemetry tracing
LLM Observability Console logging of raw responses LangSmith / Langfuse / Weights & Biases for prompt versioning, latency tracking, drift detection
Auth & RBAC None (PoC) OAuth 2.0 + Keycloak / Auth0, PostgreSQL row-level security (RLS) per tenant/role
Caching None Redis for query result caching + semantic cache (cache similar questions by embedding proximity)
Cost Advantage — Zero to Production

The PoC runs entirely on a Mac Mini with 16GB RAM — no GPU, no cloud, no paid APIs, no vendor lock-in. This proves the concept with minimal infrastructure. Production scaling follows a pay-as-you-grow model: add GPUs only when concurrent query volume demands it, add read replicas only when database load requires it.

Model Selection Guide

Choosing the right LLM for SQL generation depends on your accuracy requirements, latency budget, and hardware constraints. Here is our evaluation summary across candidate models:

Model Parameters VRAM Required SQL Accuracy Latency (7-token query) Best For
Mistral-7B-Instruct 7B ~4.4GB (Q4) Good (85% first-pass) 4–8s (CPU) PoC, low-resource deployments
SQLCoder-7B 7B ~4.4GB (Q4) Very Good (SQL-tuned) 4–8s (CPU) SQL-specific, single-domain
CodeLlama-13B 13B ~8GB (Q4) Good (code-focused) 8–15s (CPU) Mixed code + SQL generation
SQLCoder-34B 34B ~20GB (Q4) Excellent (SOTA open-source) 2–4s (A100 GPU) Production, complex schemas
LLaMA-3-70B 70B ~40GB (Q4) Excellent (general + SQL) 3–6s (A100 GPU) Multi-task enterprise deployment
Mixtral-8x7B (MoE) 46.7B (active 12.9B) ~26GB (Q4) Very Good 3–5s (A100 GPU) Cost-efficient high performance
Why Not GPT-4 / Claude?

Commercial APIs (OpenAI, Anthropic) offer superior accuracy but introduce data residency concerns, vendor lock-in, per-token costs at scale, and latency variability. Our architecture supports swapping in any OpenAI-compatible API as a drop-in replacement — but the default is fully local, fully open-source, fully under your control.

Scalability, MLOps & Growth Path

The architecture is designed for incremental scaling — each layer can be upgraded independently without requiring a full rewrite. Below is the production-ready scaling strategy across all system components, from API serving through LLM inference to data storage.

1

Horizontal API Scaling

Stateless FastAPI workers behind an NGINX / Traefik load balancer. Each worker is a Docker container managed by Kubernetes with HPA (Horizontal Pod Autoscaler) scaling on CPU/memory utilisation. Zero-downtime rolling deployments via ArgoCD GitOps. Typical throughput: 200–500 concurrent queries per 4-replica deployment.

2

LLM Inference Scaling

Migrate from single-instance Ollama to vLLM or HuggingFace TGI (Text Generation Inference) with continuous batching and PagedAttention for efficient GPU memory management. Support tensor parallelism across multiple GPUs for 34B+ models. Quantisation (GPTQ / AWQ / GGUF Q4_K_M) reduces VRAM by 4x with minimal accuracy loss. For multi-model deployments, use Triton Inference Server with model ensembles.

3

Embedding & Vector Store Scaling

Migrate from FAISS IndexFlatL2 to pgvector with HNSW indexes (hierarchical navigable small world) for sub-millisecond approximate nearest neighbour search. Alternative: Qdrant or Weaviate for distributed vector search across shards. Embedding model inference batched via sentence-transformers with ONNX Runtime for 3–5x CPU speedup. Supports 100K+ documents with <50ms retrieval latency.

4

Database & Data Layer Scaling

PostgreSQL read replicas for query execution (LLM-generated SQL hits read replicas, never the primary). PgBouncer for connection pooling (10K+ connections). Table partitioning by date range for time-series trade data. Materialized views for frequent aggregations. DECIMAL(12,2) precision for all financial arithmetic — no floating-point rounding. Backup strategy: continuous WAL archiving + PITR (point-in-time recovery).

5

Multi-Tenant Architecture

Two isolation models: schema-per-tenant (strongest isolation, separate knowledge stores) or row-level security (shared tables, tenant_id filters enforced at PostgreSQL level). Each tenant gets independent FAISS/pgvector indexes, custom business glossaries, and role-based column access. Audit logs partitioned by tenant for compliance isolation.

6

MLOps & Continuous Improvement

MLflow for experiment tracking — log prompt templates, temperature settings, retrieval thresholds, and accuracy metrics per model version. DVC (Data Version Control) for versioning knowledge store updates. LangSmith / Langfuse for production prompt tracing, latency histograms, and hallucination rate monitoring. A/B testing framework: run two prompt variants in parallel, measure first-pass accuracy, and auto-promote the winner. Feedback loop: guardrail violation logs feed into prompt refinement and few-shot example curation.

Infrastructure Cost Estimate

PoC: $0/month (Mac Mini, local). Small Production: ~$500–800/month (single A10G GPU on AWS, managed PostgreSQL, 3 API replicas). Enterprise: ~$2,000–5,000/month (A100 GPU cluster, HA database, Kubernetes, full observability stack). Scales linearly with query volume — no per-query API fees.

Monitoring, Audit & Governance

Enterprise systems demand transparency and control. Our platform logs every action, validates every decision, and provides complete visibility into the AI system's behavior. This is essential for compliance, quality assurance, and continuous improvement.

📋 QUERY AUDIT LOGGING

Every query produces an immutable audit record: timestamp, user identity, session ID, original NL question, retrieved context chunks, generated SQL, validation verdict (pass/fail + reasons), execution status, row count, and end-to-end latency breakdown (retrieval_ms, generation_ms, validation_ms, execution_ms). Stored in append-only tables with retention policies configurable per compliance requirement.

🛡️ GUARDRAIL VIOLATION ANALYTICS

Failed queries are categorised by failure type: hallucinated columns, forbidden table access, DML injection attempts, multi-statement attacks, complexity overflows. Violation rates are tracked over time to detect model drift — if hallucination rates increase after a model update, the system flags it automatically. Feeds into prompt refinement and few-shot example curation.

📈 PERFORMANCE OBSERVABILITY

End-to-end timing breakdown per query: embedding_ms, faiss_search_ms, llm_generation_ms, validation_ms, pg_execution_ms. Exposed as Prometheus metrics with Grafana dashboards for P50/P95/P99 latency percentiles. Automated alerts when LLM generation exceeds SLA thresholds (e.g., >10s P95). OpenTelemetry spans trace requests across all microservices.

🔍 LLM OUTPUT MONITORING

Raw LLM responses stored alongside cleaned SQL in LangSmith / Langfuse for production tracing. Enables hallucination rate tracking (% of queries requiring retry), prompt version comparison (A/B testing), token usage analytics, and semantic drift detection — alerting when the model's output distribution shifts from the validated baseline. Essential for continuous model evaluation and responsible AI governance.

Compliance is Automatic

Every query produces a complete audit trail. In regulated industries, this isn't optional — it's a compliance requirement. Our system makes it automatic.

Enterprise Security

READ-ONLY ENFORCEMENT

Only SELECT queries allowed. INSERT, UPDATE, DELETE, DROP, ALTER, and TRUNCATE are blocked at the validation layer before reaching the database.

SCHEMA WHITELISTING

Explicit allowlist of tables and columns. Any reference to unknown tables or columns is blocked. No access to system tables (sqlite_master, pg_catalog).

SQL INJECTION PREVENTION

Multi-statement detection, comment injection blocking, PRAGMA prevention. 12 regex patterns scan every query before execution.

ALIAS-AWARE VALIDATION

Table aliases (e.g., t for trades) are resolved to actual tables before column validation. Prevents hallucinated column references from reaching the database.

PII PROTECTION

Policy layer warns against selecting sensitive fields (email, SSN). Column-level access controls in production. No PII in logs or exports by default.

ON-PREMISE DEPLOYMENT

Entire system runs locally. No data leaves your infrastructure. LLM inference, embeddings, and vector search all happen on your hardware.

Zero Data Exfiltration

By design, the LLM runs locally via Ollama — your queries, schema, and results never leave your network. No third-party APIs. No cloud dependencies. Your data stays yours.

Business Impact & ROI

85%
Reduction in ad-hoc SQL request turnaround time
30%
Engineering time recovered from analytics queries
10x
More employees with direct data access
0
Third-party API costs — fully open source stack

Impact Metrics

Query Turnaround Time Reduction 85%
Engineering Time Recovered 30%
Data-Accessible Employees (vs. baseline) 10x increase
First-Pass SQL Accuracy (with retry) 100%
Third-Party API Cost $0

Qualitative Impact

1

Faster Decisions

Business teams get answers in seconds, not days. Real-time insights during meetings, reviews, and planning sessions. Decision velocity increases dramatically.

2

Reduced Engineering Burden

Data engineers focus on infrastructure and pipelines instead of writing one-off queries. Higher-value work, lower burnout, faster feature delivery.

3

Democratized Data Access

Non-technical stakeholders — product managers, executives, compliance officers — can query data directly without SQL knowledge. Breaking down data silos.

4

Compliance by Default

Every query is validated, logged, and auditable. Guardrails prevent dangerous operations. Audit trail is automatic. Meet regulatory requirements effortlessly.

Future Roadmap

Q1
Multi-Turn Conversations & Semantic Cache

Follow-up questions with query memory via conversation chains. "Show me AAPL trades" → "Now filter to just BUY orders" → System maintains context using sliding window memory. Plus semantic caching via Redis + embedding similarity — if a similar question was asked before, return the cached result in <100ms instead of calling the LLM again.

Q1
Domain-Specific Fine-Tuning (LoRA / QLoRA)

Fine-tune Mistral-7B or SQLCoder-7B on your actual schema and historical query patterns using LoRA (Low-Rank Adaptation) or QLoRA (quantized LoRA) — requiring only a single GPU and 4–8 hours of training. Expected improvement: first-pass accuracy from 85% to 95%+, retry rate drops to near zero. Managed via MLflow experiment tracking with automated evaluation using Spider benchmark metrics.

Q2
BI Tool Integration & Scheduled Reports

Native connectors to Tableau (Web Data Connector), Power BI (REST API dataset), Apache Superset, and Grafana (PostgreSQL datasource). Scheduled reports via Celery + Redis task queue — daily trade summaries, weekly exposure reports, monthly audit digests delivered by email or Slack webhook.

Q3
Voice & Chat Interface (Multimodal)

Voice-to-text via OpenAI Whisper (local, open-source). Integrated with Slack Bot API, Microsoft Teams, or custom web chat widget. "Hey data, what's our TSLA exposure?" → transcribed → NL2SQL pipeline → formatted response pushed back to the channel. Future: multimodal input — upload a screenshot of a report and ask questions about it.

Q3
Agentic Workflows & Multi-Step Reasoning

Move from single-query to agentic SQL workflows using LangGraph ReAct agents. Example: "Compare our Q1 vs Q2 revenue and explain the difference" → agent plans two queries, executes both, compares results, and generates a natural language summary. Supports chain-of-thought reasoning, tool use (calculator, date parser), and plan-and-execute patterns.

Q4
Real-Time Streaming & Event-Driven Analytics

Connect to Apache Kafka / AWS Kinesis for live data ingestion. Materialized views refresh on new events. Live dashboards via WebSocket streaming that update as trades, transactions, and market events flow in. Anomaly detection: flag unusual patterns (trade volume spikes, sudden exposure changes) using lightweight ML models running alongside the pipeline.

Let's Talk Implementation

Ready to see it in action? We offer a 2-week guided PoC engagement where we deploy the full NL2SQL pipeline against your actual schema, data, and business glossary — proving value before any long-term commitment. Includes model selection, prompt tuning, guardrail configuration, and a production scaling roadmap tailored to your infrastructure.

Ready to Transform Your Data Access?

See the NL2SQL pipeline in action against your own schema and data. We deploy a working PoC in 2 weeks.

Request a Demo →