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
sqlglotto 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
EXPLAINchecks, 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,
EXPLAINcost 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.