analytics-ai
# Analytics AI: Semantic & Ontology-Driven Text-to-SQL Agent
An AI analytics system that translates plain-English business questions into safe, accurate DuckDB SQL using a **Semantic & Ontology Knowledge Graph**, summarizes results into executive narratives with declarative chart specifications, and exposes the entire pipeline over the **Model Context Protocol (MCP)**.
---
## Architecture Overview
```mermaid
flowchart LR
Client["Client / User\n(MCP Client, CLI, Dashboard)"] <-->|MCP stdio / CLI| Entry["MCP Server / CLI"]
subgraph Core Pipeline
Entry --> Graph["1. Semantic & Ontology Graph\n(NetworkX + YAML)"]
Graph --> SQLGen["2. Constrained SQL Generation\n(LiteLLM + Prompt Context)"]
SQLGen --> Safety["3. AST Safety Guard\n(SQLGlot Read-Only Check)"]
Safety --> DB[("4. DuckDB Engine\n(Columnar OLAP)")]
DB --> Summary["5. Business Insight Summarizer\n(Narrative + Chart Spec)"]
end
Summary --> Entry
```
### Why This Architecture?
- **Semantic & Ontology Graph (`NetworkX` + `ontology.yaml`)**: Prevents LLM join hallucinations by computing shortest valid join paths between entities and injecting canonical metric formulas (e.g., `net_revenue`, `average_order_value`).
- **AST-Level SQL Safety (`SQLGlot`)**: Parses generated SQL into a DuckDB Abstract Syntax Tree to enforce read-only `SELECT` / `WITH` queries and block `DROP`, `DELETE`, `UPDATE`, `INSERT`, `ALTER`, and stacked statements.
- **In-Process OLAP (`DuckDB`)**: Fast, zero-server columnar analytical queries over local e-commerce data (`customers`, `products`, `orders`, `order_items`).
- **Declarative Visualization Specs**: Returns structured `ChartRecommendation` metadata (`bar`, `line`, `pie`, `metric_card`, `table`) alongside raw records so any frontend can render interactive charts natively.
---
## Quickstart
### 1. Prerequisites & Installation
Ensure **Python 3.12+** and **[uv](https://docs.astral.sh/uv/)** are installed, then clone the repository and install dependencies:
```bash
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create virtual environment and install project + dev dependencies
uv sync --extra dev
```
### 2. Environment & Seed Data
```bash
# Copy environment template and optionally add GEMINI_API_KEY or OPENAI_API_KEY
cp .env.example .env
# Seed the local DuckDB database
uv run python -m analytics_ai.data.seed
```
> **Offline / Mock Mode**: If no API key is set (or `OFFLINE_MODE=true`), `LLMClient` automatically uses deterministic mock responses so the entire pipeline and test suite run offline at zero cost.
### 3. Run the Test Suite
```bash
uv run pytest tests/ -v
```
---
## Developer CLI Usage
Run [analytics_ai/cli.py](file:///home/rjayapalan/Documents/Projects/analytics-ai/analytics_ai/cli.py) from the terminal:
```bash
# Ask a business question end-to-end (Markdown report)
uv run python -m analytics_ai.cli ask "What is our total revenue by product category?"
# Output raw JSON
uv run python -m analytics_ai.cli ask "What is our total revenue by product category?" --json
# Generate and validate SQL without executing
uv run python -m analytics_ai.cli sql "Show me top customers by revenue"
# Inspect the business ontology
uv run python -m analytics_ai.cli ontology
uv run python -m analytics_ai.cli ontology net_revenue
# Start an interactive REPL
uv run python -m analytics_ai.cli repl
```
---
## MCP Server Usage
Start the MCP server over stdio ([analytics_ai/mcp/server.py](file:///home/rjayapalan/Documents/Projects/analytics-ai/analytics_ai/mcp/server.py)):
```bash
uv run python -m analytics_ai.mcp.server
```
### Exposed MCP Tools
| Tool | Description |
| --- | --- |
| `ask_business_question(question)` | Full end-to-end pipeline: SQL generation, DuckDB execution, executive summary, and chart spec. |
| `inspect_ontology(entity_or_metric?)` | Returns the business glossary, relationships, and metric formulas. |
| `generate_sql_only(question)` | Generates and AST-validates DuckDB SQL without executing it. |
| `execute_analytics_sql(sql)` | Executes a read-only SQL query directly against DuckDB (rejects DDL/DML). |
### Example MCP Client Configuration (Claude Desktop / Cursor)
```json
{
"mcpServers": {
"analytics-ai": {
"command": "/path/to/analytics-ai/.venv/bin/python",
"args": ["-m", "analytics_ai.mcp.server"],
"cwd": "/path/to/analytics-ai"
}
}
}
```
---
## Frontend Integration Guide
When a dashboard or UI calls `ask_business_question(question)`, it receives a JSON payload containing:
- `data`: Array of record objects (e.g., `[{"category": "Electronics", "net_revenue": 881876.71}, ...]`)
- `columns`: Ordered list of column names
- `insight.summary`: Executive narrative string
- `insight.key_findings`: Bullet-point takeaways
- `insight.chart_recommendation`:
```json
{
"chart_type": "bar",
"title": "Net Revenue by Category",
"x_axis": "category",
"y_axis": "net_revenue",
"description": "Bar chart ranking net_revenue across category."
}
```
A frontend charting library (e.g., **Vega-Lite**, **Chart.js**, **Recharts**, or **Plotly**) can map `chart_recommendation` directly:
1. Switch on `chart_recommendation.chart_type` (`bar`, `line`, `pie`, `metric_card`, `table`).
2. Bind `data` as the dataset.
3. Map `chart_recommendation.x_axis` and `chart_recommendation.y_axis` to the chart's X and Y encodings.
4. Render `insight.summary` and `insight.key_findings` alongside the visualization.
---
## Project Structure
```text
analytics_ai/
├── config.py # Pydantic Settings configuration
├── cli.py # Developer CLI (ask, sql, ontology, repl)
├── data/
│ ├── db.py # DuckDB connection & query helpers
│ └── seed.py # Synthetic e-commerce data generator
├── semantic/
│ ├── models.py # Pydantic v2 ontology schemas
│ ├── ontology.yaml # Declarative entities, joins, metrics, synonyms
│ └── graph.py # NetworkX shortest-path & term resolver
├── engine/
│ ├── llm.py # LiteLLM wrapper with offline mock fallback
│ ├── safety.py # SQLGlot AST read-only validator
│ ├── sql_generator.py # Context-injected Text-to-SQL generator
│ ├── executor.py # Safe DuckDB query executor
│ ├── summarizer.py # Executive insight & chart spec generator
│ └── pipeline.py # End-to-end AnalyticsPipeline orchestrator
└── mcp/
└── server.py # MCPServer exposing 4 analytics tools
```
TDQS
Scored across 4 tools
The tools have distinct pipeline roles: full Q&A, ontology inspection, SQL generation without execution, and direct SQL execution. There is mild overlap between ask_business_question and generate_sql_only since both generate SQL, but the execute/no-execute distinction is clear.
All names use consistent snake_case with verb-first phrasing. Minor deviation: generate_sql_only includes a qualifier suffix rather than a clean verb_noun pattern, but it remains readable and predictable.
Four tools is well-scoped for a focused analytics pipeline: ask, inspect metadata, generate SQL, and execute SQL. Each tool has a clear purpose within that flow.
The surface covers the main analytics lifecycle from question to execution, plus ontology inspection and safe SQL validation. Minor gaps include no dedicated schema/table discovery beyond ontology inspection and no chart rendering, only recommendation.