HomeCase studiesRead-Safe Natural-Language BI Engine and Schema-Grounded SQL...

Case study · Boston, United States

Read-Safe Natural-Language BI Engine and Schema-Grounded SQL Assistant

Natural-Language BI & Read-Safe SQL

Product managers and operations analysts frequently wait days for overworked data engineers to write routine SQL reports, yet giving generic language models direct database access risks hallucinated joins, destructive mutations, and data leaks. We engineered a natural-language business intelligence assistant using Python, SQL AST validation, and structured LLM APIs. The platform grounds every prompt against curated semantic metadata, enforces read-only SQL execution through strict AST parsing and database role sandboxing, and translates verified query results into interactive charts with full SQL lineage.

Industry
Natural-Language BI & Read-Safe SQL
Solution
A schema-grounded natural-language BI platform built with Python, SQL, and LLM APIs featuring AST-enforced read-only query validation, semantic metric definitions, and tenant-scoped execution.
Platforms
Web & API
Stack
Python · SQL · LLM APIs · FastAPI · PostgreSQL · Redis
Location
Boston, United States · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in Boston, United States. Names withheld by agreement.

Project Overview

Business teams routinely hit a bottleneck between asking an operational question and getting trustworthy numbers from the company warehouse. Backlog queues force analysts to wait on data engineers for straightforward cohort breakdowns or margin checks, while naive "chat with your database" prototypes break down the moment schemas exceed a dozen ambiguously named tables.

We engineered a read-safe natural-language BI assistant powered by Python, SQL validation engines, and structured LLM APIs. Rather than allowing language models to guess schema semantics or execute unverified strings, the platform grounds generation in a curated semantic catalog, validates every query through an Abstract Syntax Tree (AST) gate, and runs bounded read-only SQL against isolated warehouse replicas.

Where Naive Text-to-SQL Fails

Deploying conversational analytics into production enterprise schemas exposes failure modes that toy benchmarks ignore:

  • Schema bloat and ambiguous columns: Real warehouses contain hundreds of legacy tables and similarly named timestamp or status columns; stuffing full DDL schemas into prompts degrades accuracy and inflates latency.
  • Silent metric drift: Different teams define concepts like "active customer" or "net revenue" differently, causing raw SQL generation to produce conflicting numbers for the same question.
  • Unbounded execution risk: A single unindexed cross-join or missing date filter generated by an LLM can saturate shared read replicas and stall production dashboards.
  • Write and injection exposure: Relying purely on system-prompt instructions ("only generate SELECT queries") is an inadequate security boundary against prompt injection or malformed multi-statement payloads.

Architectural Strategy

We structured the assistant around deterministic verification wrapped around probabilistic generation. A Python FastAPI service acts as the sole broker between the user interface, the semantic metadata store, the LLM APIs, and target analytical databases.

When a user submits a question, the orchestrator retrieves only the relevant subset of curated table schemas, canonical metric formulas, and verified example queries. The LLM returns structured SQL alongside a plain-English explanation of its chosen joins. Before a single byte reaches the analytical database, Python parses the SQL into an AST, rewrites or rejects unsafe constructs, verifies every referenced column against catalog metadata, and checks execution cost via EXPLAIN.

Core Capabilities

  • Semantic Schema Grounding: Indexes curated table descriptions, foreign-key relationships, and canonical KPI formulas in PostgreSQL so prompts stay compact and business definitions remain consistent.
  • AST-Enforced Read-Only Guardrails: Parses generated SQL with sqlglot to block DML/DDL statements, multi-statement batches, system catalog probes, and cross-tenant table references.
  • Automated Query Repair & Clarification: Validates candidate queries with read-only EXPLAIN checks, feeding concrete engine diagnostics back into a bounded repair pass or prompting the user when a business term is ambiguous.
  • Row-Level Access & PII Masking: Binds each authenticated user's role and tenant claims directly to database session variables while omitting restricted columns from LLM context windows.
  • Transparent SQL Lineage & Visualization: Renders query results as interactive tables and charts alongside the exact executed SQL, cited metric definitions, and one-click CSV or SQL export.

Technical Architecture

A TypeScript web workspace streams user questions to a Python FastAPI orchestrator. The orchestrator resolves the user's RBAC profile, queries PostgreSQL and Redis to assemble relevant semantic table definitions and golden SQL examples, and invokes external LLM APIs using strict structured-output schemas. Returned SQL passes through the Python sqlglot AST sanitizer, an EXPLAIN cost gate, and a read-only connection pool targeting analytical replicas. Results stream back to Redis for pagination and chart rendering.

Flow: TypeScript BI Workspace → Python FastAPI Orchestrator → Semantic Catalog Lookup (PostgreSQL/Redis) → Structured LLM APIs → SQL AST Validator & EXPLAIN Gate → Read-Only Replica Pool → Interactive Charts & SQL Lineage

Separating schema retrieval, AST validation, and replica execution inside stateless Python workers makes it straightforward to support multiple SQL dialects while maintaining uniform security invariants.

Technology Stack

Category Technology detail
Backend Orchestration Python and FastAPI handling prompt assembly, schema retrieval, and query lifecycle APIs
Query Execution & Safety SQL AST parsing (sqlglot) and isolated read-only database connection pools
Model Inference LLM APIs configured with structured JSON outputs for SQL generation and repair
Semantic & Metadata Store PostgreSQL storing curated table descriptions, verified join paths, and audit logs
Schema & Result Cache Redis caching semantic embeddings, execution plans, and paginated result sets
Analytics Workspace TypeScript frontend displaying conversational threads, editable SQL, and chart outputs
Read-Replica Targets PostgreSQL and warehouse read replicas bound to session-level RBAC and query timeouts
Observability OpenTelemetry tracing prompt tokens, AST rejection reasons, and warehouse execution times

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
Balancing schema completeness against LLM context limits and accuracy Built a semantic retrieval step that injects only top-ranked tables, verified join edges, and canonical metrics rather than raw database DDLs; requires lightweight curation during onboarding while dramatically cutting join errors.
Preventing prompt-injected or malformed SQL from reaching the database Enforced deterministic AST allow-listing via sqlglot paired with read-only replica credentials and statement_timeout; adds negligible pre-flight latency while eliminating reliance on LLM prompt compliance for security.
Handling follow-up questions ("now break that down by region") without losing SQL precision Carried forward the previously validated AST and user-approved assumptions as explicit state in PostgreSQL rather than summarizing prior prose; ensures drill-downs mutate filters deterministically.
Protecting analytical replicas from expensive exploratory scans Intercepted queries lacking partition filters or limits with EXPLAIN cost thresholds and mandatory LIMIT injection; occasionally requires users to narrow date ranges in exchange for predictable warehouse stability.

Security & Reliability

Enterprise trust in an AI SQL assistant depends on proving that neither the model nor a malicious prompt can exfiltrate restricted records or degrade database availability. First, the semantic catalog explicitly excludes sensitive PII columns and internal system tables, so raw credentials or restricted attributes never enter third-party LLM API payloads—only schema metadata and sanitized error messages leave the network boundary.

Second, every database connection runs over TLS against dedicated read-only replicas using per-request session variables that trigger PostgreSQL row-level security policies. AST verification rejects stacked statements, COPY commands, and unsafe UDF calls before execution. Full audit logs in PostgreSQL capture every user prompt, generated SQL AST, execution duration, and row count for compliance review.

Performance & Scale

Interactive BI collapses if users wait half a minute for every follow-up chart. FastAPI caches semantic schema embeddings and verified few-shot SQL templates in Redis, eliminating repeated metadata queries on warm sessions.

When a user pivots or sorts an existing dataset in the TypeScript workspace, pagination and lightweight aggregations read directly from bounded result caches in Redis rather than re-invoking the LLM APIs. Meanwhile, asynchronous worker pools handle slow multi-step analytical queries with progressive streaming updates and automatic cancellation if a user closes the session.

Operational Outcomes

Introducing a governed, schema-grounded Python and SQL query assistant changed how non-technical teams and data engineers collaborate:

  • Self-serve operational reporting: Product, finance, and operations staff answer ad-hoc questions directly without waiting in engineering ticket queues.
  • Verifiable analytical trust: Showing the generated SQL, semantic metric definitions, and table lineage alongside every chart lets stakeholders audit numbers before sharing them.
  • Protected database infrastructure: AST validation, EXPLAIN cost gates, and read-replica timeouts eliminate runaway AI-generated scans.
  • Compounding semantic quality: Data engineers review flagged ambiguities and promote validated user queries into the golden catalog, continuously improving accuracy across the organization.

01 — Questions

asked about this kind of project

How do you guarantee the AI assistant can never run DROP, UPDATE, or unauthorized queries against production?

Safety is enforced in two independent layers: Python parses every generated SQL statement into an Abstract Syntax Tree (sqlglot) to reject non-SELECT statements and disallowed functions before execution, while the target warehouse connection runs under a strictly read-only role with no write privileges.

How does the system prevent hallucinated table names, columns, or incorrect metric definitions?

Instead of dumping an entire raw warehouse DDL into the prompt, FastAPI retrieves only relevant tables and verified business definitions from a curated semantic layer. Column names and join keys are cross-checked against the live catalog during AST validation prior to running SQL.

How are row-level permissions and sensitive PII columns protected when non-technical users ask questions?

Every query executes with the authenticated user's session context bound to database row-level security policies and column-masking views. Sensitive PII fields are excluded from the semantic catalog exposed to the LLM APIs entirely, preventing both exposure in prompts and retrieval in results.

What happens when the generated SQL triggers a syntax error or misses an edge case in a complex join?

An automated self-correction loop captures the database engine's read-only EXPLAIN or syntax diagnostic, passes the error alongside the failing AST node back to the LLM APIs for a bounded number of repair attempts, and surfaces transparent assumptions if ambiguity remains.

Why include an editable SQL inspection pane instead of hiding the generated query behind a chat bubble?

Analysts and data teams cannot trust opaque numbers in board meetings. Showing the exact SQL, cited metric definitions, and table lineage alongside every chart lets power users verify logic immediately or hand off edge cases cleanly to analytics engineers.

How do you keep natural-language queries from triggering expensive full-table scans on large warehouses?

Before executing SQL, the Python validator runs EXPLAIN to inspect estimated scan cost and row counts, injects mandatory LIMIT caps when absent, enforces strict statement timeouts, and caches repeated conversational follow-ups in Redis.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.