How varunmundas-de-stack/convai-nl2sql works
1. System boundary
This repo is a full-stack NL-to-SQL analytics platform. The main runtime path is: browser UI → FastAPI backend → Cube.js semantic layer → PostgreSQL warehouse → JSON response back to the UI. Around that core are supporting subsystems for authentication, clarification, insight generation, caching/session memory, RLHF feedback, and ETL ingestion.
2. Frontend surface
The frontend is a Next.js 14 app under frontend/src/app with three primary user experiences: the conversational entry point (/), a KPI dashboard (/dashboard), and an insights view (/insights plus detail pages). The React components in frontend/src/components render chat bubbles, clarification prompts, charts, tables, and feedback controls. frontend/src/services/api.ts is the single HTTP client boundary to the backend.
3. Backend entry points
The FastAPI app in backend/app/main.py is the main integration layer. It exposes routes for query execution, clarification continuation, retries, catalog discovery, insights, dashboard KPIs, auth, and RLHF/feedback. This is the place where request-level concerns meet the business pipeline.
4. Security and tenant isolation
Authentication is JWT-based (backend/app/security/auth.py), with backend-side token issuance and request context handling. A second, Cube-specific JWT is minted per request so the browser does not directly hold Cube credentials. Row-level access control is enforced at the semantic-query layer via Cube.js query rewriting, driven by user role/hierarchy metadata stored in the backend security modules.
5. Core NL2SQL orchestration
The main query flow is implemented as a staged pipeline in backend/app/pipeline and supported by the DSPy-based agent stack in backend/app/dspy_pipeline. A user question is turned into a structured Query Context Object, merged with any prior session context, optionally paused for clarification, validated against the catalog and RBAC rules, converted into a Cube query, executed, then summarized into a narrative plus chart recommendation.
6. Intent understanding and query normalization
The backend/app/services/intent package and the DSPy agent modules cover extraction, decomposition, classification, scope handling, dimension selection, metric selection, time-window interpretation, and validation. The important architectural boundary here is that free-form language is normalized into a constrained internal schema before any warehouse query is allowed.
7. Semantic query execution
backend/app/services/cube turns validated intent into Cube.js load queries. Cube.js itself is the semantic/data-access boundary: the model in cube/model/cubes defines facts and dimensions, and Cube translates the request into optimized SQL against PostgreSQL. This keeps the backend from constructing raw SQL directly for the main analytics path.
8. Data warehouse and semantic model
PostgreSQL is the system of record for analytics data. The cube/data scripts initialize and seed the warehouse, while cube/model defines the business semantics over fact tables such as primary and secondary sales plus shared dimension tables. The Cube layer sits on top of this warehouse and is the main contract for analytics consumers.
9. State, caching, and conversational memory
Redis is used for session state and conversational context, enabling follow-up questions to inherit prior intent. The backend also has cache/memory-related services (cache_manager, redis_session, memory_manager) to avoid recomputing common queries and to preserve short-term user context. The README describes a layered cache strategy, which is important because it changes the runtime path for repeated questions.
10. Insights and proactive analytics
There is a separate insights subsystem under backend/app/insights_router.py, backend/app/insight_generator.py, and backend/app/services/insights. It appears to generate role-aware alerts and narrative insights from the warehouse, independent of the interactive chat flow. The backend/app/intel package adds scheduled, stepwise processing for profile/watch/execute/detect/narrate/store workflows, which suggests background intelligence jobs rather than user-triggered queries.
11. RLHF and feedback loop
The backend/app/rlhf package is a distinct feedback/experimentation loop. It includes feedback collection, prompt management, A/B routing, scheduling, and a SQLite-backed store (backend/rlhf.db). This subsystem sits beside the main query pipeline and is used to refine prompts and responses over time.
12. ETL and data onboarding
New source data is ingested through backend/etl/cpg_etl.py and the Dockerized watch-mode ETL service described in the README. CSV files dropped into a watched directory are upserted into dimension and fact tables, then archived. This is the data onboarding boundary that feeds the warehouse used by Cube.js and the analytics pipeline.
13. Infrastructure and deployment
The app is containerized with Docker Compose, with separate services for frontend, backend, Cube.js, PostgreSQL, Redis, and the ETL watcher. The repo also includes AWS deployment scripts and Nginx config under aws-deploy, so the deployment topology is a multi-service single-host setup rather than a serverless architecture.
14. Testing and contract protection
The backend test suite includes API end-to-end tests, catalog contract tests, clarification tests, intent validation, and data sanity checks. That indicates the repo relies heavily on schema/catalog correctness and pipeline behavior stability, which are critical architectural contracts for a natural-language analytics system.
Main entry points: main.py FastAPI app · runner.py NL2SQL pipeline · docker-compose.yml Deployment · app App shell
Components 22
Frontend
Next.js user interfaces and browser-side state.
- App shell · Top-level Next.js routes and layout for the conversational analytics UI.
frontend/src/app - Chat UI · Conversation entry point, message rendering, clarification prompts, retries, and feedback controls.
frontend/src/components - Dashboard · KPI-focused analytics surface for summary metrics and charts.
frontend/src/app/dashboard/page.tsx - Insights views · Insights list and detail pages for proactive analytics content.
frontend/src/app/insights - RLHF page · Frontend surface for feedback and experimentation workflows.
frontend/src/app/rlhf/page.tsx - API client · Single browser-to-backend HTTP boundary.
frontend/src/services/api.ts - Conversation state · Browser-side conversation state and parsing helpers.
frontend/src/state/conversation.ts
Backend
FastAPI orchestration, security, analytics, insights, and feedback services.
- FastAPI app · Main backend integration layer for query execution, clarification, insights, dashboards, auth, and feedback routes.
backend/app/main.py - Security · JWT auth, request context, and tenant metadata handling.
backend/app/security/auth.py - NL2SQL pipeline · Staged query orchestration from question to validated query context and response.
backend/app/pipeline/runner.py - Intent stack · Extraction, classification, decomposition, normalization, and validation of user questions.
backend/app/services/intent - QCO store · Persistent query context and state management across follow-up turns.
backend/app/pipeline/qco_store.py - Cube adapter · Builds Cube load queries from validated intent and period planning.
backend/app/services/cube/cube_query_builder.py - Memory & cache · Redis session handling, cache manager, and short-term conversational memory.
backend/app/services/cache_manager.py - Insights engine · Role-aware insight generation, refinement, and visual spec construction.
backend/app/services/insights/insight_engine.py - RLHF loop · Feedback collection, prompt management, routing, A/B logic, and refinement.
backend/app/rlhf/router.py - Intel jobs · Scheduled stepwise profile, watch, execute, detect, narrate, and store workflows.
backend/app/intel/scheduler.py - LLM service · Backend wrapper around LLM calls used by query, insight, and refinement flows.
backend/app/llm/service.py
Analytics Stack
Cube semantic layer and PostgreSQL warehouse.
- Cube model · Cube.js dimensions, facts, and views defining the analytics contract.
cube/model/cubes - PostgreSQL · System of record for analytics facts and dimensions.
cube/data
Infrastructure
ETL, deployment, and runtime support.
- ETL ingest · CSV/watch-mode ingestion and warehouse loading for new source data.
backend/etl/cpg_etl.py - Deployment · Compose-based multi-service deployment and AWS/Nginx packaging.
docker-compose.yml
Connections 34
- App shell → Chat UI: renders · Top-level routes compose the conversational experience.
- App shell → Dashboard: renders · Dashboard route surfaces KPI analytics.
- App shell → Insights views: renders · Insights routes show proactive analytics content.
- App shell → RLHF page: renders · RLHF route exposes feedback workflows.
- Chat UI → API client: calls · All browser requests go through the shared API client.
- Dashboard → API client: calls · Dashboard data is fetched from the backend.
- Insights views → API client: calls · Insights pages fetch backend-generated insight data.
- RLHF page → API client: calls · Feedback interactions are submitted to backend routes.
- Chat UI → Conversation state: uses · Conversation state supports follow-up questions and clarification.
- API client → FastAPI app: HTTP · Browser traffic terminates at the FastAPI application.
- FastAPI app → Security: authenticates · Request handling is protected by JWT and tenant context.
- FastAPI app → NL2SQL pipeline: orchestrates · Main NL2SQL requests enter the staged query pipeline.
- FastAPI app → Insights engine: serves · Insight routes produce proactive analytics responses.
- FastAPI app → RLHF loop: routes · Feedback and experimentation endpoints are separated from core query flow.
- FastAPI app → Intel jobs: schedules · Background intelligence workflows are exposed through the backend.
- NL2SQL pipeline → Intent stack: normalizes · Free-form language is converted into constrained intent structures.
- NL2SQL pipeline → QCO store: persists · Structured query context is stored across turns.
- NL2SQL pipeline → Memory & cache: reuses · Session and cache layers shortcut repeated work and preserve context.
- NL2SQL pipeline → Cube adapter: queries · Validated intent is converted into semantic Cube queries.
- NL2SQL pipeline → LLM service: summarizes · LLM calls generate narratives and clarifications.
- Intent stack → LLM service: interprets · LLM-backed agents support classification and validation steps.
- Cube adapter → Cube model: targets · Cube queries execute against the semantic model.
- Cube model → PostgreSQL: reads · Cube translates semantic requests into SQL over PostgreSQL.
- ETL ingest → PostgreSQL: loads · ETL populates the warehouse with source data and dimensions.
- Insights engine → LLM service: refines · Narratives and visual specifications are generated and refined with model assistance.
- Insights engine → Cube adapter: reads · Insights are computed from warehouse-backed semantic queries.
- RLHF loop → LLM service: tunes · Feedback loop updates prompts and routing behavior.
- Intel jobs → Cube adapter: analyzes · Scheduled jobs execute data-driven detection and narration steps.
- Security → Memory & cache: tracks · Context and tenant state can be reused across requests.
- Deployment → App shell: deploys · Compose and AWS packaging include the frontend service.
- Deployment → FastAPI app: deploys · Compose and AWS packaging include the backend service.
- Deployment → Cube model: deploys · Cube service is part of the deployment topology.
- Deployment → PostgreSQL: deploys · PostgreSQL is provisioned as a core service.
- Deployment → ETL ingest: deploys · Watch-mode ETL runs alongside the application stack.