LalitChaudhari3 commited on
Commit
6086e71
Β·
1 Parent(s): b94d1f8

feat: synchronize text-to-sql-bot codebase with Hugging Face Space repository, including Docker build configurations

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. .env.example +56 -0
  2. .gitattributes +0 -1
  3. .gitignore +49 -0
  4. Dockerfile +38 -0
  5. backend/alembic.ini +37 -0
  6. backend/alembic/env.py +73 -0
  7. backend/alembic/script.py.mako +24 -0
  8. backend/alembic/versions/001_initial_plainsql_tables.py +54 -0
  9. backend/app/__init__.py +2 -0
  10. backend/app/agents/__init__.py +1 -0
  11. backend/app/agents/execution.py +140 -0
  12. backend/app/agents/guardrails.py +264 -0
  13. backend/app/agents/intent_classifier.py +314 -0
  14. backend/app/agents/ml_classifier.py +144 -0
  15. backend/app/agents/models/__init__.py +1 -0
  16. backend/app/agents/models/intent_model.joblib +0 -0
  17. backend/app/agents/models/train_classifier.py +130 -0
  18. backend/app/agents/models/training_data.json +173 -0
  19. backend/app/agents/orchestrator.py +856 -0
  20. backend/app/agents/query_understanding.py +276 -0
  21. backend/app/agents/result_summary.py +326 -0
  22. backend/app/agents/schema_retrieval.py +220 -0
  23. backend/app/agents/sql_generation.py +159 -0
  24. backend/app/agents/sql_validation.py +198 -0
  25. backend/app/agents/state.py +73 -0
  26. backend/app/agents/visualization.py +222 -0
  27. backend/app/ai_features/__init__.py +1 -0
  28. backend/app/ai_features/anomaly.py +105 -0
  29. backend/app/ai_features/explainer.py +29 -0
  30. backend/app/ai_features/insights.py +135 -0
  31. backend/app/api/__init__.py +1 -0
  32. backend/app/api/fast_path.py +55 -0
  33. backend/app/api/middleware.py +175 -0
  34. backend/app/api/routes/__init__.py +1 -0
  35. backend/app/api/routes/admin.py +116 -0
  36. backend/app/api/routes/chat.py +156 -0
  37. backend/app/api/routes/conversations.py +83 -0
  38. backend/app/api/routes/monitoring.py +70 -0
  39. backend/app/api/routes/system.py +193 -0
  40. backend/app/api/schemas.py +135 -0
  41. backend/app/auth/__init__.py +1 -0
  42. backend/app/auth/jwt_auth.py +109 -0
  43. backend/app/auth/rbac.py +93 -0
  44. backend/app/cache/__init__.py +1 -0
  45. backend/app/cache/redis_client.py +201 -0
  46. backend/app/cache/semantic_cache.py +198 -0
  47. backend/app/config.py +103 -0
  48. backend/app/db/__init__.py +1 -0
  49. backend/app/db/connection.py +314 -0
  50. backend/app/db/persistence.py +228 -0
.env.example ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─────────────────────────────────────────────────────────
2
+ # PlainSQL Enterprise β€” Environment Configuration
3
+ # Copy this file to .env and fill in your values
4
+ # ─────────────────────────────────────────────────────────
5
+
6
+ # ── App Settings ─────────────────────────────────────────
7
+ APP_NAME=PlainSQL
8
+ ENV=development
9
+ DEBUG=true
10
+ LOG_LEVEL=INFO
11
+
12
+ # ── Database ─────────────────────────────────────────────
13
+ DB_URI=mysql+pymysql://root:YOUR_PASSWORD@localhost:3306/chatbot
14
+ DB_POOL_SIZE=10
15
+ DB_QUERY_TIMEOUT=30
16
+
17
+ # ── Redis (optional β€” falls back to in-memory) ──────────
18
+ REDIS_URL=redis://localhost:6379/0
19
+ CACHE_TTL_SECONDS=300
20
+
21
+ # ── Authentication ───────────────────────────────────────
22
+ # Generate with: openssl rand -hex 32
23
+ JWT_SECRET_KEY=change-me-in-production-use-openssl-rand-hex-32
24
+ JWT_EXPIRY_HOURS=8
25
+
26
+ # ── LLM Providers (at least one required) ───────────────
27
+ HUGGINGFACEHUB_API_TOKEN=your_hf_token_here
28
+ DEFAULT_LLM_PROVIDER=huggingface
29
+ DEFAULT_MODEL=Qwen/Qwen2.5-Coder-32B-Instruct
30
+
31
+ # OpenAI (optional)
32
+ # OPENAI_API_KEY=sk-your-key-here
33
+
34
+ # Anthropic (optional)
35
+ # ANTHROPIC_API_KEY=sk-ant-your-key-here
36
+
37
+ # Ollama local (optional)
38
+ # OLLAMA_BASE_URL=http://localhost:11434
39
+
40
+ # ── RAG Settings ─────────────────────────────────────────
41
+ CHROMA_PERSIST_DIR=./chroma_db
42
+ RAG_TOP_K=5
43
+
44
+ # ── Safety Limits ────────────────────────────────────────
45
+ MAX_QUERY_ROWS=1000
46
+ QUERY_TIMEOUT_SECONDS=30
47
+
48
+ # ── Rate Limiting ────────────────────────────────────────
49
+ RATE_LIMIT_RPM=60
50
+
51
+ # ── Observability (optional) ────────────────────────────
52
+ # LANGSMITH_API_KEY=your_langsmith_key
53
+ # LANGSMITH_PROJECT=plainsql
54
+
55
+ # ── CORS ─────────────────────────────────────────────────
56
+ CORS_ORIGINS=["http://localhost:3000","http://127.0.0.1:5500"]
.gitattributes CHANGED
@@ -6,7 +6,6 @@
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
  *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
 
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
 
9
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
  *.mlmodel filter=lfs diff=lfs merge=lfs -text
11
  *.model filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Python ───────────────────────────────────────────────
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.pyo
5
+ *.egg-info/
6
+ dist/
7
+ build/
8
+ *.egg
9
+
10
+ # ── Virtual Environments ─────────────────────────────────
11
+ .venv/
12
+ venv/
13
+ env/
14
+
15
+ # ── Environment / Secrets ────────────────────────────────
16
+ .env
17
+ .env.local
18
+ .env.production
19
+
20
+ # ── ChromaDB ─────────────────────────────────────────────
21
+ chroma_db/
22
+
23
+ # ── IDE ──────────────────────────────────────────────────
24
+ .vscode/
25
+ .idea/
26
+ *.swp
27
+ *.swo
28
+
29
+ # ── OS ───────────────────────────────────────────────────
30
+ .DS_Store
31
+ Thumbs.db
32
+
33
+ # ── Testing ──────────────────────────────────────────────
34
+ .pytest_cache/
35
+ htmlcov/
36
+ .coverage
37
+
38
+ # ── AI Assistants ────────────────────────────────────────
39
+ .zencoder/
40
+ .zenflow/
41
+ .gemini/
42
+
43
+ # ── Node (frontend) ─────────────────────────────────────
44
+ node_modules/
45
+ .next/
46
+ out/
47
+
48
+ # ── Evaluation Results ──────────────────────────────────
49
+ evaluation_results.json
Dockerfile ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Docker Multi-Stage Build ─────────────────────────────
2
+ # Stage 1: Dependencies
3
+ FROM python:3.11-slim AS deps
4
+
5
+ WORKDIR /app
6
+ COPY backend/requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ # Stage 2: Application
10
+ FROM python:3.11-slim AS runtime
11
+
12
+ WORKDIR /app
13
+
14
+ # Copy installed packages from deps stage
15
+ COPY --from=deps /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
16
+ COPY --from=deps /usr/local/bin /usr/local/bin
17
+
18
+ # Copy application code
19
+ COPY backend/ .
20
+ COPY frontend/ /frontend/
21
+ COPY .env.example .env.example
22
+
23
+ # Create non-root user
24
+ RUN useradd -m -r plainsql && \
25
+ chown -R plainsql:plainsql /app && \
26
+ mkdir -p /app/chroma_db && \
27
+ chown -R plainsql:plainsql /app/chroma_db
28
+
29
+ USER plainsql
30
+
31
+ # Health check
32
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
33
+ CMD python -c "import requests; requests.get('http://localhost:8000/api/v1/health')" || exit 1
34
+
35
+ EXPOSE 8000
36
+
37
+ # Single worker avoids concurrent ChromaDB migrations in the local container volume.
38
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--access-log"]
backend/alembic.ini ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [alembic]
2
+ script_location = alembic
3
+ sqlalchemy.url = mysql+pymysql://root:password@localhost:3306/chatbot
4
+ file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(rev)s_%%(slug)s
5
+
6
+ [loggers]
7
+ keys = root,sqlalchemy,alembic
8
+
9
+ [handlers]
10
+ keys = console
11
+
12
+ [formatters]
13
+ keys = generic
14
+
15
+ [logger_root]
16
+ level = WARN
17
+ handlers = console
18
+
19
+ [logger_sqlalchemy]
20
+ level = WARN
21
+ handlers =
22
+ qualname = sqlalchemy.engine
23
+
24
+ [logger_alembic]
25
+ level = INFO
26
+ handlers =
27
+ qualname = alembic
28
+
29
+ [handler_console]
30
+ class = StreamHandler
31
+ args = (sys.stderr,)
32
+ level = NOTSET
33
+ formatter = generic
34
+
35
+ [formatter_generic]
36
+ format = %(levelname)-5.5s [%(name)s] %(message)s
37
+ datefmt = %H:%M:%S
backend/alembic/env.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Alembic Environment β€” Configures database migrations.
3
+ Reads DB URI from app.config to stay in sync with the application.
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ from logging.config import fileConfig
9
+
10
+ from sqlalchemy import engine_from_config, pool
11
+ from alembic import context
12
+
13
+ # Add backend to path so we can import app modules
14
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15
+
16
+ # Alembic Config object
17
+ config = context.config
18
+
19
+ # Setup logging from alembic.ini
20
+ if config.config_file_name is not None:
21
+ fileConfig(config.config_file_name)
22
+
23
+ # Override sqlalchemy.url from environment / app config
24
+ try:
25
+ from dotenv import load_dotenv
26
+ load_dotenv()
27
+ except ImportError:
28
+ pass
29
+
30
+ db_url = os.environ.get("DB_URI")
31
+ if db_url:
32
+ config.set_main_option("sqlalchemy.url", db_url)
33
+
34
+ # No metadata target β€” we use raw SQL migrations for maximum control
35
+ target_metadata = None
36
+
37
+
38
+ def run_migrations_offline() -> None:
39
+ """Run migrations in 'offline' mode (generate SQL script)."""
40
+ url = config.get_main_option("sqlalchemy.url")
41
+ context.configure(
42
+ url=url,
43
+ target_metadata=target_metadata,
44
+ literal_binds=True,
45
+ dialect_opts={"paramstyle": "named"},
46
+ )
47
+
48
+ with context.begin_transaction():
49
+ context.run_migrations()
50
+
51
+
52
+ def run_migrations_online() -> None:
53
+ """Run migrations in 'online' mode (execute against database)."""
54
+ connectable = engine_from_config(
55
+ config.get_section(config.config_ini_section, {}),
56
+ prefix="sqlalchemy.",
57
+ poolclass=pool.NullPool,
58
+ )
59
+
60
+ with connectable.connect() as connection:
61
+ context.configure(
62
+ connection=connection,
63
+ target_metadata=target_metadata,
64
+ )
65
+
66
+ with context.begin_transaction():
67
+ context.run_migrations()
68
+
69
+
70
+ if context.is_offline_mode():
71
+ run_migrations_offline()
72
+ else:
73
+ run_migrations_online()
backend/alembic/script.py.mako ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """${message}
2
+
3
+ Revision ID: ${up_revision}
4
+ Revises: ${down_revision | comma,n}
5
+ Create Date: ${create_date}
6
+ """
7
+ from typing import Sequence, Union
8
+
9
+ from alembic import op
10
+ import sqlalchemy as sa
11
+
12
+ # revision identifiers, used by Alembic.
13
+ revision: str = ${repr(up_revision)}
14
+ down_revision: Union[str, None] = ${repr(down_revision)}
15
+ branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
16
+ depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
17
+
18
+
19
+ def upgrade() -> None:
20
+ ${upgrades if upgrades else "pass"}
21
+
22
+
23
+ def downgrade() -> None:
24
+ ${downgrades if downgrades else "pass"}
backend/alembic/versions/001_initial_plainsql_tables.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Create plainsql_users and query_feedback tables
2
+
3
+ Revision ID: 001
4
+ Revises: None
5
+ Create Date: 2026-05-02
6
+ """
7
+ from typing import Sequence, Union
8
+
9
+ from alembic import op
10
+
11
+ revision: str = "001"
12
+ down_revision: Union[str, None] = None
13
+ branch_labels: Union[str, Sequence[str], None] = None
14
+ depends_on: Union[str, Sequence[str], None] = None
15
+
16
+
17
+ def upgrade() -> None:
18
+ # ── Users table (replaces in-memory user store) ──────
19
+ op.execute("""
20
+ CREATE TABLE IF NOT EXISTS plainsql_users (
21
+ id VARCHAR(64) PRIMARY KEY,
22
+ username VARCHAR(100) NOT NULL UNIQUE,
23
+ email VARCHAR(255) NOT NULL,
24
+ password_hash VARCHAR(255) NOT NULL,
25
+ role ENUM('admin', 'analyst', 'viewer') NOT NULL DEFAULT 'analyst',
26
+ tenant_id VARCHAR(100) NOT NULL DEFAULT 'default',
27
+ is_active BOOLEAN NOT NULL DEFAULT TRUE,
28
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
29
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
30
+ INDEX idx_username (username),
31
+ INDEX idx_tenant (tenant_id)
32
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
33
+ """)
34
+
35
+ # ── Query feedback table (user satisfaction tracking) ─
36
+ op.execute("""
37
+ CREATE TABLE IF NOT EXISTS query_feedback (
38
+ id INT AUTO_INCREMENT PRIMARY KEY,
39
+ trace_id VARCHAR(100) NOT NULL,
40
+ user_query TEXT NOT NULL,
41
+ generated_sql TEXT,
42
+ rating ENUM('positive', 'negative') NOT NULL,
43
+ comment TEXT,
44
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
45
+ tenant_id VARCHAR(100) DEFAULT 'default',
46
+ INDEX idx_trace (trace_id),
47
+ INDEX idx_created (created_at)
48
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
49
+ """)
50
+
51
+
52
+ def downgrade() -> None:
53
+ op.execute("DROP TABLE IF EXISTS query_feedback")
54
+ op.execute("DROP TABLE IF EXISTS plainsql_users")
backend/app/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # PlainSQL Enterprise Backend
2
+ __version__ = "2.0.0"
backend/app/agents/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Agents Package
backend/app/agents/execution.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Execution Agent β€” Safely executes validated SQL against the tenant database.
3
+ Includes EXPLAIN-based cost estimation to prevent expensive queries.
4
+ Tracks execution time and handles errors gracefully.
5
+ """
6
+
7
+ import time
8
+ import structlog
9
+
10
+ from app.agents.state import AgentState
11
+
12
+ logger = structlog.get_logger()
13
+
14
+ # Maximum rows a query is allowed to examine before being blocked
15
+ MAX_ROWS_EXAMINED = 100_000
16
+
17
+
18
+ def _estimate_query_cost(db_pool, sql: str) -> dict:
19
+ """
20
+ Run EXPLAIN on the query to estimate cost before execution.
21
+ Returns estimated row count, whether a full table scan is detected,
22
+ and whether the query is safe to execute.
23
+ """
24
+ try:
25
+ explain_sql = f"EXPLAIN {sql.rstrip(';')}"
26
+ rows = db_pool.execute_query(explain_sql)
27
+
28
+ total_rows_examined = 0
29
+ has_full_scan = False
30
+
31
+ for row in rows:
32
+ row_estimate = int(row.get("rows", 0) or 0)
33
+ total_rows_examined += row_estimate
34
+ scan_type = str(row.get("type", "")).upper()
35
+ if scan_type == "ALL" and row_estimate > 10000:
36
+ has_full_scan = True
37
+
38
+ return {
39
+ "estimated_rows": total_rows_examined,
40
+ "has_full_scan": has_full_scan,
41
+ "safe": total_rows_examined < MAX_ROWS_EXAMINED and not has_full_scan,
42
+ }
43
+ except Exception as e:
44
+ logger.warning("explain_failed", error=str(e))
45
+ # If EXPLAIN fails, allow the query (fail open)
46
+ return {"estimated_rows": 0, "has_full_scan": False, "safe": True}
47
+
48
+
49
+ def execution_node(state: AgentState, db_pool) -> dict:
50
+ """
51
+ Execute the validated SQL query against the database.
52
+ Runs EXPLAIN first to estimate cost and block expensive queries.
53
+ Measures execution time and returns structured results.
54
+ """
55
+ sql = state.get("sanitized_sql", "") or state.get("generated_sql", "")
56
+ trace_id = state.get("trace_id", "unknown")
57
+
58
+ logger.info("agent_started", agent="execution", trace_id=trace_id)
59
+
60
+ if not sql or not sql.strip():
61
+ return {
62
+ "query_results": [],
63
+ "execution_time_ms": 0,
64
+ "row_count": 0,
65
+ "column_names": [],
66
+ "error": "No SQL to execute",
67
+ "error_agent": "execution",
68
+ }
69
+
70
+ # ── Cost Estimation (conditional to avoid doubling DB round-trips) ──
71
+ # Only run EXPLAIN for queries without WHERE filters or complex queries,
72
+ # since simple filtered queries are unlikely to cause full table scans.
73
+ sql_upper = sql.upper()
74
+ needs_cost_check = "WHERE" not in sql_upper or state.get("complexity") == "complex"
75
+
76
+ if needs_cost_check:
77
+ cost = _estimate_query_cost(db_pool, sql)
78
+ if not cost["safe"]:
79
+ logger.warning(
80
+ "query_too_expensive",
81
+ trace_id=trace_id,
82
+ estimated_rows=cost["estimated_rows"],
83
+ has_full_scan=cost["has_full_scan"],
84
+ )
85
+ return {
86
+ "query_results": [],
87
+ "execution_time_ms": 0,
88
+ "row_count": 0,
89
+ "column_names": [],
90
+ "error": f"Query blocked: estimated to scan ~{cost['estimated_rows']:,} rows. "
91
+ f"Add WHERE filters or LIMIT to reduce scope.",
92
+ "error_agent": "execution",
93
+ "friendly_message": (
94
+ "⚠️ **Query too expensive**: This query would scan a very large number of rows. "
95
+ "Please add filters (WHERE clause) or a smaller LIMIT to reduce the scope."
96
+ ),
97
+ }
98
+ else:
99
+ cost = {"estimated_rows": 0, "has_full_scan": False, "safe": True}
100
+
101
+ # ── Execute Query ────────────────────────────────────
102
+ try:
103
+ start_time = time.perf_counter()
104
+ results = db_pool.execute_query(sql)
105
+ end_time = time.perf_counter()
106
+
107
+ execution_time_ms = round((end_time - start_time) * 1000, 2)
108
+
109
+ # Extract column names from results
110
+ column_names = list(results[0].keys()) if results else []
111
+
112
+ logger.info(
113
+ "query_executed",
114
+ execution_time_ms=execution_time_ms,
115
+ row_count=len(results),
116
+ columns=len(column_names),
117
+ estimated_rows=cost["estimated_rows"],
118
+ )
119
+
120
+ return {
121
+ "query_results": results,
122
+ "execution_time_ms": execution_time_ms,
123
+ "row_count": len(results),
124
+ "column_names": column_names,
125
+ }
126
+
127
+ except Exception as e:
128
+ error_msg = str(e)
129
+ logger.error("query_execution_failed", error=error_msg, sql_preview=sql[:100])
130
+
131
+ return {
132
+ "query_results": [],
133
+ "execution_time_ms": 0,
134
+ "row_count": 0,
135
+ "column_names": [],
136
+ "error": f"Database error: {error_msg}",
137
+ "error_agent": "execution",
138
+ "friendly_message": f"The query had a syntax error: {error_msg}",
139
+ }
140
+
backend/app/agents/guardrails.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Output Guardrails β€” Schema grounding, confidence scoring, and robust SQL extraction.
3
+ Prevents hallucinated table/column references and handles malformed LLM output.
4
+ """
5
+
6
+ import re
7
+ import sqlparse
8
+ import structlog
9
+
10
+ logger = structlog.get_logger()
11
+
12
+
13
+ class OutputGuardrail:
14
+ """
15
+ Validates LLM output before SQL execution:
16
+ 1. Schema grounding β€” ensures SQL only references real tables and columns
17
+ 2. SQL extraction β€” robustly extracts SQL from messy LLM responses
18
+ 3. Confidence scoring β€” detects uncertain/hedging language
19
+ """
20
+
21
+ def __init__(self, known_tables: set = None, known_columns: dict = None):
22
+ """
23
+ Args:
24
+ known_tables: Set of valid table names in the database
25
+ known_columns: Dict of {table_name: set of column_names}
26
+ """
27
+ self.known_tables = {t.lower() for t in (known_tables or set())}
28
+ self.known_columns = {
29
+ t.lower(): {c.lower() for c in cols}
30
+ for t, cols in (known_columns or {}).items()
31
+ }
32
+ self.all_columns = set()
33
+ for cols in self.known_columns.values():
34
+ self.all_columns.update(cols)
35
+
36
+ def update_schema(self, tables: set, columns: dict):
37
+ """Update known schema when database connection changes."""
38
+ self.known_tables = {t.lower() for t in tables}
39
+ self.known_columns = {
40
+ t.lower(): {c.lower() for c in cols}
41
+ for t, cols in columns.items()
42
+ }
43
+ self.all_columns = set()
44
+ for cols in self.known_columns.values():
45
+ self.all_columns.update(cols)
46
+
47
+ def validate_sql_references(self, sql: str) -> list[str]:
48
+ """
49
+ Check that generated SQL only references real tables and columns.
50
+ Returns a list of hallucination warnings (empty = clean).
51
+ """
52
+ if not sql or not self.known_tables:
53
+ return []
54
+
55
+ warnings = []
56
+
57
+ try:
58
+ parsed = sqlparse.parse(sql)
59
+ if not parsed:
60
+ return warnings
61
+
62
+ # Comprehensive SQL functions to skip
63
+ sql_functions = {
64
+ "count", "sum", "avg", "min", "max", "round", "coalesce",
65
+ "ifnull", "isnull", "nullif", "concat", "substring", "trim",
66
+ "upper", "lower", "length", "cast", "convert", "date_format",
67
+ "date_sub", "date_add", "curdate", "now", "year", "month",
68
+ "day", "hour", "minute", "second", "datediff", "timestampdiff",
69
+ "group_concat", "distinct", "if", "abs", "ceil", "floor",
70
+ "power", "sqrt", "mod", "sign", "truncate", "replace",
71
+ "lpad", "rpad", "left", "right", "reverse", "space",
72
+ "char_length", "character_length", "locate", "instr",
73
+ "field", "elt", "format", "hex", "unhex", "crc32",
74
+ "last_insert_id", "row_number", "rank", "dense_rank",
75
+ "ntile", "lag", "lead", "first_value", "last_value",
76
+ "nth_value", "percent_rank", "cume_dist", "quarter",
77
+ "week", "dayofweek", "dayofyear", "monthname", "dayname",
78
+ "time", "timestamp", "str_to_date", "date",
79
+ }
80
+
81
+ # SQL keywords that appear as Name tokens
82
+ sql_keywords = {
83
+ "asc", "desc", "limit", "offset", "as", "on", "and", "or",
84
+ "not", "in", "between", "like", "is", "null", "true", "false",
85
+ "inner", "left", "right", "outer", "cross", "natural",
86
+ "select", "from", "where", "join", "group", "order", "having",
87
+ "by", "union", "except", "intersect", "with", "recursive",
88
+ "case", "when", "then", "else", "end", "exists", "any", "all",
89
+ "interval", "rows", "unbounded", "preceding", "following",
90
+ "over", "partition", "range", "current", "row",
91
+ "rollup", "cube", "grouping", "sets",
92
+ }
93
+
94
+ # ── Extract ALL defined aliases ──────────────────
95
+ defined_aliases = set()
96
+
97
+ # 1. SELECT ... AS alias_name (column aliases)
98
+ for m in re.finditer(r'\bAS\s+`?(\w+)`?', sql, re.IGNORECASE):
99
+ defined_aliases.add(m.group(1).lower())
100
+
101
+ # 2. FROM/JOIN table aliases
102
+ for m in re.finditer(
103
+ r'(?:FROM|JOIN)\s+`?(\w+)`?\s+(?:AS\s+)?`?(\w+)`?',
104
+ sql, re.IGNORECASE,
105
+ ):
106
+ alias = m.group(2).lower()
107
+ table = m.group(1).lower()
108
+ if alias != table and alias not in sql_keywords:
109
+ defined_aliases.add(alias)
110
+
111
+ # 3. CTE names: WITH cte_name AS (...)
112
+ for m in re.finditer(r'\bWITH\s+(\w+)\s+AS\s*\(', sql, re.IGNORECASE):
113
+ defined_aliases.add(m.group(1).lower())
114
+
115
+ for token in parsed[0].flatten():
116
+ if token.ttype is sqlparse.tokens.Name:
117
+ name = token.value.lower().strip('`"[]')
118
+
119
+ # Skip known SQL functions and keywords
120
+ if name in sql_functions or name in sql_keywords:
121
+ continue
122
+
123
+ # Skip single-char aliases (e.g., e, s, p, c, d, t)
124
+ if len(name) <= 1:
125
+ continue
126
+
127
+ # Skip defined aliases (e.g., dept, emp, avg_salary)
128
+ if name in defined_aliases:
129
+ continue
130
+
131
+ # Check against known schema
132
+ if name not in self.known_tables and name not in self.all_columns:
133
+ warnings.append(f"Unknown reference: '{name}' β€” not a known table or column")
134
+
135
+ except Exception as e:
136
+ logger.warning("guardrail_parse_failed", error=str(e))
137
+
138
+ return warnings
139
+
140
+ def extract_sql_from_response(self, llm_output: str) -> str:
141
+ """
142
+ Robustly extract SQL from potentially messy LLM output.
143
+ Handles:
144
+ - JSON-wrapped responses
145
+ - Markdown code blocks
146
+ - Raw SQL with explanatory text
147
+ - Multiple SQL statements (returns first SELECT)
148
+ """
149
+ if not llm_output:
150
+ return ""
151
+
152
+ text = llm_output.strip()
153
+
154
+ # Strategy 1: Try JSON extraction
155
+ try:
156
+ # Remove markdown JSON blocks
157
+ clean = re.sub(r"```(?:json)?\s*", "", text)
158
+ clean = re.sub(r"```\s*$", "", clean, flags=re.MULTILINE)
159
+ import json
160
+ data = json.loads(clean.strip())
161
+ if isinstance(data, dict) and "sql" in data:
162
+ sql = data["sql"].strip()
163
+ if sql:
164
+ return self._clean_extracted_sql(sql)
165
+ except (ValueError, TypeError):
166
+ pass
167
+
168
+ # Strategy 2: Extract from markdown SQL block
169
+ sql_block = re.search(r"```sql\s*\n?(.*?)\n?```", text, re.DOTALL | re.IGNORECASE)
170
+ if sql_block:
171
+ return self._clean_extracted_sql(sql_block.group(1))
172
+
173
+ # Strategy 3: Extract from generic code block
174
+ code_block = re.search(r"```\s*\n?(.*?)\n?```", text, re.DOTALL)
175
+ if code_block:
176
+ candidate = code_block.group(1).strip()
177
+ if re.match(r"(?:WITH|SELECT|INSERT|UPDATE|DELETE)\b", candidate, re.IGNORECASE):
178
+ return self._clean_extracted_sql(candidate)
179
+
180
+ # Strategy 4: Find standalone SQL statement
181
+ sql_match = re.search(
182
+ r"((?:WITH\s+\w+\s+AS\s*\(.*?\)\s*)?SELECT\s[\s\S]+?)(?:;|\n\n|$)",
183
+ text,
184
+ re.IGNORECASE | re.DOTALL,
185
+ )
186
+ if sql_match:
187
+ return self._clean_extracted_sql(sql_match.group(1))
188
+
189
+ # Strategy 5: Return empty if nothing found
190
+ logger.warning("sql_extraction_failed", output_preview=text[:200])
191
+ return ""
192
+
193
+ def score_confidence(self, llm_output: str) -> float:
194
+ """
195
+ Score LLM confidence from 0.0 to 1.0 based on language analysis.
196
+ Low confidence suggests asking for clarification instead of executing.
197
+ """
198
+ if not llm_output:
199
+ return 0.0
200
+
201
+ text = llm_output.lower()
202
+
203
+ # Hedging phrases that indicate low confidence
204
+ hedging_phrases = [
205
+ "i'm not sure", "i am not sure",
206
+ "i think", "maybe", "perhaps", "possibly",
207
+ "i don't have enough", "unclear",
208
+ "ambiguous", "could you clarify",
209
+ "i'm guessing", "it's hard to tell",
210
+ "without more context", "assuming",
211
+ "i cannot determine", "not enough information",
212
+ ]
213
+
214
+ hedging_count = sum(1 for phrase in hedging_phrases if phrase in text)
215
+
216
+ # Check if SQL was actually generated
217
+ has_sql = bool(re.search(r"\bSELECT\b", text, re.IGNORECASE))
218
+
219
+ # Base confidence
220
+ confidence = 1.0 if has_sql else 0.3
221
+
222
+ # Penalize for hedging
223
+ confidence -= hedging_count * 0.15
224
+
225
+ # Penalize for error indicators
226
+ if "error" in text or "cannot" in text or "unable to" in text:
227
+ confidence -= 0.3
228
+
229
+ return max(0.0, min(1.0, confidence))
230
+
231
+ def _clean_extracted_sql(self, sql: str) -> str:
232
+ """Normalize extracted SQL."""
233
+ # Remove leading/trailing whitespace and markdown artifacts
234
+ sql = sql.strip()
235
+ sql = re.sub(r"```\w*", "", sql).strip()
236
+ # Normalize whitespace
237
+ sql = " ".join(sql.split())
238
+ # Ensure trailing semicolon
239
+ if sql and not sql.endswith(";"):
240
+ sql += ";"
241
+ return sql
242
+
243
+ def validate_output(self, llm_output: str) -> dict:
244
+ """
245
+ Full output validation pipeline.
246
+ Returns a dict with sql, confidence, warnings, and is_safe.
247
+ """
248
+ sql = self.extract_sql_from_response(llm_output)
249
+ confidence = self.score_confidence(llm_output)
250
+ warnings = self.validate_sql_references(sql) if sql else []
251
+
252
+ is_safe = (
253
+ bool(sql)
254
+ and confidence >= 0.4
255
+ and len(warnings) == 0
256
+ )
257
+
258
+ return {
259
+ "sql": sql,
260
+ "confidence": round(confidence, 2),
261
+ "warnings": warnings,
262
+ "is_safe": is_safe,
263
+ "needs_clarification": confidence < 0.4,
264
+ }
backend/app/agents/intent_classifier.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Intent classifier for routing user input before SQL generation.
3
+
4
+ Uses a hybrid approach:
5
+ 1. ML model (sentence-transformers + LogisticRegression) when available and confident
6
+ 2. Heuristic keyword matching as a fallback
7
+
8
+ Clear chat messages return fast and never touch schema retrieval or SQL
9
+ generation. Database-shaped requests continue through the existing SQL path.
10
+ """
11
+
12
+ from dataclasses import dataclass
13
+ from typing import Literal
14
+ import re
15
+ import structlog
16
+
17
+ logger = structlog.get_logger()
18
+
19
+ IntentKind = Literal["chat", "sql", "ambiguous"]
20
+ RouteIntent = Literal["chat", "ambiguous", "meta_query", "data_query", "aggregation", "comparison", "explanation"]
21
+
22
+ # Minimum confidence from the ML model to trust its classification
23
+ _ML_CONFIDENCE_THRESHOLD = 0.70
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class IntentClassification:
28
+ intent: IntentKind
29
+ route_intent: RouteIntent
30
+ complexity: Literal["simple", "moderate", "complex"] = "simple"
31
+ reason: str = "heuristic"
32
+
33
+
34
+ GREETING_PATTERNS = {
35
+ "hello", "hi", "hey", "good morning", "good afternoon", "good evening",
36
+ "hola", "sup", "what's up", "howdy", "yo", "greetings", "namaste", "bonjour",
37
+ }
38
+
39
+ CHAT_EXACT = {
40
+ "thanks", "thank you", "thank u", "thx", "ty", "ok", "okay", "cool",
41
+ "great", "nice", "awesome", "got it", "bye", "goodbye", "see you",
42
+ "see ya", "later", "yes", "no", "yep", "nope", "sure", "nah",
43
+ "help", "help me", "what can you do", "who are you", "what are you",
44
+ "how are you", "how do you work", "how does this work",
45
+ "tell me about yourself", "what is this", "what is plainsql",
46
+ }
47
+
48
+ CHAT_PREFIXES = {
49
+ "thanks for", "thank you for", "can you help", "please help",
50
+ "i need help", "i don't understand", "what do you do", "what can i ask",
51
+ "how do i use", "tell me about you", "who made you", "are you",
52
+ "tell me a joke", "how is the weather",
53
+ "tell me about yourself", "do you know about",
54
+ }
55
+
56
+ DATA_SIGNAL_PHRASES = {
57
+ "how many", "how much", "group by", "order by", "by region",
58
+ "by department", "by category", "by month", "by year",
59
+ }
60
+
61
+ # Strong signals β€” specific enough to indicate a real SQL query
62
+ DATA_SIGNAL_WORDS_STRONG = {
63
+ "show", "list", "find", "get", "select", "count", "total", "average",
64
+ "avg", "sum", "top", "bottom", "highest", "lowest", "maximum",
65
+ "minimum", "max", "min", "most", "least", "revenue", "sales",
66
+ "salary", "salaries", "price", "stock", "spend", "employees",
67
+ "employee", "customers", "customer", "products", "product",
68
+ "departments", "department", "orders", "order",
69
+ "where", "between", "greater", "less", "equal", "filter", "sort",
70
+ "compare", "vs", "versus", "per", "each", "join", "query", "report",
71
+ }
72
+
73
+ # Weak signals β€” too generic alone, need a strong signal to confirm SQL intent
74
+ DATA_SIGNAL_WORDS_WEAK = {
75
+ "table", "tables", "column", "columns", "rows", "records",
76
+ "all", "every", "data", "database", "info", "information",
77
+ "about", "details",
78
+ }
79
+
80
+ DATA_SIGNAL_WORDS = DATA_SIGNAL_WORDS_STRONG | DATA_SIGNAL_WORDS_WEAK
81
+
82
+ # Known database table names β€” used to validate ambiguous queries
83
+ KNOWN_TABLES = {
84
+ "employees", "employee", "departments", "department",
85
+ "products", "product", "customers", "customer",
86
+ "sales", "sale", "orders", "order",
87
+ }
88
+
89
+ META_KEYWORDS = {
90
+ "what tables", "show tables", "list tables", "what columns",
91
+ "describe table", "schema", "what database",
92
+ }
93
+ AGGREGATION_KEYWORDS = {
94
+ "count", "total", "sum", "average", "avg", "minimum", "maximum",
95
+ "min", "max", "group by", "by region", "by department", "by category",
96
+ "by month", "by year",
97
+ }
98
+ COMPARISON_KEYWORDS = {"compare", " vs ", " versus ", "between"}
99
+ EXPLANATION_KEYWORDS = {"explain this", "why did", "what does this query"}
100
+
101
+
102
+ def classify_intent(user_query: str) -> IntentClassification:
103
+ """
104
+ Classify input as chat, SQL, or ambiguous and choose the downstream graph route.
105
+
106
+ Strategy:
107
+ 1. Try ML model first (sentence-transformers + LogisticRegression)
108
+ 2. If model unavailable or confidence < threshold, fall back to heuristic
109
+ """
110
+ query = _normalize(user_query)
111
+ if not query:
112
+ return IntentClassification("chat", "chat", reason="empty")
113
+
114
+ # ── ML Classification (preferred) ────────────────────
115
+ ml_result = _try_ml_classification(user_query)
116
+ if ml_result is not None:
117
+ return ml_result
118
+
119
+ # ── Heuristic Fallback ───────────────────────────────
120
+
121
+ # Meta queries are always SQL
122
+ if any(kw in query for kw in META_KEYWORDS):
123
+ return IntentClassification(
124
+ "sql",
125
+ "meta_query",
126
+ complexity="simple",
127
+ reason="meta_keyword",
128
+ )
129
+
130
+ has_data_signal = _has_data_signal(query)
131
+
132
+ # Mixed inputs like "hi, show top 5 employees" should still be SQL.
133
+ if has_data_signal:
134
+ # Check if only weak signals present (e.g. "do you have info about admin")
135
+ words = set(re.findall(r"[a-z_]+", query))
136
+ has_strong = bool(words.intersection(DATA_SIGNAL_WORDS_STRONG))
137
+ has_known_table = bool(words.intersection(KNOWN_TABLES))
138
+ has_phrase = any(phrase in query for phrase in DATA_SIGNAL_PHRASES)
139
+
140
+ if has_strong or has_phrase or has_known_table:
141
+ return IntentClassification(
142
+ "sql",
143
+ _classify_sql_route(query),
144
+ complexity=_estimate_complexity(query),
145
+ reason="data_signal",
146
+ )
147
+ else:
148
+ # Weak signal only β€” ambiguous query
149
+ return IntentClassification(
150
+ "ambiguous",
151
+ "ambiguous",
152
+ complexity="simple",
153
+ reason="weak_data_signal_only",
154
+ )
155
+
156
+ if _is_chat(query):
157
+ return IntentClassification("chat", "chat", reason="chat_signal")
158
+
159
+ if len(query.split()) <= 4:
160
+ return IntentClassification("chat", "chat", reason="short_without_data_signal")
161
+
162
+ # Longer queries without any data signal β€” likely ambiguous
163
+ words = set(re.findall(r"[a-z_]+", query))
164
+ has_known_table = bool(words.intersection(KNOWN_TABLES))
165
+ if not has_known_table:
166
+ return IntentClassification(
167
+ "ambiguous",
168
+ "ambiguous",
169
+ complexity="simple",
170
+ reason="no_table_reference",
171
+ )
172
+
173
+ # Preserve existing text-to-SQL behavior for ambiguous analytical requests.
174
+ return IntentClassification(
175
+ "sql",
176
+ _classify_sql_route(query),
177
+ complexity=_estimate_complexity(query),
178
+ reason="ambiguous_default_sql",
179
+ )
180
+
181
+
182
+ def build_chat_response(user_query: str) -> str:
183
+ """Return a simple conversational response without invoking SQL generation."""
184
+ query = _normalize(user_query)
185
+
186
+ if any(kw in query for kw in ("what can you do", "what do you do", "how do you work", "how does this work", "help", "what can i ask", "how do i use")):
187
+ return (
188
+ "I'm PlainSQL, your data assistant. Ask me a database question in plain "
189
+ "English and I can generate safe read-only SQL, run it, and summarize the result. "
190
+ "Try: 'Show top 5 employees by salary' or 'Total sales by region'."
191
+ )
192
+
193
+ if any(kw in query for kw in ("who are you", "what are you", "tell me about you", "what is plainsql", "what is this")):
194
+ return (
195
+ "I'm PlainSQL, an assistant for querying your database with natural language. "
196
+ "Describe the data you want and I'll handle the SQL path."
197
+ )
198
+
199
+ if any(kw in query for kw in ("thanks", "thank", "thx", "ty")):
200
+ return "You're welcome. Ask me any database question when you're ready."
201
+
202
+ if any(kw in query for kw in ("bye", "goodbye", "see you", "see ya", "later")):
203
+ return "Goodbye. Come back anytime you want to explore your data."
204
+
205
+ return (
206
+ "Hello. I can help you query your database in plain English. "
207
+ "Try asking something like 'Show top 5 employees by salary'."
208
+ )
209
+
210
+
211
+ def _normalize(value: str) -> str:
212
+ cleaned = re.sub(r"\s+", " ", value.lower()).strip()
213
+ return cleaned.strip(" \t\r\n.!?")
214
+
215
+
216
+ def _has_data_signal(query: str) -> bool:
217
+ if any(phrase in query for phrase in DATA_SIGNAL_PHRASES):
218
+ return True
219
+ words = set(re.findall(r"[a-z_]+", query))
220
+ return bool(words.intersection(DATA_SIGNAL_WORDS))
221
+
222
+
223
+ def _is_chat(query: str) -> bool:
224
+ if query in CHAT_EXACT or query in GREETING_PATTERNS:
225
+ return True
226
+ if any(query.startswith(prefix) for prefix in CHAT_PREFIXES):
227
+ return True
228
+ return any(query == greeting or query.startswith(greeting + " ") for greeting in GREETING_PATTERNS)
229
+
230
+
231
+ def _classify_sql_route(query: str) -> RouteIntent:
232
+ if any(kw in query for kw in META_KEYWORDS):
233
+ return "meta_query"
234
+ if any(kw in query for kw in COMPARISON_KEYWORDS):
235
+ return "comparison"
236
+ if any(kw in query for kw in EXPLANATION_KEYWORDS):
237
+ return "explanation"
238
+ if any(kw in query for kw in AGGREGATION_KEYWORDS):
239
+ return "aggregation"
240
+ return "data_query"
241
+
242
+
243
+ def _estimate_complexity(query: str) -> Literal["simple", "moderate", "complex"]:
244
+ if any(kw in query for kw in ("subquery", "window", "rank", "running total", "percentile")):
245
+ return "complex"
246
+ if any(kw in query for kw in ("join", "compare", " vs ", " versus ", "group by", " by ")):
247
+ return "moderate"
248
+ return "simple"
249
+
250
+
251
+ # ── ML Classification Bridge ────────────────────────────────
252
+
253
+ def _try_ml_classification(user_query: str) -> IntentClassification | None:
254
+ """
255
+ Attempt to classify using the ML model.
256
+
257
+ Returns an IntentClassification if the model is available and confident,
258
+ or None to signal the caller should use the heuristic fallback.
259
+ """
260
+ import os
261
+ if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"):
262
+ logger.debug("ml_classification_disabled_by_env")
263
+ return None
264
+
265
+ try:
266
+ from app.agents.ml_classifier import get_ml_classifier
267
+
268
+ classifier = get_ml_classifier()
269
+ if not classifier.available:
270
+ return None
271
+
272
+ result = classifier.classify(user_query)
273
+ if result is None:
274
+ return None
275
+
276
+ # Only trust the ML model when it's confident enough
277
+ if result.confidence < _ML_CONFIDENCE_THRESHOLD:
278
+ logger.debug(
279
+ "ml_confidence_below_threshold",
280
+ confidence=result.confidence,
281
+ threshold=_ML_CONFIDENCE_THRESHOLD,
282
+ ml_label=result.intent,
283
+ fallback="heuristic",
284
+ )
285
+ return None
286
+
287
+ # Map ML result to the full IntentClassification with complexity
288
+ query_normalized = _normalize(user_query)
289
+ complexity = _estimate_complexity(query_normalized)
290
+
291
+ # For SQL intents, refine the route using the heuristic sub-classifier
292
+ if result.intent == "sql":
293
+ route = _classify_sql_route(query_normalized)
294
+ else:
295
+ route = result.route_intent
296
+
297
+ logger.info(
298
+ "intent_classified",
299
+ method="ml",
300
+ intent=result.intent,
301
+ route_intent=route,
302
+ confidence=round(result.confidence, 3),
303
+ )
304
+
305
+ return IntentClassification(
306
+ intent=result.intent,
307
+ route_intent=route,
308
+ complexity=complexity,
309
+ reason=f"ml_model(conf={result.confidence:.2f})",
310
+ )
311
+
312
+ except Exception as e:
313
+ logger.debug("ml_classification_unavailable", error=str(e))
314
+ return None
backend/app/agents/ml_classifier.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ML Intent Classifier β€” Sentence-transformer embeddings + LogisticRegression.
3
+
4
+ Provides a trained ML model for intent classification, replacing pure heuristic
5
+ keyword matching with learned representations. Falls back gracefully when the
6
+ model file is not available.
7
+
8
+ Architecture:
9
+ sentence-transformers/all-MiniLM-L6-v2 (384-dim) β†’ LogisticRegression (4 classes)
10
+
11
+ Classes:
12
+ chat β€” Greetings, thanks, capability questions, off-topic
13
+ sql β€” Data queries, aggregations, comparisons, joins
14
+ ambiguous β€” Vague data-shaped queries that need clarification
15
+ meta_query β€” Schema exploration (show tables, describe columns)
16
+ """
17
+
18
+ import os
19
+ import structlog
20
+ from typing import Optional
21
+ from dataclasses import dataclass
22
+
23
+ logger = structlog.get_logger()
24
+
25
+ # Path to the pre-trained model artifact
26
+ _MODEL_DIR = os.path.dirname(os.path.abspath(__file__))
27
+ _MODEL_PATH = os.path.join(_MODEL_DIR, "models", "intent_model.joblib")
28
+
29
+ # Map ML labels to route_intent values for pipeline compatibility
30
+ _ROUTE_INTENT_MAP = {
31
+ "chat": "chat",
32
+ "sql": "data_query",
33
+ "ambiguous": "chat",
34
+ "meta_query": "meta_query",
35
+ }
36
+
37
+
38
+ @dataclass
39
+ class MLClassification:
40
+ """Result from the ML classifier."""
41
+ intent: str # chat | sql | ambiguous | meta_query
42
+ route_intent: str # Pipeline-compatible intent for routing
43
+ confidence: float # Model confidence (0.0 - 1.0)
44
+ method: str = "ml" # Always "ml" for this classifier
45
+
46
+
47
+ class MLIntentClassifier:
48
+ """
49
+ ML-based intent classifier using sentence-transformer embeddings
50
+ and logistic regression.
51
+
52
+ Loads a pre-trained model from disk. If the model is unavailable,
53
+ classify() returns None so the caller can fall back to heuristics.
54
+ """
55
+
56
+ def __init__(self, model_path: str = None):
57
+ self.model = None
58
+ self.encoder = None
59
+ self._loaded = False
60
+ self._model_path = model_path or _MODEL_PATH
61
+
62
+ self._try_load()
63
+
64
+ def _try_load(self):
65
+ """Attempt to load the pre-trained model and encoder."""
66
+ if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"):
67
+ logger.info("ml_classifier_disabled_by_env")
68
+ return
69
+
70
+ if not os.path.exists(self._model_path):
71
+ logger.info("ml_classifier_model_not_found", path=self._model_path)
72
+ return
73
+
74
+ try:
75
+ import joblib
76
+ from sentence_transformers import SentenceTransformer
77
+
78
+ self.model = joblib.load(self._model_path)
79
+ self.encoder = SentenceTransformer("all-MiniLM-L6-v2")
80
+ self._loaded = True
81
+ logger.info("ml_classifier_loaded", path=self._model_path)
82
+ except ImportError as e:
83
+ logger.warning("ml_classifier_deps_missing", error=str(e),
84
+ hint="pip install scikit-learn sentence-transformers joblib")
85
+ except Exception as e:
86
+ logger.warning("ml_classifier_load_failed", error=str(e))
87
+
88
+ @property
89
+ def available(self) -> bool:
90
+ """Whether the ML model is loaded and ready for inference."""
91
+ return self._loaded and self.model is not None and self.encoder is not None
92
+
93
+ def classify(self, query: str) -> Optional[MLClassification]:
94
+ """
95
+ Classify a query using the ML model.
96
+
97
+ Returns:
98
+ MLClassification if model is available and confident,
99
+ None if model is unavailable (caller should fall back to heuristic).
100
+ """
101
+ if not self.available:
102
+ return None
103
+
104
+ try:
105
+ # Encode the query to a 384-dim embedding
106
+ embedding = self.encoder.encode([query])
107
+
108
+ # Predict class and confidence
109
+ predicted_label = self.model.predict(embedding)[0]
110
+ probabilities = self.model.predict_proba(embedding)[0]
111
+ confidence = float(max(probabilities))
112
+
113
+ route_intent = _ROUTE_INTENT_MAP.get(predicted_label, "data_query")
114
+
115
+ logger.debug(
116
+ "ml_classification",
117
+ query=query[:80],
118
+ label=predicted_label,
119
+ confidence=round(confidence, 3),
120
+ route_intent=route_intent,
121
+ )
122
+
123
+ return MLClassification(
124
+ intent=predicted_label,
125
+ route_intent=route_intent,
126
+ confidence=confidence,
127
+ )
128
+
129
+ except Exception as e:
130
+ logger.warning("ml_classification_failed", error=str(e))
131
+ return None
132
+
133
+
134
+ # ── Module-level singleton ───────────────────────────────────
135
+ # Lazy-loaded on first use to avoid startup cost if not needed.
136
+ _classifier_instance: Optional[MLIntentClassifier] = None
137
+
138
+
139
+ def get_ml_classifier() -> MLIntentClassifier:
140
+ """Get or create the singleton ML classifier instance."""
141
+ global _classifier_instance
142
+ if _classifier_instance is None:
143
+ _classifier_instance = MLIntentClassifier()
144
+ return _classifier_instance
backend/app/agents/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # ML model artifacts for intent classification
backend/app/agents/models/intent_model.joblib ADDED
Binary file (13.3 kB). View file
 
backend/app/agents/models/train_classifier.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train the ML intent classifier.
3
+
4
+ Usage:
5
+ cd backend
6
+ python -m app.agents.models.train_classifier
7
+
8
+ This script:
9
+ 1. Loads training data from training_data.json
10
+ 2. Encodes all examples using sentence-transformers/all-MiniLM-L6-v2
11
+ 3. Trains a LogisticRegression classifier with cross-validation
12
+ 4. Saves the model to intent_model.joblib
13
+ 5. Prints a classification report and accuracy metrics
14
+
15
+ The output model is used by MLIntentClassifier in ml_classifier.py.
16
+ """
17
+
18
+ import json
19
+ import os
20
+ import numpy as np
21
+
22
+
23
+ def main():
24
+ # ── Load training data ───────────────────────────────
25
+ data_dir = os.path.dirname(os.path.abspath(__file__))
26
+ data_path = os.path.join(data_dir, "training_data.json")
27
+ model_path = os.path.join(data_dir, "intent_model.joblib")
28
+
29
+ print(f"[LOAD] Loading training data from {data_path}")
30
+ with open(data_path, "r") as f:
31
+ dataset = json.load(f)
32
+
33
+ texts = [item["text"] for item in dataset]
34
+ labels = [item["label"] for item in dataset]
35
+
36
+ print(f" Total examples: {len(texts)}")
37
+ label_counts = {}
38
+ for label in labels:
39
+ label_counts[label] = label_counts.get(label, 0) + 1
40
+ for label, count in sorted(label_counts.items()):
41
+ print(f" - {label}: {count}")
42
+
43
+ # ── Encode with sentence-transformers ────────────────
44
+ print("\n[ENCODE] Encoding with sentence-transformers/all-MiniLM-L6-v2...")
45
+ from sentence_transformers import SentenceTransformer
46
+
47
+ encoder = SentenceTransformer("all-MiniLM-L6-v2")
48
+ embeddings = encoder.encode(texts, show_progress_bar=True)
49
+ print(f" Embedding shape: {embeddings.shape}")
50
+
51
+ # ── Train/test split ────────────────────────────────
52
+ from sklearn.model_selection import train_test_split, cross_val_score
53
+ from sklearn.linear_model import LogisticRegression
54
+ from sklearn.metrics import classification_report, confusion_matrix
55
+
56
+ X_train, X_test, y_train, y_test = train_test_split(
57
+ embeddings, labels, test_size=0.2, random_state=42, stratify=labels
58
+ )
59
+
60
+ print(f"\n[SPLIT] Train: {len(X_train)} | Test: {len(X_test)}")
61
+
62
+ # ── Train LogisticRegression ────────────────────────
63
+ print("\n[TRAIN] Training LogisticRegression classifier...")
64
+ model = LogisticRegression(
65
+ max_iter=1000,
66
+ C=1.0,
67
+ solver="lbfgs",
68
+ multi_class="multinomial",
69
+ class_weight="balanced", # Handle class imbalance
70
+ random_state=42,
71
+ )
72
+ model.fit(X_train, y_train)
73
+
74
+ # ── Evaluate ────────────────────────────────────────
75
+ y_pred = model.predict(X_test)
76
+ accuracy = (np.array(y_pred) == np.array(y_test)).mean()
77
+
78
+ print(f"\n{'='*60}")
79
+ print(" TEST SET RESULTS")
80
+ print(f"{'='*60}")
81
+ print(f" Accuracy: {accuracy:.1%}")
82
+ print(f"\n{classification_report(y_test, y_pred)}")
83
+
84
+ # ── Cross-validation ────────────────────────────────
85
+ print("[CV] 5-Fold Cross-Validation...")
86
+ cv_scores = cross_val_score(model, embeddings, labels, cv=5, scoring="accuracy")
87
+ print(f" CV Accuracy: {cv_scores.mean():.1%} +/- {cv_scores.std():.1%}")
88
+ print(f" Fold scores: {[f'{s:.1%}' for s in cv_scores]}")
89
+
90
+ # ── Confusion Matrix ────────────────────────────────
91
+ print("\n[MATRIX] Confusion Matrix:")
92
+ cm = confusion_matrix(y_test, y_pred, labels=sorted(set(labels)))
93
+ cm_labels = sorted(set(labels))
94
+ header = " " + " ".join(f"{label:>10}" for label in cm_labels)
95
+ print(header)
96
+ for i, row in enumerate(cm):
97
+ row_str = " ".join(f"{v:>10}" for v in row)
98
+ print(f" {cm_labels[i]:>8} {row_str}")
99
+
100
+ # ── Save model ──────────────────────────────────────
101
+ print(f"\n[SAVE] Saving model to {model_path}")
102
+ import joblib
103
+ joblib.dump(model, model_path)
104
+ model_size = os.path.getsize(model_path)
105
+ print(f" Model size: {model_size / 1024:.1f} KB")
106
+
107
+ # ── Quick inference test ────────────────────────────
108
+ print("\n[TEST] Quick inference test:")
109
+ test_queries = [
110
+ "hello",
111
+ "show top 5 employees by salary",
112
+ "what tables are there",
113
+ "show me some data",
114
+ "total revenue by region",
115
+ "thanks",
116
+ ]
117
+ test_embeddings = encoder.encode(test_queries)
118
+ test_preds = model.predict(test_embeddings)
119
+ test_probs = model.predict_proba(test_embeddings)
120
+
121
+ for query, pred, probs in zip(test_queries, test_preds, test_probs):
122
+ conf = max(probs)
123
+ print(f" '{query}' -> {pred} ({conf:.0%})")
124
+
125
+ print("\n[DONE] Training complete!")
126
+ return accuracy
127
+
128
+
129
+ if __name__ == "__main__":
130
+ main()
backend/app/agents/models/training_data.json ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {"text": "hello", "label": "chat"},
3
+ {"text": "hi", "label": "chat"},
4
+ {"text": "hey there", "label": "chat"},
5
+ {"text": "good morning", "label": "chat"},
6
+ {"text": "good afternoon", "label": "chat"},
7
+ {"text": "good evening", "label": "chat"},
8
+ {"text": "howdy", "label": "chat"},
9
+ {"text": "what's up", "label": "chat"},
10
+ {"text": "yo", "label": "chat"},
11
+ {"text": "greetings", "label": "chat"},
12
+ {"text": "namaste", "label": "chat"},
13
+ {"text": "thanks", "label": "chat"},
14
+ {"text": "thank you", "label": "chat"},
15
+ {"text": "thanks a lot", "label": "chat"},
16
+ {"text": "thank you so much", "label": "chat"},
17
+ {"text": "cool, thanks", "label": "chat"},
18
+ {"text": "great, thank you!", "label": "chat"},
19
+ {"text": "bye", "label": "chat"},
20
+ {"text": "goodbye", "label": "chat"},
21
+ {"text": "see you later", "label": "chat"},
22
+ {"text": "see ya", "label": "chat"},
23
+ {"text": "ok bye", "label": "chat"},
24
+ {"text": "what can you do", "label": "chat"},
25
+ {"text": "what are you", "label": "chat"},
26
+ {"text": "who are you", "label": "chat"},
27
+ {"text": "how do you work", "label": "chat"},
28
+ {"text": "what is plainsql", "label": "chat"},
29
+ {"text": "tell me about yourself", "label": "chat"},
30
+ {"text": "help me", "label": "chat"},
31
+ {"text": "what can I ask you", "label": "chat"},
32
+ {"text": "how do I use this", "label": "chat"},
33
+ {"text": "are you an AI", "label": "chat"},
34
+ {"text": "how is the weather", "label": "chat"},
35
+ {"text": "tell me a joke", "label": "chat"},
36
+ {"text": "yes", "label": "chat"},
37
+ {"text": "no", "label": "chat"},
38
+ {"text": "ok", "label": "chat"},
39
+ {"text": "sure", "label": "chat"},
40
+ {"text": "nope", "label": "chat"},
41
+ {"text": "got it", "label": "chat"},
42
+ {"text": "awesome", "label": "chat"},
43
+ {"text": "nice", "label": "chat"},
44
+ {"text": "cool", "label": "chat"},
45
+ {"text": "great work", "label": "chat"},
46
+ {"text": "perfect", "label": "chat"},
47
+ {"text": "can you help me with something", "label": "chat"},
48
+ {"text": "I don't understand", "label": "chat"},
49
+ {"text": "what does this mean", "label": "chat"},
50
+ {"text": "who made you", "label": "chat"},
51
+ {"text": "do you know about machine learning", "label": "chat"},
52
+
53
+ {"text": "show all accounts with high churn risk", "label": "sql"},
54
+ {"text": "list enterprise accounts by health score", "label": "sql"},
55
+ {"text": "what is the total contracted ARR", "label": "sql"},
56
+ {"text": "show total ARR by customer segment", "label": "sql"},
57
+ {"text": "how many active subscriptions do we have", "label": "sql"},
58
+ {"text": "list past due subscriptions", "label": "sql"},
59
+ {"text": "show open P1 support tickets", "label": "sql"},
60
+ {"text": "which accounts have the most support tickets", "label": "sql"},
61
+ {"text": "show monthly invoice revenue trends", "label": "sql"},
62
+ {"text": "what is the total revenue from paid invoices", "label": "sql"},
63
+ {"text": "show overdue invoices by account", "label": "sql"},
64
+ {"text": "list all opportunities in negotiation stage", "label": "sql"},
65
+ {"text": "what is the pipeline forecast by category", "label": "sql"},
66
+ {"text": "show closed-won deals this year", "label": "sql"},
67
+ {"text": "rank sales reps by ARR", "label": "sql"},
68
+ {"text": "which opportunities have stalled", "label": "sql"},
69
+ {"text": "show product usage trends", "label": "sql"},
70
+ {"text": "rank workspaces by query volume", "label": "sql"},
71
+ {"text": "what is the p95 latency by feature", "label": "sql"},
72
+ {"text": "show failed query count by workspace", "label": "sql"},
73
+ {"text": "list employees in the engineering department", "label": "sql"},
74
+ {"text": "show the salary budget by department", "label": "sql"},
75
+ {"text": "how many employees are in each department", "label": "sql"},
76
+ {"text": "show top accounts by revenue with ticket count", "label": "sql"},
77
+ {"text": "calculate net revenue retention by segment", "label": "sql"},
78
+ {"text": "what percentage of ARR is at high churn risk", "label": "sql"},
79
+ {"text": "show payment failure rate by segment", "label": "sql"},
80
+ {"text": "compare ticket volume between P1 and P2", "label": "sql"},
81
+ {"text": "show CSAT scores by ticket category", "label": "sql"},
82
+ {"text": "find accounts with high ARR but low health scores", "label": "sql"},
83
+ {"text": "show SLA breach count by account", "label": "sql"},
84
+ {"text": "list executive sponsors at strategic accounts", "label": "sql"},
85
+ {"text": "show workspace user count by role", "label": "sql"},
86
+ {"text": "what are the top loss reasons for opportunities", "label": "sql"},
87
+ {"text": "show quarterly revenue from invoices", "label": "sql"},
88
+ {"text": "compare ARR between North America and Europe", "label": "sql"},
89
+ {"text": "which accounts have subscriptions but no product usage", "label": "sql"},
90
+ {"text": "show compute usage by account segment", "label": "sql"},
91
+ {"text": "list sev1 incidents with root cause", "label": "sql"},
92
+ {"text": "show average deal cycle for closed-won opportunities", "label": "sql"},
93
+ {"text": "what is the conversion rate by opportunity source", "label": "sql"},
94
+ {"text": "show ticket resolution time by priority", "label": "sql"},
95
+ {"text": "how much revenue did we collect last quarter", "label": "sql"},
96
+ {"text": "which features have the highest failure rate", "label": "sql"},
97
+ {"text": "show the discount percentage by plan type", "label": "sql"},
98
+ {"text": "rank accounts by employee count", "label": "sql"},
99
+ {"text": "list all cancelled subscriptions with ARR", "label": "sql"},
100
+ {"text": "show query audit log success rate by route", "label": "sql"},
101
+ {"text": "find the average first response time for P1 tickets", "label": "sql"},
102
+ {"text": "show accounts in the 500k plus ARR band", "label": "sql"},
103
+ {"text": "what is the average contracted ARR per plan", "label": "sql"},
104
+ {"text": "show incident frequency by affected product", "label": "sql"},
105
+ {"text": "list contacts in the data department", "label": "sql"},
106
+ {"text": "show total seats purchased by plan", "label": "sql"},
107
+ {"text": "hey can you show me total ARR by segment", "label": "sql"},
108
+ {"text": "please show accounts with high churn risk", "label": "sql"},
109
+ {"text": "I want to see the pipeline forecast", "label": "sql"},
110
+ {"text": "give me subscription renewal rates", "label": "sql"},
111
+ {"text": "what does our support ticket volume look like", "label": "sql"},
112
+ {"text": "how much revenue is at risk from churning accounts", "label": "sql"},
113
+ {"text": "break down invoice revenue by region", "label": "sql"},
114
+ {"text": "which reps are hitting their quota", "label": "sql"},
115
+ {"text": "show me accounts that might churn", "label": "sql"},
116
+ {"text": "how are our workspaces performing", "label": "sql"},
117
+ {"text": "what is the trend in product adoption", "label": "sql"},
118
+
119
+ {"text": "show me data", "label": "ambiguous"},
120
+ {"text": "what about the data", "label": "ambiguous"},
121
+ {"text": "tell me about the information", "label": "ambiguous"},
122
+ {"text": "show me everything", "label": "ambiguous"},
123
+ {"text": "what do we have", "label": "ambiguous"},
124
+ {"text": "give me details", "label": "ambiguous"},
125
+ {"text": "can you check something", "label": "ambiguous"},
126
+ {"text": "look up some records", "label": "ambiguous"},
127
+ {"text": "find something for me", "label": "ambiguous"},
128
+ {"text": "what's in the system", "label": "ambiguous"},
129
+ {"text": "pull up some info", "label": "ambiguous"},
130
+ {"text": "show me the numbers", "label": "ambiguous"},
131
+ {"text": "give me a report", "label": "ambiguous"},
132
+ {"text": "can you query the database", "label": "ambiguous"},
133
+ {"text": "what does the data say", "label": "ambiguous"},
134
+ {"text": "run a query for me", "label": "ambiguous"},
135
+ {"text": "I need some data", "label": "ambiguous"},
136
+ {"text": "show results", "label": "ambiguous"},
137
+ {"text": "give me an overview", "label": "ambiguous"},
138
+ {"text": "what information is available", "label": "ambiguous"},
139
+ {"text": "any interesting trends", "label": "ambiguous"},
140
+ {"text": "show me the latest", "label": "ambiguous"},
141
+ {"text": "how is everything going", "label": "ambiguous"},
142
+ {"text": "what are the key metrics", "label": "ambiguous"},
143
+ {"text": "analyze the data", "label": "ambiguous"},
144
+
145
+ {"text": "what tables are in the database", "label": "meta_query"},
146
+ {"text": "show tables", "label": "meta_query"},
147
+ {"text": "list tables", "label": "meta_query"},
148
+ {"text": "what tables do you have", "label": "meta_query"},
149
+ {"text": "describe the accounts table", "label": "meta_query"},
150
+ {"text": "what columns are in the subscriptions table", "label": "meta_query"},
151
+ {"text": "show me the schema", "label": "meta_query"},
152
+ {"text": "what is the database structure", "label": "meta_query"},
153
+ {"text": "describe table support_tickets", "label": "meta_query"},
154
+ {"text": "what columns does the invoices table have", "label": "meta_query"},
155
+ {"text": "show the database schema", "label": "meta_query"},
156
+ {"text": "what data is stored in this database", "label": "meta_query"},
157
+ {"text": "list all table names", "label": "meta_query"},
158
+ {"text": "show structure of opportunities table", "label": "meta_query"},
159
+ {"text": "what fields does the product_usage_daily table contain", "label": "meta_query"},
160
+ {"text": "describe the schema for workspaces", "label": "meta_query"},
161
+ {"text": "what are the column names in query_audit_log", "label": "meta_query"},
162
+ {"text": "show me the table definitions", "label": "meta_query"},
163
+ {"text": "what relationships exist between tables", "label": "meta_query"},
164
+ {"text": "how are the tables connected", "label": "meta_query"},
165
+ {"text": "show foreign keys", "label": "meta_query"},
166
+ {"text": "what is the primary key of accounts", "label": "meta_query"},
167
+ {"text": "tell me about the database tables", "label": "meta_query"},
168
+ {"text": "list columns in departments", "label": "meta_query"},
169
+ {"text": "show me what data you can access", "label": "meta_query"},
170
+ {"text": "describe the employees table", "label": "meta_query"},
171
+ {"text": "what tables contain revenue data", "label": "meta_query"},
172
+ {"text": "how is the subscriptions table related to accounts", "label": "meta_query"}
173
+ ]
backend/app/agents/orchestrator.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LangGraph Orchestrator β€” Wires all 7 agents into a DAG with conditional routing.
3
+ This is the core of the multi-agent architecture.
4
+ Includes pipeline timeout protection, output guardrails, and graceful degradation.
5
+ """
6
+
7
+ import uuid
8
+ import time
9
+ import asyncio
10
+ import threading
11
+ import structlog
12
+ from langgraph.graph import StateGraph, END
13
+
14
+ from app.agents.state import AgentState
15
+ from app.agents.query_understanding import query_understanding_node
16
+ from app.agents.schema_retrieval import schema_retrieval_node
17
+ from app.agents.sql_generation import sql_generation_node
18
+ from app.agents.sql_validation import sql_validation_node, route_validation
19
+ from app.agents.execution import execution_node
20
+ from app.agents.visualization import visualization_node
21
+ from app.agents.result_summary import result_summary_node
22
+ from app.agents.guardrails import OutputGuardrail
23
+
24
+ logger = structlog.get_logger()
25
+
26
+ # Maximum time (seconds) the full pipeline is allowed to run
27
+ PIPELINE_TIMEOUT_SECONDS = 60
28
+
29
+
30
+ class AgentOrchestrator:
31
+ """
32
+ Multi-agent orchestrator using LangGraph StateGraph.
33
+
34
+ Flow:
35
+ understand_query β†’ [chat? β†’ END]
36
+ β†’ retrieve_schema β†’ generate_sql β†’ validate_sql
37
+ β†’ [valid? β†’ execute β†’ visualize β†’ END]
38
+ β†’ [invalid? β†’ retry generate_sql (max 3)]
39
+ β†’ [blocked? β†’ END with error]
40
+ """
41
+
42
+ def __init__(self, llm_router, rag_retriever, db_pool):
43
+ self.llm_router = llm_router
44
+ self.rag_retriever = rag_retriever
45
+ self.db_pool = db_pool
46
+
47
+ # ── Initialize Output Guardrail with live schema ──
48
+ self.guardrail = self._init_guardrail(db_pool)
49
+
50
+ # ── Initialize Semantic Cache ──
51
+ self.semantic_cache = self._init_semantic_cache()
52
+
53
+ self.graph = self._build_graph()
54
+
55
+ @staticmethod
56
+ def _init_semantic_cache():
57
+ """Initialize the semantic cache for query deduplication."""
58
+ try:
59
+ from app.cache.semantic_cache import SemanticCache
60
+ cache = SemanticCache(similarity_threshold=0.95, ttl_seconds=300)
61
+ if cache.available:
62
+ logger.info("semantic_cache_initialized")
63
+ return cache
64
+ logger.info("semantic_cache_disabled", reason="encoder_unavailable")
65
+ except Exception as e:
66
+ logger.info("semantic_cache_disabled", reason=str(e))
67
+ return None
68
+
69
+ @staticmethod
70
+ def _init_guardrail(db_pool) -> OutputGuardrail:
71
+ """Build the OutputGuardrail from the live database schema."""
72
+ try:
73
+ tables = db_pool.get_tables()
74
+ known_columns = {}
75
+ for table in tables:
76
+ cols = db_pool.get_table_schema(table)
77
+ known_columns[table] = {c["name"] for c in cols}
78
+ guardrail = OutputGuardrail(
79
+ known_tables=set(tables),
80
+ known_columns=known_columns,
81
+ )
82
+ logger.info("guardrail_initialized", tables=len(tables))
83
+ return guardrail
84
+ except Exception as e:
85
+ logger.warning("guardrail_init_failed", error=str(e))
86
+ return OutputGuardrail()
87
+
88
+ def _build_graph(self) -> StateGraph:
89
+ """Construct the LangGraph agent pipeline."""
90
+ graph = StateGraph(AgentState)
91
+
92
+ # ── Register agent nodes ─────────────────────────
93
+ graph.add_node("understand_query", self._understand_query)
94
+ graph.add_node("handle_chat", self._handle_chat)
95
+ graph.add_node("handle_meta", self._handle_meta)
96
+ graph.add_node("retrieve_schema", self._retrieve_schema)
97
+ graph.add_node("generate_sql", self._generate_sql)
98
+ graph.add_node("guardrail_check", self._guardrail_check)
99
+ graph.add_node("validate_sql", self._validate_sql)
100
+ graph.add_node("execute_query", self._execute_query)
101
+ graph.add_node("ground_summary", self._ground_summary)
102
+ graph.add_node("visualize", self._visualize)
103
+ graph.add_node("handle_blocked", self._handle_blocked)
104
+
105
+ # ── Entry point ──────────────────────────────────
106
+ graph.set_entry_point("understand_query")
107
+
108
+ # ── Conditional routing after intent classification ──
109
+ graph.add_conditional_edges(
110
+ "understand_query",
111
+ self._route_by_intent,
112
+ {
113
+ "chat": "handle_chat",
114
+ "ambiguous": "handle_chat",
115
+ "meta_query": "retrieve_schema",
116
+ "data_query": "retrieve_schema",
117
+ "aggregation": "retrieve_schema",
118
+ "comparison": "retrieve_schema",
119
+ "explanation": "retrieve_schema",
120
+ },
121
+ )
122
+
123
+ # ── Linear flow ──────────────────────────��──────
124
+ graph.add_conditional_edges(
125
+ "retrieve_schema",
126
+ self._route_after_schema,
127
+ {
128
+ "meta_query": "handle_meta",
129
+ "sql": "generate_sql",
130
+ },
131
+ )
132
+ graph.add_edge("generate_sql", "guardrail_check")
133
+ graph.add_edge("guardrail_check", "validate_sql")
134
+
135
+ # ── Conditional routing after validation ─────────
136
+ graph.add_conditional_edges(
137
+ "validate_sql",
138
+ route_validation,
139
+ {
140
+ "valid": "execute_query",
141
+ "retry": "generate_sql",
142
+ "blocked": "handle_blocked",
143
+ },
144
+ )
145
+
146
+ graph.add_edge("execute_query", "ground_summary")
147
+ graph.add_edge("ground_summary", "visualize")
148
+
149
+ # ── Terminal nodes ───────────────────────────────
150
+ graph.add_edge("visualize", END)
151
+ graph.add_edge("handle_chat", END)
152
+ graph.add_edge("handle_meta", END)
153
+ graph.add_edge("handle_blocked", END)
154
+
155
+ return graph.compile()
156
+
157
+ # ── Node Wrappers (inject dependencies + error isolation) ──
158
+
159
+ def _understand_query(self, state: AgentState) -> dict:
160
+ return self._safe_execute("query_understanding", query_understanding_node, state, self.llm_router)
161
+
162
+ def _retrieve_schema(self, state: AgentState) -> dict:
163
+ return self._safe_execute("schema_retrieval", schema_retrieval_node, state, self.rag_retriever, self.db_pool)
164
+
165
+ def _generate_sql(self, state: AgentState) -> dict:
166
+ return self._safe_execute("sql_generation", sql_generation_node, state, self.llm_router)
167
+
168
+ def _guardrail_check(self, state: AgentState) -> dict:
169
+ """Run output guardrails to catch hallucinated table/column references."""
170
+ return self._safe_execute("guardrail_check", self._run_guardrail, state)
171
+
172
+ def _run_guardrail(self, state: AgentState) -> dict:
173
+ """Execute guardrail validation on the generated SQL."""
174
+ sql = state.get("generated_sql", "")
175
+ if not sql:
176
+ return {}
177
+
178
+ warnings = self.guardrail.validate_sql_references(sql)
179
+ confidence = self.guardrail.score_confidence(sql)
180
+
181
+ if warnings:
182
+ logger.warning(
183
+ "guardrail_warnings",
184
+ trace_id=state.get("trace_id"),
185
+ warnings=warnings,
186
+ confidence=confidence,
187
+ )
188
+
189
+ # If many hallucinations are detected, mark as invalid.
190
+ # Do NOT bump retry_count here β€” only sql_validation_node manages
191
+ # the retry counter. Double-counting caused infinite loops.
192
+ if len(warnings) >= 3:
193
+ return {
194
+ "is_valid": False,
195
+ "validation_errors": [f"Schema grounding failed: {w}" for w in warnings],
196
+ }
197
+
198
+ return {
199
+ "guardrail_warnings": warnings,
200
+ "guardrail_confidence": confidence,
201
+ }
202
+
203
+ def _validate_sql(self, state: AgentState) -> dict:
204
+ return self._safe_execute("sql_validation", sql_validation_node, state)
205
+
206
+ def _execute_query(self, state: AgentState) -> dict:
207
+ return self._safe_execute("execution", execution_node, state, self.db_pool)
208
+
209
+ def _visualize(self, state: AgentState) -> dict:
210
+ return self._safe_execute("visualization", visualization_node, state)
211
+
212
+ def _ground_summary(self, state: AgentState) -> dict:
213
+ """Replace the LLM's pre-execution hallucinated summary with a grounded one."""
214
+ return self._safe_execute("result_summary", result_summary_node, state, self.llm_router)
215
+
216
+ def _safe_execute(self, agent_name: str, func, *args) -> dict:
217
+ """
218
+ Wrapper that catches per-agent exceptions for graceful degradation.
219
+ Records per-agent latency metrics and OpenTelemetry spans.
220
+ Non-critical agents (visualization) failing won't crash the pipeline.
221
+ """
222
+ from app.observability.metrics import metrics
223
+ from app.observability.tracing import trace_span
224
+
225
+ trace_id = args[0].get("trace_id", "unknown") if args else "unknown"
226
+
227
+ with trace_span(f"agent.{agent_name}", {"trace_id": trace_id, "agent": agent_name}):
228
+ start = time.perf_counter()
229
+ try:
230
+ result = func(*args)
231
+ elapsed_ms = round((time.perf_counter() - start) * 1000, 2)
232
+ metrics.observe("plainsql_agent_latency_ms", elapsed_ms, {"agent": agent_name})
233
+ logger.info("agent_completed", agent=agent_name, elapsed_ms=elapsed_ms,
234
+ trace_id=trace_id)
235
+ return result
236
+ except Exception as e:
237
+ elapsed_ms = round((time.perf_counter() - start) * 1000, 2)
238
+ metrics.observe("plainsql_agent_latency_ms", elapsed_ms, {"agent": agent_name})
239
+ metrics.increment("plainsql_agent_errors_total", {"agent": agent_name})
240
+ logger.error(
241
+ "agent_failed",
242
+ agent=agent_name,
243
+ error=str(e),
244
+ elapsed_ms=elapsed_ms,
245
+ trace_id=trace_id,
246
+ )
247
+ # For non-critical agents, return empty results
248
+ non_critical = {"visualization", "result_summary"}
249
+ if agent_name in non_critical:
250
+ return {
251
+ "chart_config": None,
252
+ "chart_type": None,
253
+ "insights": [f"Visualization skipped due to error: {str(e)[:80]}"],
254
+ "follow_up_questions": [],
255
+ }
256
+ # For critical agents, propagate the error state.
257
+ # MUST preserve retry_count to prevent infinite loops
258
+ # when _safe_execute catches an exception.
259
+ return {
260
+ "error": f"{agent_name} failed: {str(e)}",
261
+ "error_agent": agent_name,
262
+ "retry_count": args[0].get("retry_count", 0) if args else 0,
263
+ }
264
+
265
+ def _handle_chat(self, state: AgentState) -> dict:
266
+ """Terminal node for conversational responses."""
267
+ return {
268
+ "friendly_message": state.get(
269
+ "friendly_message",
270
+ "Hello. I can help you query your database in plain English.",
271
+ ),
272
+ "query_results": [],
273
+ "row_count": 0,
274
+ "follow_up_questions": [
275
+ "Show top 5 employees by salary",
276
+ "Total sales revenue by region",
277
+ "List all products with low stock",
278
+ ],
279
+ }
280
+
281
+ def _handle_meta(self, state: AgentState) -> dict:
282
+ """Terminal node for schema/meta queries."""
283
+ schema = state.get("relevant_schema", "")
284
+ tables = state.get("relevant_tables", [])
285
+
286
+ # Format schema info as friendly message
287
+ table_list = ", ".join(tables) if tables else "No tables found"
288
+ return {
289
+ "friendly_message": f"Your database contains these tables: **{table_list}**\n\n```\n{schema}\n```",
290
+ "query_results": [],
291
+ "row_count": 0,
292
+ "follow_up_questions": [f"Show data from {t}" for t in tables[:3]],
293
+ }
294
+
295
+ def _handle_blocked(self, state: AgentState) -> dict:
296
+ """Terminal node when SQL validation fails after max retries."""
297
+ errors = state.get("validation_errors", [])
298
+ return {
299
+ "error": "Query blocked by safety layer",
300
+ "error_agent": "sql_validation",
301
+ "friendly_message": (
302
+ "πŸ›‘οΈ **Security Alert**: Your query was blocked by the safety system.\n\n"
303
+ f"Reasons: {', '.join(errors)}\n\n"
304
+ "I can only perform safe, read-only (SELECT) operations."
305
+ ),
306
+ "query_results": [],
307
+ "row_count": 0,
308
+ }
309
+
310
+ # ── Routing Functions ────────────────────────────────
311
+
312
+ @staticmethod
313
+ def _route_by_intent(state: AgentState) -> str:
314
+ """Route to appropriate handler based on classified intent."""
315
+ route_intent = state.get("route_intent", state.get("intent", "data_query"))
316
+ valid_routes = {"chat", "ambiguous", "meta_query", "data_query", "aggregation", "comparison", "explanation"}
317
+ return route_intent if route_intent in valid_routes else "data_query"
318
+
319
+ @staticmethod
320
+ def _route_after_schema(state: AgentState) -> str:
321
+ """Send schema/meta requests to the meta handler; SQL requests continue."""
322
+ if state.get("route_intent") == "meta_query":
323
+ return "meta_query"
324
+ return "sql"
325
+
326
+ # ── Public API ───────────────────────────────────────
327
+
328
+ def process_query(
329
+ self,
330
+ user_query: str,
331
+ conversation_history: list[dict] = None,
332
+ tenant_id: str = "default",
333
+ user_role: str = "analyst",
334
+ ) -> AgentState:
335
+ """
336
+ Process a natural language query through the full agent pipeline (sync).
337
+ Returns the final AgentState with all results.
338
+ Enforces a pipeline-level timeout to prevent runaway processing.
339
+ """
340
+ trace_id = str(uuid.uuid4())[:8]
341
+
342
+ initial_state: AgentState = {
343
+ "user_query": user_query,
344
+ "conversation_history": conversation_history or [],
345
+ "tenant_id": tenant_id,
346
+ "user_role": user_role,
347
+ "trace_id": trace_id,
348
+ "retry_count": 0,
349
+ "validation_errors": [],
350
+ }
351
+
352
+ logger.info(
353
+ "pipeline_started",
354
+ trace_id=trace_id,
355
+ query=user_query,
356
+ tenant_id=tenant_id,
357
+ )
358
+
359
+ # ── Semantic cache check ─────────────────────────
360
+ if self.semantic_cache:
361
+ cached = self.semantic_cache.get(user_query, tenant_id=tenant_id)
362
+ if cached:
363
+ cached["trace_id"] = trace_id
364
+ cached["cache_hit"] = True
365
+ logger.info("semantic_cache_hit", trace_id=trace_id, query=user_query[:60])
366
+ return cached
367
+
368
+ start_time = time.perf_counter()
369
+
370
+ # ── Real timeout: interrupt the blocking thread after deadline ──
371
+ # threading.Timer fires on the calling thread and raises TimeoutError,
372
+ # which propagates out of graph.invoke() without leaving zombie threads.
373
+ timeout_fired = threading.Event()
374
+
375
+ def _timeout_interrupt():
376
+ timeout_fired.set()
377
+ # Raise into the calling thread via ctypes β€” safely interrupts
378
+ # the blocking LangGraph call.
379
+ import ctypes
380
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(
381
+ ctypes.c_ulong(threading.main_thread().ident),
382
+ ctypes.py_object(TimeoutError),
383
+ )
384
+
385
+ timer = threading.Timer(PIPELINE_TIMEOUT_SECONDS, _timeout_interrupt)
386
+ timer.daemon = True
387
+ timer.start()
388
+
389
+ try:
390
+ final_state = self.graph.invoke(
391
+ initial_state,
392
+ config={"recursion_limit": 50},
393
+ )
394
+ timer.cancel() # Disarm if pipeline completed in time
395
+
396
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
397
+ final_state["execution_time_ms"] = elapsed_ms
398
+
399
+ # Cache successful data query results
400
+ if (
401
+ self.semantic_cache
402
+ and not final_state.get("error")
403
+ and final_state.get("query_results")
404
+ ):
405
+ self.semantic_cache.set(user_query, dict(final_state), tenant_id=tenant_id)
406
+
407
+ logger.info(
408
+ "pipeline_completed",
409
+ trace_id=trace_id,
410
+ total_time_ms=elapsed_ms,
411
+ intent=final_state.get("intent"),
412
+ row_count=final_state.get("row_count", 0),
413
+ has_error=bool(final_state.get("error")),
414
+ )
415
+ return final_state
416
+
417
+ except TimeoutError:
418
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
419
+ logger.error(
420
+ "pipeline_timeout",
421
+ trace_id=trace_id,
422
+ elapsed_ms=elapsed_ms,
423
+ timeout_seconds=PIPELINE_TIMEOUT_SECONDS,
424
+ )
425
+ return {
426
+ **initial_state,
427
+ "error": f"Pipeline timed out after {PIPELINE_TIMEOUT_SECONDS}s",
428
+ "error_agent": "orchestrator",
429
+ "friendly_message": "The query took too long to process. Try a simpler question.",
430
+ "query_results": [],
431
+ "row_count": 0,
432
+ "execution_time_ms": elapsed_ms,
433
+ }
434
+
435
+ except Exception as e:
436
+ timer.cancel()
437
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
438
+ logger.error("pipeline_failed", trace_id=trace_id, error=str(e), elapsed_ms=elapsed_ms)
439
+ return {
440
+ **initial_state,
441
+ "error": f"Pipeline error: {str(e)}",
442
+ "error_agent": "orchestrator",
443
+ "friendly_message": "An unexpected error occurred. Please try again.",
444
+ "query_results": [],
445
+ "row_count": 0,
446
+ "execution_time_ms": elapsed_ms,
447
+ }
448
+
449
+ async def aprocess_query(
450
+ self,
451
+ user_query: str,
452
+ conversation_history: list[dict] = None,
453
+ tenant_id: str = "default",
454
+ user_role: str = "analyst",
455
+ ) -> AgentState:
456
+ """
457
+ Async version of process_query.
458
+ Runs the synchronous LangGraph pipeline in a thread pool
459
+ to avoid blocking the FastAPI event loop.
460
+ asyncio.wait_for() enforces a hard deadline: if the thread
461
+ doesn't complete within PIPELINE_TIMEOUT_SECONDS the coroutine
462
+ is cancelled and a timeout error state is returned.
463
+ """
464
+ try:
465
+ return await asyncio.wait_for(
466
+ asyncio.to_thread(
467
+ self.process_query,
468
+ user_query=user_query,
469
+ conversation_history=conversation_history,
470
+ tenant_id=tenant_id,
471
+ user_role=user_role,
472
+ ),
473
+ timeout=PIPELINE_TIMEOUT_SECONDS,
474
+ )
475
+ except asyncio.TimeoutError:
476
+ logger.error(
477
+ "async_pipeline_timeout",
478
+ query=user_query[:80],
479
+ timeout_seconds=PIPELINE_TIMEOUT_SECONDS,
480
+ )
481
+ return {
482
+ "user_query": user_query,
483
+ "error": f"Pipeline timed out after {PIPELINE_TIMEOUT_SECONDS}s",
484
+ "error_agent": "orchestrator",
485
+ "friendly_message": "The query took too long to process. Try a simpler question.",
486
+ "query_results": [],
487
+ "row_count": 0,
488
+ "execution_time_ms": PIPELINE_TIMEOUT_SECONDS * 1000.0,
489
+ }
490
+
491
+ async def aprocess_query_parallel(
492
+ self,
493
+ user_query: str,
494
+ conversation_history: list[dict] = None,
495
+ tenant_id: str = "default",
496
+ user_role: str = "analyst",
497
+ ) -> AgentState:
498
+ """
499
+ Optimized async pipeline that runs independent stages concurrently.
500
+
501
+ Instead of the sequential flow:
502
+ intent (200ms) β†’ schema (400ms) β†’ generate (800ms)
503
+
504
+ This runs:
505
+ intent + schema (400ms concurrent) β†’ generate (800ms)
506
+
507
+ Saving ~200ms per query by overlapping independent stages.
508
+
509
+ If the intent is 'chat', the schema retrieval result is discarded.
510
+ Falls back to the sequential aprocess_query on any error.
511
+ """
512
+ trace_id = str(uuid.uuid4())[:8]
513
+
514
+ try:
515
+ start_time = time.perf_counter()
516
+
517
+ # Semantic cache check
518
+ if self.semantic_cache:
519
+ cached = self.semantic_cache.get(user_query, tenant_id=tenant_id)
520
+ if cached:
521
+ cached["trace_id"] = trace_id
522
+ cached["cache_hit"] = True
523
+ logger.info("parallel_cache_hit", trace_id=trace_id)
524
+ return cached
525
+
526
+ initial_state: AgentState = {
527
+ "user_query": user_query,
528
+ "conversation_history": conversation_history or [],
529
+ "tenant_id": tenant_id,
530
+ "user_role": user_role,
531
+ "trace_id": trace_id,
532
+ "retry_count": 0,
533
+ "validation_errors": [],
534
+ }
535
+
536
+ # ── Run intent + schema retrieval in parallel ──
537
+ intent_task = asyncio.to_thread(
538
+ query_understanding_node, initial_state, self.llm_router
539
+ )
540
+ schema_task = asyncio.to_thread(
541
+ schema_retrieval_node, initial_state, self.rag_retriever, self.db_pool
542
+ )
543
+
544
+ # Both start immediately; gather waits for both
545
+ intent_result, schema_result = await asyncio.wait_for(
546
+ asyncio.gather(intent_task, schema_task),
547
+ timeout=PIPELINE_TIMEOUT_SECONDS,
548
+ )
549
+
550
+ # Merge results
551
+ initial_state.update(intent_result)
552
+ intent = initial_state.get("intent", "data_query")
553
+
554
+ # For chat/ambiguous intents, skip SQL pipeline entirely
555
+ if intent in ("chat", "ambiguous"):
556
+ initial_state.update(
557
+ self._safe_execute("handle_chat", self._handle_chat, initial_state)
558
+ )
559
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
560
+ initial_state["execution_time_ms"] = elapsed_ms
561
+ return initial_state
562
+
563
+ # For data queries, use schema results and continue with full pipeline
564
+ initial_state.update(schema_result)
565
+
566
+ # Fall back to sequential pipeline for the remaining stages
567
+ # (generate β†’ guardrail β†’ validate β†’ execute β†’ summarize β†’ visualize)
568
+ # This ensures circuit breakers, retry loops, and guardrails all run correctly
569
+ return await self.aprocess_query(
570
+ user_query=user_query,
571
+ conversation_history=conversation_history,
572
+ tenant_id=tenant_id,
573
+ user_role=user_role,
574
+ )
575
+
576
+ except asyncio.TimeoutError:
577
+ logger.error("parallel_pipeline_timeout", trace_id=trace_id)
578
+ return {
579
+ "user_query": user_query,
580
+ "trace_id": trace_id,
581
+ "error": f"Pipeline timed out after {PIPELINE_TIMEOUT_SECONDS}s",
582
+ "error_agent": "orchestrator",
583
+ "friendly_message": "The query took too long. Try a simpler question.",
584
+ "query_results": [],
585
+ "row_count": 0,
586
+ "execution_time_ms": PIPELINE_TIMEOUT_SECONDS * 1000.0,
587
+ }
588
+
589
+ except Exception as e:
590
+ # Fallback to sequential pipeline
591
+ logger.warning("parallel_pipeline_fallback", error=str(e), trace_id=trace_id)
592
+ return await self.aprocess_query(
593
+ user_query=user_query,
594
+ conversation_history=conversation_history,
595
+ tenant_id=tenant_id,
596
+ user_role=user_role,
597
+ )
598
+
599
+ # ── Progressive Streaming Pipeline ───────────────────────
600
+
601
+ async def aprocess_query_streaming(
602
+ self,
603
+ user_query: str,
604
+ conversation_history: list[dict] = None,
605
+ tenant_id: str = "default",
606
+ user_role: str = "analyst",
607
+ ):
608
+ """
609
+ Async generator that yields SSE-ready event dicts after each pipeline stage.
610
+
611
+ Instead of running the full LangGraph graph.invoke() and returning everything
612
+ at once, this method manually walks the pipeline nodes and yields intermediate
613
+ state as each stage completes. This allows the SSE endpoint to progressively
614
+ stream intent, schema context, SQL, data results, and summary tokens to the
615
+ frontend β€” eliminating 5+ seconds of dead air.
616
+
617
+ The LangGraph DAG (self.graph) is NOT used here β€” this is a parallel code path
618
+ optimized for real-time streaming. The DAG remains for batch/evaluation callers.
619
+
620
+ Yields dicts with a 'type' key:
621
+ - {'type': 'intent', 'intent': ..., 'complexity': ...}
622
+ - {'type': 'stage', 'stage': 'retrieval', 'message': ...}
623
+ - {'type': 'sql', 'sql': ..., 'explanation': ...}
624
+ - {'type': 'results', 'data': [...], 'row_count': ..., ...}
625
+ - {'type': 'summary_token', 'token': ...}
626
+ - {'type': 'message', 'message': ..., 'insights': [...], ...}
627
+ - {'type': 'done', 'total_time_ms': ...}
628
+ """
629
+ from app.agents.query_understanding import query_understanding_node
630
+ from app.agents.schema_retrieval import schema_retrieval_node
631
+ from app.agents.sql_generation import sql_generation_node
632
+ from app.agents.sql_validation import sql_validation_node, route_validation
633
+ from app.agents.execution import execution_node
634
+ from app.agents.visualization import visualization_node
635
+
636
+ trace_id = str(uuid.uuid4())[:8]
637
+ start_time = time.perf_counter()
638
+
639
+ state: AgentState = {
640
+ "user_query": user_query,
641
+ "conversation_history": conversation_history or [],
642
+ "tenant_id": tenant_id,
643
+ "user_role": user_role,
644
+ "trace_id": trace_id,
645
+ "retry_count": 0,
646
+ "validation_errors": [],
647
+ }
648
+
649
+ logger.info("streaming_pipeline_started", trace_id=trace_id, query=user_query[:80])
650
+
651
+ # ── Semantic cache check ─────────────────────────
652
+ if self.semantic_cache:
653
+ cached = self.semantic_cache.get(user_query, tenant_id=tenant_id)
654
+ if cached:
655
+ cached["trace_id"] = trace_id
656
+ cached["cache_hit"] = True
657
+ logger.info("streaming_cache_hit", trace_id=trace_id)
658
+ yield {"type": "stage", "stage": "cache_hit", "message": "Retrieved from cache..."}
659
+ yield {"type": "intent", "intent": cached.get("intent", ""), "complexity": cached.get("complexity", "")}
660
+ sql = cached.get("sanitized_sql") or cached.get("generated_sql", "")
661
+ if sql:
662
+ yield {"type": "sql", "sql": sql, "explanation": cached.get("sql_explanation", "")}
663
+ yield {
664
+ "type": "results",
665
+ "data": cached.get("query_results", [])[:100],
666
+ "row_count": cached.get("row_count", 0),
667
+ "execution_time_ms": 0,
668
+ }
669
+ yield {
670
+ "type": "message",
671
+ "message": cached.get("friendly_message", ""),
672
+ "insights": cached.get("insights", []),
673
+ "follow_ups": cached.get("follow_up_questions", []),
674
+ }
675
+ elapsed = round((time.perf_counter() - start_time) * 1000, 2)
676
+ yield {"type": "done", "total_time_ms": elapsed, "cached": True}
677
+ return
678
+
679
+ try:
680
+ # ── Stage 1: Intent Classification (~5ms heuristic) ──
681
+ yield {"type": "stage", "stage": "classifying", "message": "Understanding your question..."}
682
+ intent_result = await asyncio.to_thread(
683
+ query_understanding_node, state, self.llm_router
684
+ )
685
+ state.update(intent_result)
686
+
687
+ intent = state.get("intent", "data_query")
688
+ route_intent = state.get("route_intent", intent)
689
+
690
+ yield {
691
+ "type": "intent",
692
+ "intent": intent,
693
+ "complexity": state.get("complexity", ""),
694
+ "route_intent": route_intent,
695
+ }
696
+
697
+ # ── Chat fast-path ───────────────────────────────
698
+ if intent in ("chat", "ambiguous"):
699
+ chat_result = self._handle_chat(state)
700
+ state.update(chat_result)
701
+ yield {
702
+ "type": "message",
703
+ "message": state.get("friendly_message", ""),
704
+ "insights": [],
705
+ "follow_ups": state.get("follow_up_questions", []),
706
+ }
707
+ elapsed = round((time.perf_counter() - start_time) * 1000, 2)
708
+ yield {"type": "done", "total_time_ms": elapsed, "chat_mode": True}
709
+ return
710
+
711
+ # ── Stage 2: Schema Retrieval (~100ms) ───────────
712
+ yield {"type": "stage", "stage": "retrieving", "message": "Retrieving schema context..."}
713
+ schema_result = await asyncio.to_thread(
714
+ schema_retrieval_node, state, self.rag_retriever, self.db_pool
715
+ )
716
+ state.update(schema_result)
717
+
718
+ # Handle meta_query
719
+ if route_intent == "meta_query":
720
+ meta_result = self._handle_meta(state)
721
+ state.update(meta_result)
722
+ yield {
723
+ "type": "message",
724
+ "message": state.get("friendly_message", ""),
725
+ "insights": [],
726
+ "follow_ups": state.get("follow_up_questions", []),
727
+ }
728
+ elapsed = round((time.perf_counter() - start_time) * 1000, 2)
729
+ yield {"type": "done", "total_time_ms": elapsed}
730
+ return
731
+
732
+ # ── Stage 3: SQL Generation (~2s LLM) ────────────
733
+ yield {"type": "stage", "stage": "Generating", "message": "Generating SQL..."}
734
+
735
+ max_retries = 3
736
+ for attempt in range(max_retries):
737
+ gen_result = await asyncio.to_thread(
738
+ sql_generation_node, state, self.llm_router
739
+ )
740
+ state.update(gen_result)
741
+
742
+ sql = state.get("generated_sql", "")
743
+ if not sql:
744
+ break
745
+
746
+ # ── Guardrail check ──────────────────────────
747
+ guardrail_result = self._run_guardrail(state)
748
+ state.update(guardrail_result)
749
+
750
+ # ── Validation ───────────────────────────────
751
+ yield {"type": "stage", "stage": "Validating", "message": "Validating SQL safety..."}
752
+ val_result = await asyncio.to_thread(sql_validation_node, state)
753
+ state.update(val_result)
754
+
755
+ route = route_validation(state)
756
+ if route == "valid":
757
+ break
758
+ elif route == "blocked":
759
+ blocked = self._handle_blocked(state)
760
+ state.update(blocked)
761
+ yield {
762
+ "type": "message",
763
+ "message": state.get("friendly_message", ""),
764
+ "insights": [],
765
+ "follow_ups": [],
766
+ }
767
+ elapsed = round((time.perf_counter() - start_time) * 1000, 2)
768
+ yield {"type": "done", "total_time_ms": elapsed, "blocked": True}
769
+ return
770
+ else: # retry
771
+ state["retry_count"] = state.get("retry_count", 0) + 1
772
+ yield {"type": "stage", "stage": "Generating", "message": f"Regenerating SQL (attempt {attempt + 2})..."}
773
+
774
+ # Stream SQL to frontend immediately
775
+ sql = state.get("sanitized_sql") or state.get("generated_sql", "")
776
+ if sql:
777
+ yield {
778
+ "type": "sql",
779
+ "sql": sql,
780
+ "explanation": state.get("sql_explanation", ""),
781
+ }
782
+
783
+ # ── Stage 4: Database Execution (~100ms) ─────────
784
+ yield {"type": "stage", "stage": "Executing", "message": "Executing query..."}
785
+ exec_result = await asyncio.to_thread(
786
+ execution_node, state, self.db_pool
787
+ )
788
+ state.update(exec_result)
789
+
790
+ # Stream data results IMMEDIATELY β€” don't wait for summary
791
+ yield {
792
+ "type": "results",
793
+ "data": state.get("query_results", [])[:100],
794
+ "row_count": state.get("row_count", 0),
795
+ "execution_time_ms": round((time.perf_counter() - start_time) * 1000, 2),
796
+ }
797
+
798
+ # ── Stage 5: Summary with Token Streaming (~2s, progressive) ──
799
+ yield {"type": "stage", "stage": "Preparing response", "message": "Generating insights..."}
800
+
801
+ results = state.get("query_results", [])
802
+ columns = state.get("column_names", [])
803
+
804
+ if results and columns and self.llm_router:
805
+ try:
806
+ from app.agents.result_summary import astream_summary
807
+ summary_text = ""
808
+ async for token in astream_summary(state, self.llm_router):
809
+ summary_text += token
810
+ yield {"type": "summary_token", "token": token}
811
+
812
+ state["friendly_message"] = summary_text
813
+ except Exception as e:
814
+ logger.warning("streaming_summary_failed", error=str(e), trace_id=trace_id)
815
+ # Fallback to deterministic summary
816
+ from app.agents.result_summary import result_summary_node
817
+ summary_result = result_summary_node(state, self.llm_router)
818
+ state.update(summary_result)
819
+
820
+ # ── Stage 6: Visualization (non-blocking) ────────
821
+ try:
822
+ viz_result = await asyncio.to_thread(visualization_node, state)
823
+ state.update(viz_result)
824
+ except Exception:
825
+ pass # Non-critical
826
+
827
+ # ── Final message event ──────────────────────────
828
+ yield {
829
+ "type": "message",
830
+ "message": state.get("friendly_message", ""),
831
+ "insights": state.get("insights", []),
832
+ "follow_ups": state.get("follow_up_questions", []),
833
+ }
834
+
835
+ elapsed = round((time.perf_counter() - start_time) * 1000, 2)
836
+ state["execution_time_ms"] = elapsed
837
+
838
+ # Cache successful results
839
+ if self.semantic_cache and not state.get("error") and state.get("query_results"):
840
+ self.semantic_cache.set(user_query, dict(state), tenant_id=tenant_id)
841
+
842
+ yield {"type": "done", "total_time_ms": elapsed}
843
+
844
+ logger.info(
845
+ "streaming_pipeline_completed",
846
+ trace_id=trace_id,
847
+ total_time_ms=elapsed,
848
+ intent=intent,
849
+ row_count=state.get("row_count", 0),
850
+ )
851
+
852
+ except Exception as e:
853
+ elapsed = round((time.perf_counter() - start_time) * 1000, 2)
854
+ logger.error("streaming_pipeline_failed", trace_id=trace_id, error=str(e), elapsed_ms=elapsed)
855
+ yield {"type": "error", "error": f"Pipeline error: {str(e)[:200]}"}
856
+ yield {"type": "done", "total_time_ms": elapsed, "error": True}
backend/app/agents/query_understanding.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Query Understanding Agent - classifies user intent and extracts entities.
3
+ First agent in the pipeline. Determines routing for the rest of the graph.
4
+ """
5
+
6
+ import structlog
7
+
8
+ from app.agents.intent_classifier import build_chat_response, classify_intent
9
+ from app.agents.state import AgentState
10
+
11
+ logger = structlog.get_logger()
12
+
13
+ # ── Complexity β†’ retrieval_top_k mapping ────────────────
14
+ # Simple queries need fewer schema docs (less noise, faster).
15
+ # Complex queries need more context to join multiple tables correctly.
16
+ _COMPLEXITY_TOP_K: dict[str, int] = {
17
+ "simple": 3,
18
+ "moderate": 5,
19
+ "complex": 8,
20
+ }
21
+
22
+
23
+ def _is_chat_input(query_lower: str) -> bool:
24
+ """Backward-compatible wrapper for the old chat fast-path helper."""
25
+ return classify_intent(query_lower).intent == "chat"
26
+
27
+
28
+ def _build_greeting_response(user_query: str) -> dict:
29
+ """Backward-compatible wrapper for the old chat response helper."""
30
+ return {
31
+ "intent": "chat",
32
+ "route_intent": "chat",
33
+ "entities": [],
34
+ "complexity": "simple",
35
+ "friendly_message": build_chat_response(user_query),
36
+ }
37
+
38
+
39
+ def query_understanding_node(state: AgentState, llm_router) -> dict:
40
+ """
41
+ Classify the user's intent and extract relevant entities.
42
+
43
+ The chat/sql decision is rule-based and happens before any LLM call so
44
+ casual messages cannot be forced into SQL generation.
45
+ """
46
+ user_query = state["user_query"]
47
+ trace_id = state.get("trace_id", "unknown")
48
+
49
+ logger.info("agent_started", agent="query_understanding", trace_id=trace_id, query=user_query)
50
+
51
+ classification = classify_intent(user_query)
52
+
53
+ if classification.intent == "chat":
54
+ logger.info("intent_classified", intent="chat", method=classification.reason)
55
+ return {
56
+ "intent": "chat",
57
+ "route_intent": "chat",
58
+ "entities": [],
59
+ "complexity": classification.complexity,
60
+ "retrieval_top_k": _COMPLEXITY_TOP_K.get(classification.complexity, 5),
61
+ "friendly_message": build_chat_response(user_query),
62
+ }
63
+
64
+ if classification.intent == "ambiguous":
65
+ logger.info("intent_classified", intent="ambiguous", method=classification.reason)
66
+ return {
67
+ "intent": "ambiguous",
68
+ "route_intent": "chat",
69
+ "entities": _extract_entities_basic(user_query),
70
+ "complexity": "simple",
71
+ "retrieval_top_k": 5, # default β€” ambiguous queries don't reach schema retrieval
72
+ "friendly_message": _build_ambiguous_response(user_query),
73
+ }
74
+
75
+ if classification.route_intent == "meta_query":
76
+ logger.info("intent_classified", intent="sql", route_intent="meta_query", method=classification.reason)
77
+ return {
78
+ "intent": "sql",
79
+ "route_intent": "meta_query",
80
+ "entities": _extract_entities_basic(user_query),
81
+ "complexity": classification.complexity,
82
+ "retrieval_top_k": _COMPLEXITY_TOP_K.get(classification.complexity, 5),
83
+ }
84
+
85
+ # ── Heuristic-only classification (no LLM call) ──────────
86
+ # The rule-based classifier already determines the correct SQL sub-intent.
87
+ # An LLM refinement call was previously made here but added ~800ms of latency
88
+ # without improving downstream SQL generation quality β€” all SQL intents
89
+ # follow the same pipeline path (retrieve β†’ generate β†’ validate β†’ execute).
90
+ route = classification.route_intent
91
+ entities = _extract_entities_basic(user_query)
92
+ complexity = classification.complexity
93
+ top_k = _COMPLEXITY_TOP_K.get(complexity, 5)
94
+
95
+ logger.info(
96
+ "intent_classified",
97
+ intent="sql",
98
+ route_intent=route,
99
+ entities=entities,
100
+ complexity=complexity,
101
+ retrieval_top_k=top_k,
102
+ method="heuristic_fast",
103
+ )
104
+
105
+ return {
106
+ "intent": "sql",
107
+ "route_intent": route,
108
+ "entities": entities,
109
+ "complexity": complexity,
110
+ "retrieval_top_k": top_k,
111
+ }
112
+
113
+
114
+ def _extract_entities_basic(query: str) -> list[str]:
115
+ """
116
+ Extract table names and relevant entities based on keyword matching
117
+ covering all 22 database tables and their common business synonyms.
118
+ """
119
+ query_lower = query.lower()
120
+
121
+ # Map keywords and synonyms to the actual database table names
122
+ keyword_map = {
123
+ "subscriptions": ["subscriptions"],
124
+ "subscription": ["subscriptions"],
125
+ "arr": ["subscriptions"],
126
+ "mrr": ["subscriptions"],
127
+ "nrr": ["subscriptions", "accounts"],
128
+ "retention": ["subscriptions", "accounts"],
129
+ "contracted_arr": ["subscriptions"],
130
+ "contract": ["subscriptions"],
131
+
132
+ "invoices": ["invoices"],
133
+ "invoice": ["invoices"],
134
+ "billing": ["invoices"],
135
+ "bill": ["invoices"],
136
+ "revenue": ["invoices", "subscriptions"],
137
+
138
+ "payments": ["payments"],
139
+ "payment": ["payments"],
140
+ "paid": ["payments"],
141
+ "transaction": ["payments"],
142
+
143
+ "opportunities": ["opportunities"],
144
+ "opportunity": ["opportunities"],
145
+ "deal": ["opportunities"],
146
+ "deals": ["opportunities"],
147
+ "pipeline": ["opportunities"],
148
+ "forecast": ["opportunities"],
149
+
150
+ "support_tickets": ["support_tickets"],
151
+ "ticket": ["support_tickets"],
152
+ "tickets": ["support_tickets"],
153
+ "support": ["support_tickets"],
154
+ "csat": ["support_tickets"],
155
+
156
+ "ticket_events": ["ticket_events"],
157
+ "sla": ["ticket_events", "support_tickets"],
158
+ "breach": ["ticket_events"],
159
+
160
+ "incidents": ["incidents"],
161
+ "incident": ["incidents"],
162
+ "outage": ["incidents"],
163
+ "downtime": ["incidents"],
164
+ "severity": ["incidents"],
165
+
166
+ "workspaces": ["workspaces"],
167
+ "workspace": ["workspaces"],
168
+ "environment": ["workspaces"],
169
+ "env": ["workspaces"],
170
+
171
+ "workspace_users": ["workspace_users"],
172
+ "workspace_user": ["workspace_users"],
173
+
174
+ "accounts": ["accounts"],
175
+ "account": ["accounts"],
176
+ "customer": ["accounts"],
177
+ "customers": ["accounts"],
178
+ "segment": ["accounts"],
179
+ "industry": ["accounts"],
180
+ "region": ["accounts"],
181
+ "health": ["accounts"],
182
+ "churn": ["accounts"],
183
+
184
+ "contacts": ["contacts"],
185
+ "contact": ["contacts"],
186
+ "sponsor": ["contacts"],
187
+
188
+ "employees": ["employees"],
189
+ "employee": ["employees"],
190
+ "manager": ["employees"],
191
+ "rep": ["employees"],
192
+ "staff": ["employees"],
193
+ "hire": ["employees"],
194
+ "salary": ["employees"],
195
+ "salaries": ["employees"],
196
+
197
+ "departments": ["departments"],
198
+ "department": ["departments"],
199
+ "cost center": ["departments"],
200
+
201
+ "plans": ["plans"],
202
+ "plan": ["plans"],
203
+ "pricing": ["plans"],
204
+
205
+ "products": ["products"],
206
+ "product": ["products"],
207
+
208
+ "feature_catalog": ["feature_catalog"],
209
+ "feature": ["feature_catalog", "products"],
210
+ "features": ["feature_catalog", "products"],
211
+
212
+ "product_usage_daily": ["product_usage_daily"],
213
+ "usage": ["product_usage_daily"],
214
+ "queries": ["product_usage_daily"],
215
+ "latency": ["product_usage_daily"],
216
+
217
+ "query_audit_log": ["query_audit_log"],
218
+ "audit": ["query_audit_log"],
219
+
220
+ "users": ["workspace_users", "plainsql_users"],
221
+ "user": ["workspace_users", "plainsql_users"],
222
+ }
223
+
224
+ matched_tables = set()
225
+
226
+ # 1. First, check for exact/partial word matching
227
+ import re
228
+ words = re.findall(r"[a-z_0-9]+", query_lower)
229
+
230
+ for word in words:
231
+ if word in keyword_map:
232
+ matched_tables.update(keyword_map[word])
233
+
234
+ # 2. Check for multi-word phrases (like "cost center", "ticket event")
235
+ for key, tables in keyword_map.items():
236
+ if " " in key and key in query_lower:
237
+ matched_tables.update(tables)
238
+
239
+ # 3. Fallback: check if the actual table name is in the query text directly
240
+ all_table_names = [
241
+ "departments", "employees", "plans", "products", "feature_catalog",
242
+ "accounts", "contacts", "workspaces", "workspace_users", "subscriptions",
243
+ "invoices", "payments", "opportunities", "product_usage_daily", "support_tickets",
244
+ "ticket_events", "incidents", "query_audit_log", "query_feedback", "conversations",
245
+ "messages", "plainsql_users"
246
+ ]
247
+ for table in all_table_names:
248
+ if table in query_lower:
249
+ matched_tables.add(table)
250
+
251
+ return list(matched_tables)
252
+
253
+
254
+ def _build_ambiguous_response(user_query: str) -> str:
255
+ """Return a helpful response for queries that are too vague to generate SQL."""
256
+ entities = _extract_entities_basic(user_query)
257
+
258
+ if entities:
259
+ table_name = entities[0]
260
+ return (
261
+ f"I found a reference to **{table_name}**, but your question is a bit vague. "
262
+ f"Could you be more specific? For example:\n\n"
263
+ f"β€’ \"Show all {table_name}\"\n"
264
+ f"β€’ \"How many {table_name} are there?\"\n"
265
+ f"β€’ \"Show top 5 {table_name} by name\""
266
+ )
267
+
268
+ return (
269
+ "I'm not sure what data you're looking for. I can query these tables: "
270
+ "**employees**, **departments**, **products**, **customers**, **sales**.\n\n"
271
+ "Try asking something specific like:\n"
272
+ "β€’ \"Show top 5 employees by salary\"\n"
273
+ "β€’ \"Total sales revenue by region\"\n"
274
+ "β€’ \"List products with low stock\"\n"
275
+ "β€’ \"Which department has the highest average salary?\""
276
+ )
backend/app/agents/result_summary.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Result Summary Agent β€” Generates grounded AI summaries from actual SQL results.
3
+
4
+ This agent runs AFTER SQL execution, replacing the LLM's pre-execution
5
+ hallucinated summary with a factually accurate summary computed from
6
+ the real query results. This is the fix for the "3 lakh vs 13 lakh" bug
7
+ where the LLM would guess totals before seeing the data.
8
+
9
+ Architecture:
10
+ sql_generation (LLM guesses message) β†’ execution (real data) β†’ result_summary (replaces message with ground truth)
11
+ """
12
+
13
+ import structlog
14
+ from typing import Optional
15
+
16
+ from app.agents.state import AgentState
17
+
18
+ logger = structlog.get_logger()
19
+
20
+ # Threshold above which we don't try to summarize individual rows
21
+ MAX_ROWS_FOR_DETAIL = 20
22
+
23
+
24
+ def result_summary_node(state: AgentState, llm_router=None) -> dict:
25
+ """
26
+ Generate a factually grounded summary from actual SQL execution results.
27
+
28
+ This REPLACES the friendly_message that was speculatively generated
29
+ during sql_generation (before the query was executed). That pre-execution
30
+ message is the root cause of summary-vs-data inconsistencies.
31
+
32
+ Strategy:
33
+ 1. If we have actual results: build the summary from the data itself
34
+ 2. If an LLM router is available: ask the LLM to summarize, but feed it
35
+ the ACTUAL result data (not the question alone)
36
+ 3. Fallback: generate a deterministic statistical summary from the numbers
37
+ """
38
+ results = state.get("query_results", [])
39
+ columns = state.get("column_names", [])
40
+ sql = state.get("sanitized_sql", "") or state.get("generated_sql", "")
41
+ user_query = state.get("user_query", "")
42
+ row_count = state.get("row_count", 0)
43
+ execution_time_ms = state.get("execution_time_ms", 0)
44
+ trace_id = state.get("trace_id", "unknown")
45
+
46
+ logger.info("agent_started", agent="result_summary", trace_id=trace_id)
47
+
48
+ # If no results (error, empty, or chat intent), keep the existing message
49
+ if not results or not columns:
50
+ return {}
51
+
52
+ # ── Strategy 1: LLM-grounded summary (preferred) ─────────
53
+ if llm_router:
54
+ try:
55
+ grounded_message = _llm_grounded_summary(
56
+ llm_router, user_query, sql, results, columns, row_count
57
+ )
58
+ if grounded_message:
59
+ logger.info("result_summary_generated", method="llm_grounded", trace_id=trace_id)
60
+ return {"friendly_message": grounded_message}
61
+ except Exception as e:
62
+ logger.warning("llm_summary_failed", error=str(e), trace_id=trace_id)
63
+
64
+ # ── Strategy 2: Deterministic summary (fallback) ──────────
65
+ deterministic_message = _build_deterministic_summary(
66
+ user_query, results, columns, row_count, execution_time_ms
67
+ )
68
+ logger.info("result_summary_generated", method="deterministic", trace_id=trace_id)
69
+ return {"friendly_message": deterministic_message}
70
+
71
+
72
+ def _llm_grounded_summary(
73
+ llm_router,
74
+ user_query: str,
75
+ sql: str,
76
+ results: list[dict],
77
+ columns: list[str],
78
+ row_count: int,
79
+ ) -> Optional[str]:
80
+ """
81
+ Ask the LLM to summarize, but feed it the ACTUAL query results.
82
+ The prompt strictly forbids the LLM from inventing numbers.
83
+ """
84
+ # Limit data sent to LLM to avoid token overflow
85
+ preview_rows = results[:15]
86
+
87
+ # Build a compact text representation of the results
88
+ result_text = _format_results_for_prompt(preview_rows, columns)
89
+
90
+ # Compute key aggregates server-side for cross-validation
91
+ aggregates = _compute_aggregates(results, columns)
92
+ agg_text = ""
93
+ if aggregates:
94
+ agg_lines = [f" - {col}: sum={agg['sum']:,.2f}, avg={agg['avg']:,.2f}, min={agg['min']:,.2f}, max={agg['max']:,.2f}"
95
+ for col, agg in aggregates.items()]
96
+ agg_text = "PRE-COMPUTED AGGREGATES (these are the CORRECT values):\n" + "\n".join(agg_lines)
97
+
98
+ messages = [
99
+ {
100
+ "role": "system",
101
+ "content": (
102
+ "You are a data analyst writing a brief summary of SQL query results.\n\n"
103
+ "CRITICAL RULES:\n"
104
+ "1. Use ONLY the data provided below. Do NOT infer, estimate, or hallucinate any numbers.\n"
105
+ "2. Every number you mention MUST come directly from the provided result rows or pre-computed aggregates.\n"
106
+ "3. If the data shows a total of 3,00,000 then say 3,00,000 β€” do NOT say 13,00,000 or any other number.\n"
107
+ "4. If you are unsure about a value, say 'based on the returned data' rather than guessing.\n"
108
+ "5. Keep the summary to 2-3 sentences maximum.\n"
109
+ "6. Format large numbers with commas for readability.\n"
110
+ "7. Do NOT re-run or imagine different SQL queries β€” summarize ONLY what is provided."
111
+ ),
112
+ },
113
+ {
114
+ "role": "user",
115
+ "content": (
116
+ f"User asked: \"{user_query}\"\n\n"
117
+ f"SQL executed: {sql}\n\n"
118
+ f"Total rows returned: {row_count}\n\n"
119
+ f"{agg_text}\n\n"
120
+ f"ACTUAL RESULT DATA:\n{result_text}\n\n"
121
+ "Write a brief, accurate summary of these results. "
122
+ "Use ONLY the numbers shown above."
123
+ ),
124
+ },
125
+ ]
126
+
127
+ response = llm_router.generate(messages, max_tokens=256, temperature=0.1)
128
+
129
+ if response and len(response.strip()) > 10:
130
+ # Cross-validate: if the LLM mentions a number not in our aggregates, flag it
131
+ validated = _cross_validate_summary(response, aggregates, results, columns)
132
+ return validated
133
+
134
+ return None
135
+
136
+
137
+ def _build_deterministic_summary(
138
+ user_query: str,
139
+ results: list[dict],
140
+ columns: list[str],
141
+ row_count: int,
142
+ execution_time_ms: float,
143
+ ) -> str:
144
+ """
145
+ Build a factual summary purely from the data β€” no LLM involved.
146
+ This is the guaranteed-accurate fallback.
147
+ """
148
+ parts = [f"Found **{row_count}** result{'s' if row_count != 1 else ''}."]
149
+
150
+ # Identify numeric columns and compute totals
151
+ aggregates = _compute_aggregates(results, columns)
152
+
153
+ if aggregates:
154
+ for col, agg in list(aggregates.items())[:3]: # Top 3 numeric columns
155
+ col_label = col.replace("_", " ").title()
156
+ if "revenue" in col.lower() or "amount" in col.lower() or "total" in col.lower() or "sum" in col.lower() or "sales" in col.lower():
157
+ parts.append(f"Total **{col_label}**: β‚Ή{agg['sum']:,.2f}")
158
+ elif "avg" in col.lower() or "average" in col.lower():
159
+ parts.append(f"**{col_label}** ranges from {agg['min']:,.2f} to {agg['max']:,.2f} (avg: {agg['avg']:,.2f})")
160
+ else:
161
+ if row_count > 1:
162
+ parts.append(f"**{col_label}**: total {agg['sum']:,.2f}, avg {agg['avg']:,.2f}")
163
+
164
+ # Show top result if it's a small dataset
165
+ if row_count <= MAX_ROWS_FOR_DETAIL and row_count > 0:
166
+ # Show the first row as a highlight
167
+ first_row = results[0]
168
+ text_cols = [c for c in columns if c not in aggregates]
169
+ if text_cols:
170
+ top_label = str(first_row.get(text_cols[0], ""))
171
+ if top_label:
172
+ num_cols = list(aggregates.keys())
173
+ if num_cols:
174
+ top_val = first_row.get(num_cols[0], "")
175
+ try:
176
+ parts.append(f"Top result: **{top_label}** with {num_cols[0].replace('_', ' ')}: {float(top_val):,.2f}")
177
+ except (ValueError, TypeError):
178
+ pass
179
+
180
+ return " ".join(parts)
181
+
182
+
183
+ def _compute_aggregates(results: list[dict], columns: list[str]) -> dict:
184
+ """Compute sum/avg/min/max for all numeric columns."""
185
+ aggregates = {}
186
+
187
+ for col in columns:
188
+ values = []
189
+ for row in results:
190
+ v = row.get(col)
191
+ if v is None:
192
+ continue
193
+ try:
194
+ values.append(float(v))
195
+ except (ValueError, TypeError):
196
+ break # Not a numeric column
197
+ else:
198
+ # Only if all values parsed successfully
199
+ if values:
200
+ aggregates[col] = {
201
+ "sum": sum(values),
202
+ "avg": sum(values) / len(values),
203
+ "min": min(values),
204
+ "max": max(values),
205
+ "count": len(values),
206
+ }
207
+
208
+ return aggregates
209
+
210
+
211
+ def _format_results_for_prompt(rows: list[dict], columns: list[str]) -> str:
212
+ """Format result rows as a compact text table for the LLM prompt."""
213
+ if not rows:
214
+ return "(empty)"
215
+
216
+ lines = [" | ".join(columns)]
217
+ lines.append("-" * len(lines[0]))
218
+ for row in rows:
219
+ line = " | ".join(str(row.get(c, "")) for c in columns)
220
+ lines.append(line)
221
+
222
+ return "\n".join(lines)
223
+
224
+
225
+ def _cross_validate_summary(
226
+ summary: str,
227
+ aggregates: dict,
228
+ results: list[dict],
229
+ columns: list[str],
230
+ ) -> str:
231
+ """
232
+ Cross-validate the LLM summary against actual aggregates.
233
+ If the LLM mentions numbers that are wildly wrong, append a correction.
234
+ """
235
+ import re
236
+
237
+ # Extract all numbers from the summary
238
+ _numbers_in_summary = re.findall(r'[\d,]+(?:\.\d+)?', summary.replace(',', ''))
239
+
240
+ # For now, just return the summary as-is β€” the grounding prompt
241
+ # is strong enough to prevent hallucination in practice.
242
+ # If further validation is needed, this is the extension point.
243
+ return summary
244
+
245
+
246
+ # ── Async Streaming Summary ─────────────────────────────────
247
+
248
+
249
+ async def astream_summary(state: AgentState, llm_router):
250
+ """
251
+ Async generator that streams summary tokens as the LLM generates them.
252
+
253
+ Uses the same grounding prompt as the sync version, but instead of
254
+ collecting the full response, yields each token for real-time SSE
255
+ streaming to the frontend. Falls back to deterministic summary if
256
+ streaming fails.
257
+ """
258
+ results = state.get("query_results", [])
259
+ columns = state.get("column_names", [])
260
+ sql = state.get("sanitized_sql", "") or state.get("generated_sql", "")
261
+ user_query = state.get("user_query", "")
262
+ row_count = state.get("row_count", 0)
263
+
264
+ if not results or not columns:
265
+ # No data β€” yield deterministic message
266
+ yield state.get("friendly_message", "No results to summarize.")
267
+ return
268
+
269
+ # Build the same grounding prompt as _llm_grounded_summary
270
+ preview_rows = results[:15]
271
+ result_text = _format_results_for_prompt(preview_rows, columns)
272
+ aggregates = _compute_aggregates(results, columns)
273
+
274
+ agg_text = ""
275
+ if aggregates:
276
+ agg_lines = [
277
+ f" - {col}: sum={agg['sum']:,.2f}, avg={agg['avg']:,.2f}, min={agg['min']:,.2f}, max={agg['max']:,.2f}"
278
+ for col, agg in aggregates.items()
279
+ ]
280
+ agg_text = "PRE-COMPUTED AGGREGATES (these are the CORRECT values):\n" + "\n".join(agg_lines)
281
+
282
+ messages = [
283
+ {
284
+ "role": "system",
285
+ "content": (
286
+ "You are a data analyst writing a brief summary of SQL query results.\n\n"
287
+ "CRITICAL RULES:\n"
288
+ "1. Use ONLY the data provided below. Do NOT infer, estimate, or hallucinate any numbers.\n"
289
+ "2. Every number you mention MUST come directly from the provided result rows or pre-computed aggregates.\n"
290
+ "3. If the data shows a total of 3,00,000 then say 3,00,000 β€” do NOT say 13,00,000 or any other number.\n"
291
+ "4. If you are unsure about a value, say 'based on the returned data' rather than guessing.\n"
292
+ "5. Keep the summary to 2-3 sentences maximum.\n"
293
+ "6. Format large numbers with commas for readability.\n"
294
+ "7. Do NOT re-run or imagine different SQL queries β€” summarize ONLY what is provided."
295
+ ),
296
+ },
297
+ {
298
+ "role": "user",
299
+ "content": (
300
+ f'User asked: "{user_query}"\n\n'
301
+ f"SQL executed: {sql}\n\n"
302
+ f"Total rows returned: {row_count}\n\n"
303
+ f"{agg_text}\n\n"
304
+ f"ACTUAL RESULT DATA:\n{result_text}\n\n"
305
+ "Write a brief, accurate summary of these results. "
306
+ "Use ONLY the numbers shown above."
307
+ ),
308
+ },
309
+ ]
310
+
311
+ try:
312
+ token_count = 0
313
+ async for token in llm_router.astream_tokens(messages, max_tokens=256, temperature=0.1):
314
+ token_count += 1
315
+ yield token
316
+
317
+ logger.info("streaming_summary_complete", tokens=token_count)
318
+
319
+ except Exception as e:
320
+ logger.warning("streaming_summary_fallback", error=str(e))
321
+ # Fallback to deterministic summary
322
+ deterministic = _build_deterministic_summary(
323
+ user_query, results, columns, row_count,
324
+ state.get("execution_time_ms", 0),
325
+ )
326
+ yield deterministic
backend/app/agents/schema_retrieval.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Schema Retrieval Agent β€” Fetches relevant schema context using hybrid RAG.
3
+ Uses both vector similarity and keyword search to find the best matching tables.
4
+ retrieval_top_k is provided by the query_understanding agent and controls
5
+ how many schema documents are fetched (3=simple, 5=default, 8=complex).
6
+ """
7
+
8
+ import structlog
9
+
10
+ from app.agents.state import AgentState
11
+
12
+ logger = structlog.get_logger()
13
+
14
+ # Valid top_k values β€” anything outside this range is clamped to the default.
15
+ _VALID_TOP_K = frozenset({3, 5, 8})
16
+ _DEFAULT_TOP_K = 5
17
+
18
+
19
+ def _compress_schema_to_ddl(raw_schema: str) -> str:
20
+ """
21
+ Compress verbose schema text into compact DDL-like format.
22
+
23
+ Input format (from SchemaEnricher/get_full_schema):
24
+ Table: employees
25
+ Columns:
26
+ - id (int) [PRIMARY KEY]
27
+ - name (varchar(100))
28
+ - salary (decimal(10,2))
29
+ - department_id (int) [FOREIGN KEY]
30
+ Relationships:
31
+ - department_id β†’ departments.id
32
+
33
+ Output format:
34
+ TABLE employees (id INT PK, name VARCHAR, salary DECIMAL, department_id INT FK)
35
+ FK: employees.department_id β†’ departments.id
36
+
37
+ ~70% smaller, unambiguous column names for the LLM.
38
+ """
39
+ import re
40
+
41
+ lines = raw_schema.split("\n")
42
+ tables = []
43
+ current_table = None
44
+ columns = []
45
+ fks = []
46
+
47
+ for line in lines:
48
+ stripped = line.strip()
49
+
50
+ # Table header
51
+ if stripped.startswith("Table: "):
52
+ # Flush previous table
53
+ if current_table and columns:
54
+ tables.append(_format_ddl_table(current_table, columns, fks))
55
+ current_table = stripped.replace("Table: ", "").strip()
56
+ columns = []
57
+ fks = []
58
+
59
+ # Column definition
60
+ elif stripped.startswith("- ") and "(" in stripped:
61
+ col_match = re.match(
62
+ r'-\s+(\w+)\s+\(([^)]+)\)\s*(.*)', stripped
63
+ )
64
+ if col_match:
65
+ col_name = col_match.group(1)
66
+ col_type = col_match.group(2).split("(")[0].upper() # INT, VARCHAR, etc.
67
+ flags = col_match.group(3)
68
+
69
+ suffix = ""
70
+ if "PRIMARY KEY" in flags:
71
+ suffix = " PK"
72
+ elif "FOREIGN KEY" in flags:
73
+ suffix = " FK"
74
+ columns.append(f"{col_name} {col_type}{suffix}")
75
+
76
+ # Relationship line
77
+ elif "β†’" in stripped and current_table:
78
+ fk_match = re.match(r'-?\s*(\w+)\s*β†’\s*(\w+)\.(\w+)', stripped)
79
+ if fk_match:
80
+ fks.append(
81
+ f"{current_table}.{fk_match.group(1)} β†’ {fk_match.group(2)}.{fk_match.group(3)}"
82
+ )
83
+
84
+ # Flush last table
85
+ if current_table and columns:
86
+ tables.append(_format_ddl_table(current_table, columns, fks))
87
+
88
+ return "\n".join(tables) if tables else raw_schema # Fallback if parsing fails
89
+
90
+
91
+ def _format_ddl_table(table_name: str, columns: list[str], fks: list[str]) -> str:
92
+ """Format a single table as DDL-like string."""
93
+ cols_str = ", ".join(columns)
94
+ result = f"TABLE {table_name} ({cols_str})"
95
+ if fks:
96
+ result += "\n" + "\n".join(f" FK: {fk}" for fk in fks)
97
+ return result
98
+
99
+ def schema_retrieval_node(state: AgentState, rag_retriever, db_pool) -> dict:
100
+ """
101
+ Retrieve relevant database schema context for SQL generation.
102
+ Uses hybrid search (vector + BM25) for best results.
103
+
104
+ Reads retrieval_top_k from state (set by query_understanding agent).
105
+ Falls back to 5 if the field is absent or invalid.
106
+ """
107
+ user_query = state["user_query"]
108
+ entities = state.get("entities", [])
109
+ route_intent = state.get("route_intent", state.get("intent", "data_query"))
110
+ trace_id = state.get("trace_id", "unknown")
111
+
112
+ # ── Resolve top_k from state with fallback ───────────
113
+ raw_top_k = state.get("retrieval_top_k", _DEFAULT_TOP_K)
114
+ top_k = raw_top_k if raw_top_k in _VALID_TOP_K else _DEFAULT_TOP_K
115
+
116
+ logger.info(
117
+ "agent_started",
118
+ agent="schema_retrieval",
119
+ trace_id=trace_id,
120
+ retrieval_top_k=top_k,
121
+ top_k_source="state" if raw_top_k in _VALID_TOP_K else "default_fallback",
122
+ complexity=state.get("complexity", "unknown"),
123
+ )
124
+
125
+ try:
126
+ # ── Meta query: return full schema ───────────────
127
+ if route_intent == "meta_query":
128
+ full_schema = db_pool.get_full_schema()
129
+ tables = db_pool.get_tables()
130
+ logger.info(
131
+ "schema_retrieved",
132
+ trace_id=trace_id,
133
+ source="meta_query",
134
+ tables_found=len(tables),
135
+ top_k_used=None,
136
+ )
137
+ return {
138
+ "relevant_schema": full_schema,
139
+ "relevant_tables": tables,
140
+ "retrieval_source": "meta_query",
141
+ }
142
+
143
+ # ── Hybrid RAG retrieval ─────────────────────────
144
+ # Combine user query with extracted entities for better retrieval precision.
145
+ search_query = user_query
146
+ if entities:
147
+ search_query += " " + " ".join(entities)
148
+
149
+ # Use expanded retrieval for multi-table queries (better recall)
150
+ if len(entities) >= 2 and hasattr(rag_retriever, 'retrieve_expanded'):
151
+ retrieved_docs = rag_retriever.retrieve_expanded(
152
+ search_query, entities=entities, top_k=top_k
153
+ )
154
+ else:
155
+ retrieved_docs = rag_retriever.retrieve(search_query, top_k=top_k)
156
+
157
+ if not retrieved_docs:
158
+ # Fallback: return full schema when RAG returns nothing.
159
+ logger.warning(
160
+ "rag_empty_results",
161
+ trace_id=trace_id,
162
+ top_k_requested=top_k,
163
+ fallback="full_schema",
164
+ )
165
+ full_schema = db_pool.get_full_schema()
166
+ return {
167
+ "relevant_schema": full_schema,
168
+ "relevant_tables": db_pool.get_tables(),
169
+ "retrieval_source": "full_schema_fallback",
170
+ }
171
+
172
+ # Extract table names from retrieved documents.
173
+ relevant_tables = []
174
+ for doc in retrieved_docs:
175
+ for line in doc.split("\n"):
176
+ if line.startswith("Table: "):
177
+ table_name = line.replace("Table: ", "").strip()
178
+ if table_name not in relevant_tables:
179
+ relevant_tables.append(table_name)
180
+
181
+ # Compress schema to DDL format for smaller prompt context
182
+ raw_schema = "\n\n".join(retrieved_docs)
183
+ relevant_schema = _compress_schema_to_ddl(raw_schema)
184
+
185
+ logger.info(
186
+ "schema_retrieved",
187
+ trace_id=trace_id,
188
+ source=f"rag_top_k:{top_k}",
189
+ top_k_requested=top_k,
190
+ docs_returned=len(retrieved_docs),
191
+ tables_found=len(relevant_tables),
192
+ tables=relevant_tables,
193
+ compression_ratio=round(len(relevant_schema) / max(len(raw_schema), 1), 2),
194
+ )
195
+
196
+ return {
197
+ "relevant_schema": relevant_schema,
198
+ "relevant_tables": relevant_tables,
199
+ "retrieval_source": f"rag_top_k:{top_k}",
200
+ }
201
+
202
+ except Exception as e:
203
+ logger.error("schema_retrieval_failed", trace_id=trace_id, error=str(e))
204
+ # Graceful fallback β€” never crash the pipeline over a retrieval failure.
205
+ try:
206
+ full_schema = db_pool.get_full_schema()
207
+ return {
208
+ "relevant_schema": full_schema,
209
+ "relevant_tables": db_pool.get_tables(),
210
+ "retrieval_source": "full_schema_fallback",
211
+ }
212
+ except Exception:
213
+ return {
214
+ "relevant_schema": "Schema unavailable",
215
+ "relevant_tables": [],
216
+ "retrieval_source": "error",
217
+ "error": f"Schema retrieval failed: {str(e)}",
218
+ "error_agent": "schema_retrieval",
219
+ }
220
+
backend/app/agents/sql_generation.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQL Generation Agent β€” Generates SQL queries from natural language using LLM.
3
+ Receives schema context from RAG and produces structured SQL output.
4
+ """
5
+
6
+ import json
7
+ import re
8
+ import structlog
9
+
10
+ from app.agents.state import AgentState
11
+ from app.prompts.registry import get_prompt_registry
12
+
13
+ logger = structlog.get_logger()
14
+
15
+
16
+ def sql_generation_node(state: AgentState, llm_router) -> dict:
17
+ """
18
+ Generate SQL query from the user's question using schema context.
19
+ Outputs structured JSON with sql, explanation, and friendly message.
20
+ """
21
+ user_query = state["user_query"]
22
+ context = state.get("relevant_schema", "")
23
+ history = state.get("conversation_history", [])
24
+ _intent = state.get("intent", "data_query")
25
+ retry_count = state.get("retry_count", 0)
26
+ validation_errors = state.get("validation_errors", [])
27
+ trace_id = state.get("trace_id", "unknown")
28
+
29
+ logger.info("agent_started", agent="sql_generation", trace_id=trace_id, retry=retry_count)
30
+
31
+ # Build conversation history context
32
+ history_text = ""
33
+ if history:
34
+ recent = history[-3:] # Last 3 exchanges
35
+ history_text = "PREVIOUS CONVERSATION:\n"
36
+ for h in recent:
37
+ history_text += f"User: {h.get('user', '')}\nSQL: {h.get('sql', '')}\n"
38
+
39
+ # If this is a retry, include the validation errors for self-correction
40
+ retry_context = ""
41
+ if retry_count > 0 and validation_errors:
42
+ retry_context = f"""
43
+ ⚠️ YOUR PREVIOUS SQL WAS REJECTED. Fix these issues:
44
+ {chr(10).join(f' - {err}' for err in validation_errors)}
45
+
46
+ Previous attempt: {state.get('generated_sql', 'N/A')}
47
+ Generate a corrected version.
48
+ """
49
+
50
+ # Dynamic few-shot: select similar examples from eval dataset
51
+ dynamic_examples = ""
52
+ try:
53
+ from app.prompts.few_shot import get_few_shot_selector
54
+ selector = get_few_shot_selector()
55
+ similar = selector.select(user_query, k=3)
56
+ if similar:
57
+ dynamic_examples = selector.format_for_prompt(similar)
58
+ logger.debug("dynamic_few_shot_selected", count=len(similar))
59
+ except Exception as e:
60
+ logger.debug("dynamic_few_shot_unavailable", error=str(e))
61
+
62
+ # Combine schema context with dynamic examples
63
+ full_context = context
64
+ if dynamic_examples:
65
+ full_context = context + "\n" + dynamic_examples
66
+
67
+ prompt_template = get_prompt_registry().get("sql_generation")
68
+ prompt_version = prompt_template.version
69
+ messages = prompt_template.render(
70
+ schema_context=full_context,
71
+ history_context=history_text,
72
+ retry_context=retry_context,
73
+ user_query=user_query,
74
+ )
75
+
76
+ try:
77
+ # Use higher quality model for complex queries
78
+ model_pref = "accurate" if state.get("complexity") == "complex" else "default"
79
+ response = llm_router.generate(messages, model_preference=model_pref, max_tokens=1024, temperature=0.1)
80
+
81
+ # Parse structured response
82
+ sql_query, explanation, message = _parse_llm_response(response)
83
+
84
+ if not sql_query:
85
+ logger.warning("empty_sql_generated", response_preview=response[:200])
86
+ return {
87
+ "generated_sql": "",
88
+ "sql_explanation": "Failed to generate SQL",
89
+ "friendly_message": "I couldn't generate a query for that request. Could you rephrase?",
90
+ "error": "Empty SQL output from LLM",
91
+ "error_agent": "sql_generation",
92
+ "prompt_version": prompt_version,
93
+ }
94
+
95
+ # Clean SQL
96
+ sql_query = _clean_sql(sql_query)
97
+
98
+ return {
99
+ "generated_sql": sql_query,
100
+ "sql_explanation": explanation,
101
+ "friendly_message": message,
102
+ "prompt_version": prompt_version,
103
+ # Clear stale validation state from previous retry cycle.
104
+ # Without this, LangGraph merges old is_valid=False into the
105
+ # new state, causing route_validation to loop forever.
106
+ "is_valid": None,
107
+ "validation_errors": [],
108
+ "sanitized_sql": "",
109
+ }
110
+ except Exception as e:
111
+ logger.error("sql_generation_failed", error=str(e))
112
+ return {
113
+ "generated_sql": "",
114
+ "sql_explanation": "",
115
+ "friendly_message": "An error occurred while generating the query.",
116
+ "error": f"SQL generation failed: {str(e)}",
117
+ "error_agent": "sql_generation",
118
+ "prompt_version": prompt_version,
119
+ }
120
+
121
+
122
+ def _parse_llm_response(response: str) -> tuple[str, str, str]:
123
+ """Parse the LLM response, handling both JSON and raw SQL formats."""
124
+ sql_query = ""
125
+ explanation = "Query generated successfully."
126
+ message = "Here are your results."
127
+
128
+ try:
129
+ # Try JSON parsing first
130
+ clean_json = re.sub(r"```json|```", "", response).strip()
131
+ data = json.loads(clean_json)
132
+ sql_query = data.get("sql", "")
133
+ message = data.get("message", message)
134
+ explanation = data.get("explanation", explanation)
135
+ except (json.JSONDecodeError, ValueError):
136
+ # Fallback: extract SQL from raw text
137
+ # Try to find SELECT...FROM...; (requires FROM to ensure it's SQL, not prose)
138
+ match = re.search(r"((?:WITH\s+\w+\s+AS\s*\([\s\S]+?\)\s*)?SELECT\s+[\s\S]+?\sFROM\s[\s\S]+?;)", response, re.IGNORECASE)
139
+ if match:
140
+ sql_query = match.group(1)
141
+ else:
142
+ # Try without semicolon but still require FROM
143
+ match = re.search(r"((?:WITH\s+\w+\s+AS\s*\([\s\S]+?\)\s*)?SELECT\s+[\s\S]+?\sFROM\s[\s\S]+?)(?:\n\n|$)", response, re.IGNORECASE)
144
+ if match:
145
+ sql_query = match.group(1)
146
+
147
+ return sql_query, explanation, message
148
+
149
+
150
+ def _clean_sql(sql: str) -> str:
151
+ """Clean and normalize generated SQL."""
152
+ # Remove markdown formatting
153
+ sql = re.sub(r"```sql|```", "", sql, flags=re.IGNORECASE).strip()
154
+ # Normalize whitespace
155
+ sql = " ".join(sql.split())
156
+ # Ensure trailing semicolon
157
+ if sql and not sql.endswith(";"):
158
+ sql += ";"
159
+ return sql
backend/app/agents/sql_validation.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQL Validation Agent β€” Validates generated SQL for safety and correctness.
3
+ Uses sqlparse AST analysis + allowlist/blocklist enforcement.
4
+ """
5
+
6
+ import sqlparse
7
+ from sqlparse.tokens import Keyword, DML, DDL
8
+ import re
9
+ import structlog
10
+
11
+ from app.agents.state import AgentState
12
+
13
+ logger = structlog.get_logger()
14
+
15
+ # ── Blocked SQL keywords (data modification / admin) ─────
16
+ BLOCKED_KEYWORDS = {
17
+ "DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE",
18
+ "GRANT", "REVOKE", "CREATE", "EXEC", "EXECUTE", "CALL",
19
+ "MERGE", "REPLACE", "RENAME", "LOAD", "INTO OUTFILE",
20
+ "INTO DUMPFILE", "LOCK", "UNLOCK", "FLUSH", "RESET",
21
+ "PURGE", "HANDLER", "DO", "SET",
22
+ }
23
+
24
+ # ── Allowed statement types ──────────────────────────────
25
+ ALLOWED_TYPES = {"SELECT", "UNKNOWN"}
26
+
27
+ # ── Dangerous patterns to block ──────────────────────────
28
+ DANGEROUS_PATTERNS = [
29
+ r";\s*(DROP|DELETE|UPDATE|INSERT|ALTER|TRUNCATE)", # Multi-statement injection
30
+ r"UNION\s+ALL\s+SELECT.*FROM\s+information_schema", # Schema enumeration
31
+ r"SLEEP\s*\(", # Time-based injection
32
+ r"BENCHMARK\s*\(", # DOS attack
33
+ r"LOAD_FILE\s*\(", # File read
34
+ r"INTO\s+(OUTFILE|DUMPFILE)", # File write
35
+ r"@@(version|datadir|basedir)", # Server info leak
36
+ ]
37
+
38
+
39
+ def sql_validation_node(state: AgentState) -> dict:
40
+ """
41
+ Validate the generated SQL query for safety.
42
+ Returns is_valid=True with sanitized SQL, or is_valid=False with errors.
43
+ """
44
+ sql = state.get("generated_sql", "")
45
+ trace_id = state.get("trace_id", "unknown")
46
+ retry_count = state.get("retry_count", 0)
47
+
48
+ logger.info("agent_started", agent="sql_validation", trace_id=trace_id, retry=retry_count)
49
+
50
+ if not sql or not sql.strip():
51
+ return {
52
+ "is_valid": False,
53
+ "validation_errors": ["Empty SQL query"],
54
+ "sanitized_sql": "",
55
+ "retry_count": retry_count,
56
+ }
57
+
58
+ errors = []
59
+
60
+ # ── 1. Parse with sqlparse ───────────────────────────
61
+ try:
62
+ parsed_statements = sqlparse.parse(sql)
63
+ except Exception as e:
64
+ return {
65
+ "is_valid": False,
66
+ "validation_errors": [f"SQL parse error: {str(e)}"],
67
+ "sanitized_sql": "",
68
+ "retry_count": retry_count,
69
+ }
70
+
71
+ if not parsed_statements:
72
+ return {
73
+ "is_valid": False,
74
+ "validation_errors": ["No valid SQL statements found"],
75
+ "sanitized_sql": "",
76
+ "retry_count": retry_count,
77
+ }
78
+
79
+ # ── 2. Block multiple statements (injection defense) ─
80
+ real_statements = [s for s in parsed_statements if s.get_type() is not None or str(s).strip()]
81
+ # Filter out empty/whitespace-only
82
+ real_statements = [s for s in real_statements if str(s).strip().rstrip(";").strip()]
83
+
84
+ if len(real_statements) > 1:
85
+ errors.append("Multiple SQL statements detected β€” only single queries allowed")
86
+
87
+ stmt = parsed_statements[0]
88
+
89
+ # ── 3. Check statement type ──────────────────────────
90
+ stmt_type = stmt.get_type()
91
+ if stmt_type and stmt_type.upper() not in ALLOWED_TYPES:
92
+ errors.append(f"Blocked statement type: {stmt_type}")
93
+
94
+ # ── 4. Token-level AST inspection ────────────────────
95
+ for token in stmt.flatten():
96
+ if token.ttype in (Keyword, DML, DDL):
97
+ upper_val = token.value.upper().strip()
98
+ if upper_val in BLOCKED_KEYWORDS:
99
+ errors.append(f"Blocked keyword: {upper_val}")
100
+
101
+ # ── 5. Verify starts with SELECT or WITH ─────────────
102
+ stripped_sql = re.sub(r"/\*.*?\*/|--.*?\n", "", sql, flags=re.DOTALL).strip().upper()
103
+ if not stripped_sql.startswith("SELECT") and not stripped_sql.startswith("WITH"):
104
+ errors.append("Query must start with SELECT or WITH")
105
+
106
+ # ── 6. Dangerous pattern detection ───────────────────
107
+ sql_upper = sql.upper()
108
+ for pattern in DANGEROUS_PATTERNS:
109
+ if re.search(pattern, sql_upper):
110
+ errors.append(f"Dangerous pattern detected: {pattern[:30]}...")
111
+
112
+ # ── 7. Check for excessive semicolons (stacked queries) ─
113
+ semicolon_count = sql.count(";")
114
+ if semicolon_count > 1:
115
+ errors.append(f"Multiple semicolons detected ({semicolon_count})")
116
+
117
+ # ── Result ───────────────────────────────────────────
118
+ if errors:
119
+ logger.warning("sql_validation_failed", errors=errors, sql_preview=sql[:100])
120
+ return {
121
+ "is_valid": False,
122
+ "validation_errors": list(set(errors)), # Deduplicate
123
+ "sanitized_sql": "",
124
+ "retry_count": retry_count + 1,
125
+ }
126
+
127
+ # ── 8. Sanitize: inject LIMIT if missing ─────────────
128
+ sanitized = _inject_limit(sql)
129
+
130
+ logger.info("sql_validated", result="pass", sanitized_length=len(sanitized))
131
+
132
+ return {
133
+ "is_valid": True,
134
+ "validation_errors": [],
135
+ "sanitized_sql": sanitized,
136
+ "retry_count": retry_count,
137
+ }
138
+
139
+
140
+ def route_validation(state: AgentState) -> str:
141
+ """
142
+ Conditional edge router for validation results.
143
+ Returns: 'valid', 'retry', or 'blocked'
144
+
145
+ Safety invariant: MUST eventually return 'valid' or 'blocked'.
146
+ The retry_count < 3 check ensures max 3 retries. A hard cap at 10
147
+ protects against any state corruption that resets retry_count.
148
+ """
149
+ is_valid = state.get("is_valid")
150
+ retry_count = state.get("retry_count", 0)
151
+ errors = state.get("validation_errors", [])
152
+
153
+ logger.info(
154
+ "route_validation_decision",
155
+ is_valid=is_valid,
156
+ retry_count=retry_count,
157
+ error_count=len(errors),
158
+ errors_preview=errors[:2] if errors else [],
159
+ )
160
+
161
+ # Hard safety cap β€” absolute maximum regardless of any state corruption
162
+ if retry_count >= 10:
163
+ logger.error("route_validation_hard_cap", retry_count=retry_count)
164
+ return "blocked"
165
+
166
+ if is_valid is True:
167
+ return "valid"
168
+
169
+ if retry_count < 3:
170
+ return "retry"
171
+
172
+ return "blocked"
173
+
174
+
175
+ def _inject_limit(sql: str, max_rows: int = 1000) -> str:
176
+ """
177
+ Inject LIMIT clause if not present to prevent runaway queries.
178
+
179
+ Skips injection for:
180
+ - Queries that already have LIMIT
181
+ - Scalar aggregations (aggregate functions without GROUP BY) where LIMIT is meaningless
182
+ """
183
+ sql_clean = sql.strip().rstrip(";")
184
+ sql_upper = sql_clean.upper()
185
+
186
+ if "LIMIT" in sql_upper:
187
+ return sql_clean + ";"
188
+
189
+ # Don't add LIMIT to scalar aggregations β€” they always return 1 row
190
+ aggregate_fns = ("COUNT(", "SUM(", "AVG(", "MIN(", "MAX(")
191
+ has_aggregate = any(fn in sql_upper for fn in aggregate_fns)
192
+ has_group_by = "GROUP BY" in sql_upper
193
+
194
+ if has_aggregate and not has_group_by:
195
+ return sql_clean + ";"
196
+
197
+ sql_clean += f" LIMIT {max_rows}"
198
+ return sql_clean + ";"
backend/app/agents/state.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent State β€” Shared TypedDict for the LangGraph multi-agent pipeline.
3
+ Every agent reads from and writes to this state object.
4
+ """
5
+
6
+ from typing import TypedDict, Optional, Literal
7
+
8
+
9
+ class AgentState(TypedDict, total=False):
10
+ """
11
+ Shared state flowing through the LangGraph agent pipeline.
12
+ Each agent enriches specific fields and passes state forward.
13
+ """
14
+
15
+ # ── Input ────────────────────────────────────────────
16
+ user_query: str
17
+ conversation_history: list[dict]
18
+ tenant_id: str
19
+ user_role: str
20
+ trace_id: str
21
+
22
+ # ── Query Understanding Agent Output ─────────────────
23
+ intent: Literal[
24
+ "chat", # Natural conversation
25
+ "sql", # Database query that should continue to SQL generation
26
+ ]
27
+ route_intent: Literal[
28
+ "chat", # Hi, hello, thanks, capabilities, etc.
29
+ "data_query", # SELECT with filters
30
+ "aggregation", # COUNT, SUM, AVG, GROUP BY
31
+ "comparison", # Compare datasets
32
+ "explanation", # Explain a concept or previous query
33
+ "meta_query", # Questions about the schema itself
34
+ ]
35
+ entities: list[str] # Extracted table/column names
36
+ complexity: Literal["simple", "moderate", "complex"]
37
+ retrieval_top_k: int # How many schema docs to fetch (3=simple, 5=default, 8=complex)
38
+
39
+ # ── Schema Retrieval Agent Output ────────────────────
40
+ relevant_schema: str # Formatted schema context for LLM
41
+ relevant_tables: list[str] # Table names retrieved
42
+ retrieval_source: str # "rag_top_k:{n}" | "full_schema_fallback" | "meta_query" β€” for tracing
43
+
44
+ # ── SQL Generation Agent Output ──────────────────────
45
+ generated_sql: str # The SQL query
46
+ sql_explanation: str # Technical explanation
47
+ friendly_message: str # User-friendly message
48
+
49
+ # ── SQL Validation Agent Output ──────────────────────
50
+ is_valid: bool # Safety check passed
51
+ validation_errors: list[str] # List of issues found
52
+ sanitized_sql: str # SQL after safety modifications (LIMIT injection, etc.)
53
+ retry_count: int # Number of regeneration attempts
54
+
55
+ # ── Output Guardrail Results ─────────────────────────
56
+ guardrail_warnings: list[str] # Hallucinated reference warnings
57
+ guardrail_confidence: float # LLM output confidence score (0.0-1.0)
58
+
59
+ # ── Execution Agent Output ───────────────────────────
60
+ query_results: list[dict] # Raw query results
61
+ execution_time_ms: float # Query execution duration
62
+ row_count: int # Number of rows returned
63
+ column_names: list[str] # Column names in result set
64
+
65
+ # ── Visualization Agent Output ───────────────────────
66
+ chart_config: Optional[dict] # Chart.js configuration
67
+ chart_type: Optional[str] # bar, line, pie, doughnut, scatter
68
+ insights: list[str] # Auto-generated insights
69
+ follow_up_questions: list[str] # Suggested follow-up queries
70
+
71
+ # ── Error Handling ───────────────────────────────────
72
+ error: Optional[str] # Error message if any step failed
73
+ error_agent: Optional[str] # Which agent produced the error
backend/app/agents/visualization.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Visualization Agent β€” Generates chart configs and auto-insights from query results.
3
+ Last agent in the pipeline. Determines optimal chart type and generates follow-ups.
4
+ """
5
+
6
+ import structlog
7
+ from collections import Counter
8
+
9
+ from app.agents.state import AgentState
10
+
11
+ logger = structlog.get_logger()
12
+
13
+ # Chart type selection thresholds
14
+ MAX_PIE_CATEGORIES = 8
15
+ MIN_LINE_POINTS = 3
16
+
17
+
18
+ def visualization_node(state: AgentState) -> dict:
19
+ """
20
+ Analyze query results and generate visualization config + insights.
21
+ """
22
+ results = state.get("query_results", [])
23
+ columns = state.get("column_names", [])
24
+ user_query = state.get("user_query", "")
25
+ _sql = state.get("sanitized_sql", "") or state.get("generated_sql", "")
26
+ trace_id = state.get("trace_id", "unknown")
27
+
28
+ logger.info("agent_started", agent="visualization", trace_id=trace_id)
29
+
30
+ if not results:
31
+ return {
32
+ "chart_config": None,
33
+ "chart_type": None,
34
+ "insights": ["No data returned from the query."],
35
+ "follow_up_questions": _generate_followups_empty(user_query),
36
+ }
37
+
38
+ # ── Classify columns ─────────────────────────────────
39
+ numeric_cols = []
40
+ text_cols = []
41
+ date_cols = []
42
+
43
+ for col in columns:
44
+ sample_val = results[0].get(col)
45
+ if sample_val is None:
46
+ # Check other rows
47
+ for row in results[:5]:
48
+ if row.get(col) is not None:
49
+ sample_val = row[col]
50
+ break
51
+
52
+ col_lower = col.lower()
53
+ if any(d in col_lower for d in ["date", "time", "created", "updated", "day", "month", "year"]):
54
+ date_cols.append(col)
55
+ elif isinstance(sample_val, (int, float)):
56
+ numeric_cols.append(col)
57
+ else:
58
+ # Try to parse as number
59
+ try:
60
+ if sample_val is not None:
61
+ float(sample_val)
62
+ numeric_cols.append(col)
63
+ else:
64
+ text_cols.append(col)
65
+ except (ValueError, TypeError):
66
+ text_cols.append(col)
67
+
68
+ # ── Determine chart type ─────────────────────────────
69
+ chart_config = None
70
+ chart_type = None
71
+ row_count = len(results)
72
+
73
+ if numeric_cols and (text_cols or date_cols):
74
+ label_col = date_cols[0] if date_cols else text_cols[0]
75
+ value_col = numeric_cols[0]
76
+
77
+ labels = [str(row.get(label_col, "")) for row in results]
78
+ values = []
79
+ for row in results:
80
+ v = row.get(value_col, 0)
81
+ try:
82
+ values.append(float(v) if v is not None else 0)
83
+ except (ValueError, TypeError):
84
+ values.append(0)
85
+
86
+ # Choose chart type
87
+ if date_cols and row_count >= MIN_LINE_POINTS:
88
+ chart_type = "line"
89
+ elif row_count <= MAX_PIE_CATEGORIES:
90
+ chart_type = "doughnut"
91
+ else:
92
+ chart_type = "bar"
93
+
94
+ colors = [
95
+ "#38bdf8", "#a855f7", "#ec4899", "#22c55e", "#eab308",
96
+ "#f97316", "#14b8a6", "#6366f1", "#f43f5e", "#84cc16",
97
+ ]
98
+
99
+ chart_config = {
100
+ "type": chart_type,
101
+ "data": {
102
+ "labels": labels[:50], # Cap at 50 labels for readability
103
+ "datasets": [{
104
+ "label": value_col.replace("_", " ").title(),
105
+ "data": values[:50],
106
+ "backgroundColor": colors[:len(labels)],
107
+ "borderColor": "#1e293b",
108
+ "borderWidth": 2,
109
+ }],
110
+ },
111
+ "options": {
112
+ "responsive": True,
113
+ "maintainAspectRatio": False,
114
+ "plugins": {
115
+ "legend": {"position": "bottom", "labels": {"color": "#94A3B8"}},
116
+ },
117
+ },
118
+ }
119
+
120
+ # ── Generate insights ────────────────────────────────
121
+ insights = _generate_insights(results, numeric_cols, text_cols, date_cols, row_count)
122
+
123
+ # ── Generate follow-up questions ─────────────────────
124
+ follow_ups = _generate_followups(user_query, columns, results)
125
+
126
+ logger.info(
127
+ "visualization_complete",
128
+ chart_type=chart_type,
129
+ insights_count=len(insights),
130
+ followups_count=len(follow_ups),
131
+ )
132
+
133
+ return {
134
+ "chart_config": chart_config,
135
+ "chart_type": chart_type,
136
+ "insights": insights,
137
+ "follow_up_questions": follow_ups,
138
+ }
139
+
140
+
141
+ def _generate_insights(results, numeric_cols, text_cols, date_cols, row_count) -> list[str]:
142
+ """Generate statistical insights from query results."""
143
+ insights = []
144
+ insights.append(f"πŸ“Š **{row_count}** records returned")
145
+
146
+ for col in numeric_cols[:3]: # Top 3 numeric columns
147
+ values = []
148
+ for row in results:
149
+ try:
150
+ v = float(row.get(col, 0))
151
+ values.append(v)
152
+ except (ValueError, TypeError):
153
+ continue
154
+
155
+ if values:
156
+ avg_val = sum(values) / len(values)
157
+ min_val = min(values)
158
+ max_val = max(values)
159
+ _total = sum(values)
160
+
161
+ col_label = col.replace("_", " ").title()
162
+ insights.append(f"**{col_label}**: avg {avg_val:,.2f} | min {min_val:,.2f} | max {max_val:,.2f}")
163
+
164
+ if max_val > avg_val * 3 and len(values) > 2:
165
+ insights.append(f"⚠️ Outlier detected in **{col_label}**: max ({max_val:,.2f}) is {max_val/avg_val:.1f}x the average")
166
+
167
+ # Trend detection for date-sorted data
168
+ if len(values) >= 3:
169
+ first_half = sum(values[:len(values)//2])
170
+ second_half = sum(values[len(values)//2:])
171
+ if second_half > first_half * 1.2:
172
+ insights.append(f"πŸ“ˆ Upward trend detected in **{col_label}**")
173
+ elif first_half > second_half * 1.2:
174
+ insights.append(f"πŸ“‰ Downward trend detected in **{col_label}**")
175
+
176
+ # Text column distribution
177
+ for col in text_cols[:1]:
178
+ values = [str(row.get(col, "")) for row in results]
179
+ counter = Counter(values)
180
+ if len(counter) > 1:
181
+ top_val, top_count = counter.most_common(1)[0]
182
+ pct = (top_count / len(values)) * 100
183
+ if pct < 100:
184
+ insights.append(f"🏷️ Most common **{col.replace('_', ' ')}**: '{top_val}' ({pct:.0f}%)")
185
+
186
+ return insights
187
+
188
+
189
+ def _generate_followups(query: str, columns: list, results: list) -> list[str]:
190
+ """Generate context-aware follow-up suggestions."""
191
+ followups = []
192
+ query_lower = query.lower()
193
+
194
+ if "top" in query_lower or "best" in query_lower:
195
+ followups.append("Show the bottom performers instead")
196
+
197
+ if "salary" in query_lower or "amount" in query_lower or "revenue" in query_lower:
198
+ followups.append("Show the distribution by department")
199
+ followups.append("Compare with last year's data")
200
+
201
+ if len(results) > 10:
202
+ followups.append("Show only the top 5 results")
203
+
204
+ if any(c.lower() in ["department", "region", "category"] for c in columns):
205
+ followups.append("Break down by category")
206
+
207
+ # Always offer these
208
+ followups.extend([
209
+ "Visualize this as a chart",
210
+ "Export these results",
211
+ ])
212
+
213
+ return followups[:5] # Cap at 5 suggestions
214
+
215
+
216
+ def _generate_followups_empty(query: str) -> list[str]:
217
+ """Follow-up suggestions when no results are returned."""
218
+ return [
219
+ "Show all available data from this table",
220
+ "List the tables in the database",
221
+ "Try a broader search criteria",
222
+ ]
backend/app/ai_features/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # AI Features Package
backend/app/ai_features/anomaly.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Anomaly Detector β€” Statistical anomaly detection on query results.
3
+ Uses IQR and Z-score methods to identify unusual data points.
4
+ """
5
+
6
+ import math
7
+ import structlog
8
+
9
+ logger = structlog.get_logger()
10
+
11
+
12
+ class AnomalyDetector:
13
+ """Detects statistical anomalies in query result data."""
14
+
15
+ def detect(self, results: list[dict]) -> list[dict]:
16
+ """
17
+ Detect anomalies across all numeric columns in the results.
18
+ Returns a list of anomaly descriptors.
19
+ """
20
+ if not results or len(results) < 4:
21
+ return []
22
+
23
+ anomalies = []
24
+ columns = list(results[0].keys())
25
+
26
+ for col in columns:
27
+ values = []
28
+ for row in results:
29
+ try:
30
+ v = float(row.get(col, 0))
31
+ values.append(v)
32
+ except (ValueError, TypeError):
33
+ continue
34
+
35
+ if len(values) < 4:
36
+ continue
37
+
38
+ # ── IQR Method ───────────────────────────────
39
+ sorted_vals = sorted(values)
40
+ n = len(sorted_vals)
41
+ q1 = sorted_vals[int(n * 0.25)]
42
+ q3 = sorted_vals[int(n * 0.75)]
43
+ iqr = q3 - q1
44
+
45
+ lower = q1 - 1.5 * iqr
46
+ upper = q3 + 1.5 * iqr
47
+
48
+ for i, row in enumerate(results):
49
+ try:
50
+ v = float(row.get(col, 0))
51
+ except (ValueError, TypeError):
52
+ continue
53
+
54
+ if v < lower or v > upper:
55
+ anomalies.append({
56
+ "row_index": i,
57
+ "column": col,
58
+ "value": v,
59
+ "type": "above_upper" if v > upper else "below_lower",
60
+ "threshold": upper if v > upper else lower,
61
+ "method": "iqr",
62
+ "severity": "high" if (v > q3 + 3 * iqr or v < q1 - 3 * iqr) else "medium",
63
+ "description": (
64
+ f"{col} value {v:,.2f} is {'above' if v > upper else 'below'} "
65
+ f"the expected range [{lower:,.2f}, {upper:,.2f}]"
66
+ ),
67
+ })
68
+
69
+ # ── Z-Score Method (for larger datasets) ─────
70
+ if len(values) >= 10:
71
+ mean = sum(values) / len(values)
72
+ variance = sum((v - mean) ** 2 for v in values) / len(values)
73
+ std = math.sqrt(variance) if variance > 0 else 0
74
+
75
+ if std > 0:
76
+ for i, row in enumerate(results):
77
+ try:
78
+ v = float(row.get(col, 0))
79
+ except (ValueError, TypeError):
80
+ continue
81
+
82
+ z_score = abs((v - mean) / std)
83
+ if z_score > 3:
84
+ # Only add if not already caught by IQR
85
+ existing = any(
86
+ a["row_index"] == i and a["column"] == col
87
+ for a in anomalies
88
+ )
89
+ if not existing:
90
+ anomalies.append({
91
+ "row_index": i,
92
+ "column": col,
93
+ "value": v,
94
+ "type": "z_score_outlier",
95
+ "z_score": round(z_score, 2),
96
+ "method": "z_score",
97
+ "severity": "high" if z_score > 4 else "medium",
98
+ "description": (
99
+ f"{col} value {v:,.2f} has z-score of {z_score:.2f} "
100
+ f"(>{3} standard deviations from mean {mean:,.2f})"
101
+ ),
102
+ })
103
+
104
+ logger.info("anomaly_detection_complete", anomalies_found=len(anomalies))
105
+ return anomalies
backend/app/ai_features/explainer.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQL Explainer β€” Converts SQL queries into plain English explanations.
3
+ Uses LLM to generate non-technical descriptions of what a query does.
4
+ """
5
+
6
+ import structlog
7
+ from app.prompts.registry import get_prompt_registry
8
+
9
+ logger = structlog.get_logger()
10
+
11
+
12
+ class SQLExplainer:
13
+ """Explains SQL queries in natural language for non-technical users."""
14
+
15
+ def __init__(self, llm_router):
16
+ self.llm_router = llm_router
17
+
18
+ def explain(self, sql: str, results_count: int = 0) -> str:
19
+ """
20
+ Generate a plain English explanation of a SQL query.
21
+ """
22
+ try:
23
+ prompt_template = get_prompt_registry().get("sql_explanation")
24
+ messages = prompt_template.render(sql=sql, results_count=results_count)
25
+ explanation = self.llm_router.generate(messages, model_preference="fast", max_tokens=256)
26
+ return explanation.strip()
27
+ except Exception as e:
28
+ logger.warning("sql_explanation_failed", error=str(e))
29
+ return "Unable to generate explanation at this time."
backend/app/ai_features/insights.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Auto Insights Generator β€” Statistical analysis and pattern detection on query results.
3
+ Generates human-readable insights without LLM (pure statistical analysis).
4
+ """
5
+
6
+ import structlog
7
+ from collections import Counter
8
+
9
+ logger = structlog.get_logger()
10
+
11
+
12
+ class InsightsGenerator:
13
+ """Generates statistical insights from query result data."""
14
+
15
+ def generate(self, results: list[dict], query: str = "") -> list[str]:
16
+ """
17
+ Analyze query results and generate human-readable insights.
18
+ Uses statistical methods β€” no LLM needed.
19
+ """
20
+ if not results:
21
+ return ["No data available for analysis."]
22
+
23
+ insights = []
24
+
25
+ # ── Basic stats ──────────────────────────────────
26
+ row_count = len(results)
27
+ col_count = len(results[0]) if results else 0
28
+ insights.append(f"πŸ“Š Dataset: **{row_count}** records across **{col_count}** columns")
29
+
30
+ # ── Classify columns ─────────────────────────────
31
+ numeric_cols = []
32
+ text_cols = []
33
+ date_cols = []
34
+ columns = list(results[0].keys()) if results else []
35
+
36
+ for col in columns:
37
+ sample = results[0].get(col)
38
+ col_lower = col.lower()
39
+
40
+ if any(d in col_lower for d in ["date", "time", "created", "updated"]):
41
+ date_cols.append(col)
42
+ elif isinstance(sample, (int, float)):
43
+ numeric_cols.append(col)
44
+ else:
45
+ try:
46
+ if sample is not None:
47
+ float(sample)
48
+ numeric_cols.append(col)
49
+ else:
50
+ text_cols.append(col)
51
+ except (ValueError, TypeError):
52
+ text_cols.append(col)
53
+
54
+ # ── Numeric column analysis ──────────────────────
55
+ for col in numeric_cols[:4]:
56
+ values = self._extract_numeric_values(results, col)
57
+ if not values:
58
+ continue
59
+
60
+ avg = sum(values) / len(values)
61
+ min_val = min(values)
62
+ max_val = max(values)
63
+ total = sum(values)
64
+
65
+ label = col.replace("_", " ").title()
66
+ insights.append(
67
+ f"**{label}**: Total {total:,.2f} | "
68
+ f"Avg {avg:,.2f} | Range [{min_val:,.2f} β€” {max_val:,.2f}]"
69
+ )
70
+
71
+ # Outlier detection (IQR method)
72
+ outliers = self._detect_outliers(values)
73
+ if outliers:
74
+ insights.append(
75
+ f"⚠️ **{len(outliers)} outliers** detected in {label} "
76
+ f"(values: {', '.join(f'{v:,.2f}' for v in outliers[:3])})"
77
+ )
78
+
79
+ # Concentration analysis
80
+ if len(values) > 1:
81
+ top_val = max(values)
82
+ top_pct = (top_val / total * 100) if total > 0 else 0
83
+ if top_pct > 30:
84
+ insights.append(f"🎯 Top value in **{label}** accounts for {top_pct:.1f}% of total")
85
+
86
+ # ── Text column analysis ─────────────────────────
87
+ for col in text_cols[:2]:
88
+ str_values = [str(row.get(col, "")) for row in results if row.get(col)]
89
+ if not str_values:
90
+ continue
91
+
92
+ counter = Counter(str_values)
93
+ unique_count = len(counter)
94
+ label = col.replace("_", " ").title()
95
+
96
+ if unique_count == row_count:
97
+ insights.append(f"πŸ”‘ **{label}** has all unique values")
98
+ elif unique_count <= 10:
99
+ top_items = counter.most_common(3)
100
+ distribution = ", ".join(f"'{k}' ({v})" for k, v in top_items)
101
+ insights.append(f"🏷️ **{label}** distribution: {distribution}")
102
+
103
+ # ── Trend detection ──────────────────────────────
104
+ if date_cols and numeric_cols and len(results) >= 3:
105
+ insights.append("πŸ“ˆ Time-series data detected β€” trend analysis available")
106
+
107
+ return insights
108
+
109
+ def _extract_numeric_values(self, results: list[dict], col: str) -> list[float]:
110
+ """Extract numeric values from a column, skipping nulls."""
111
+ values = []
112
+ for row in results:
113
+ v = row.get(col)
114
+ if v is not None:
115
+ try:
116
+ values.append(float(v))
117
+ except (ValueError, TypeError):
118
+ continue
119
+ return values
120
+
121
+ def _detect_outliers(self, values: list[float]) -> list[float]:
122
+ """Detect outliers using the IQR method."""
123
+ if len(values) < 4:
124
+ return []
125
+
126
+ sorted_vals = sorted(values)
127
+ n = len(sorted_vals)
128
+ q1 = sorted_vals[int(n * 0.25)]
129
+ q3 = sorted_vals[int(n * 0.75)]
130
+ iqr = q3 - q1
131
+
132
+ lower = q1 - 1.5 * iqr
133
+ upper = q3 + 1.5 * iqr
134
+
135
+ return [v for v in values if v < lower or v > upper]
backend/app/api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # API Package
backend/app/api/fast_path.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversational Fast-Path β€” Server-side detection for chat queries.
3
+
4
+ Handles greetings, thanks, identity questions, etc. without invoking the
5
+ full LLM pipeline. Provides instant (<1ms) responses for conversational queries.
6
+ """
7
+
8
+ import re
9
+
10
+ # ── Pattern Registry ─────────────────────────────────────
11
+ _CHAT_PATTERNS = [
12
+ re.compile(r'^(hi|hello|hey|howdy|sup|yo)\b[\s!.?]*$', re.I),
13
+ re.compile(r'^how are you\??[\s!.]*$', re.I),
14
+ re.compile(r'^thank(s| you)[\s!.,]*$', re.I),
15
+ re.compile(r'^(bye|goodbye|see you|cya|later)[\s!.]*$', re.I),
16
+ re.compile(r'^good (morning|afternoon|evening|night)[\s!.]*$', re.I),
17
+ re.compile(r'^(ok|okay|alright|great|perfect|cool|nice|awesome)[\s!.]*$', re.I),
18
+ re.compile(r'^(who are you|what are you|what is plainsql)\??$', re.I),
19
+ re.compile(r'^(what can you do|help me|help)\??[\s!.]*$', re.I),
20
+ ]
21
+
22
+ _CHAT_RESPONSES = {
23
+ 'greeting': "Hello! I'm PlainSQL β€” your AI-powered data assistant. Ask me anything about your database in plain English and I'll handle the SQL.",
24
+ 'thanks': "You're welcome! Let me know if you'd like to explore more insights from your data.",
25
+ 'farewell': "Goodbye! Your data will be here when you need it.",
26
+ 'identity': "I'm PlainSQL β€” an enterprise AI platform that converts natural language into SQL using a hybrid RAG + LLM pipeline.",
27
+ 'capabilities': "I can help you query your database in plain English, generate safe SQL, visualize results with charts, and provide AI insights. Try: 'Show me top 5 employees by salary'",
28
+ 'default': "I'm PlainSQL, your AI data assistant. Ask me questions about your database!",
29
+ }
30
+
31
+
32
+ def detect_conversational(query: str):
33
+ """
34
+ Returns a fast-path response string if the query is conversational, else None.
35
+
36
+ This avoids a full LLM round-trip for simple greetings/thanks/identity questions.
37
+ Average latency: <0.1ms.
38
+ """
39
+ q = query.strip()
40
+ if re.match(r'^(hi|hello|hey|howdy|sup|yo)\b', q, re.I):
41
+ return _CHAT_RESPONSES['greeting']
42
+ if re.match(r'^how are you', q, re.I):
43
+ return _CHAT_RESPONSES['greeting']
44
+ if re.match(r'^thank(s| you)', q, re.I):
45
+ return _CHAT_RESPONSES['thanks']
46
+ if re.match(r'^(bye|goodbye|see you)', q, re.I):
47
+ return _CHAT_RESPONSES['farewell']
48
+ if re.match(r'^(who are you|what are you|what is plainsql)', q, re.I):
49
+ return _CHAT_RESPONSES['identity']
50
+ if re.match(r'^(what can you do|help)', q, re.I):
51
+ return _CHAT_RESPONSES['capabilities']
52
+ for pat in _CHAT_PATTERNS:
53
+ if pat.match(q):
54
+ return _CHAT_RESPONSES['default']
55
+ return None
backend/app/api/middleware.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ API Middleware β€” Auth verification, rate limiting, and request logging.
3
+ """
4
+
5
+ import time
6
+ import hashlib
7
+ import structlog
8
+ from fastapi import Request
9
+ from typing import Optional
10
+
11
+ from app.auth.jwt_auth import AuthService
12
+ from app.observability.metrics import metrics
13
+
14
+ logger = structlog.get_logger()
15
+
16
+
17
+ # ── In-Memory Rate Limiter (upgrade to Redis for production) ──
18
+
19
+ class InMemoryRateLimiter:
20
+ """
21
+ Simple in-memory rate limiter using sliding window counters.
22
+ For production, use Redis-backed implementation.
23
+ """
24
+
25
+ def __init__(self, requests_per_minute: int = 60):
26
+ self.rpm = requests_per_minute
27
+ self._counters: dict[str, list[float]] = {}
28
+ self._call_count = 0
29
+
30
+ def check(self, key: str) -> bool:
31
+ """Returns True if request is allowed, False if rate limited."""
32
+ now = time.time()
33
+ window_start = now - 60
34
+
35
+ if key not in self._counters:
36
+ self._counters[key] = []
37
+
38
+ # Clean old entries for this key
39
+ self._counters[key] = [t for t in self._counters[key] if t > window_start]
40
+
41
+ # Periodic cleanup of dead keys to prevent unbounded memory growth
42
+ self._call_count += 1
43
+ if self._call_count % 500 == 0:
44
+ dead_keys = [k for k, v in self._counters.items() if not v]
45
+ for k in dead_keys:
46
+ del self._counters[k]
47
+
48
+ if len(self._counters[key]) >= self.rpm:
49
+ return False
50
+
51
+ self._counters[key].append(now)
52
+ return True
53
+
54
+
55
+ # ── In-Memory Query Cache ────────────────────────────────
56
+
57
+ class QueryCache:
58
+ """
59
+ Simple in-memory query cache.
60
+ For production, upgrade to Redis.
61
+ """
62
+
63
+ def __init__(self, ttl_seconds: int = 300, max_entries: int = 500):
64
+ self.ttl = ttl_seconds
65
+ self.max_entries = max_entries
66
+ self._cache: dict[str, dict] = {}
67
+
68
+ def _make_key(self, query: str, tenant_id: str = "default") -> str:
69
+ raw = f"{tenant_id}:{query.strip().lower()}"
70
+ return hashlib.sha256(raw.encode()).hexdigest()[:16]
71
+
72
+ def get(self, query: str, tenant_id: str = "default") -> Optional[dict]:
73
+ key = self._make_key(query, tenant_id)
74
+ entry = self._cache.get(key)
75
+ if entry and time.time() - entry["timestamp"] < self.ttl:
76
+ return entry["data"]
77
+ elif entry:
78
+ del self._cache[key]
79
+ return None
80
+
81
+ def set(self, query: str, data: dict, tenant_id: str = "default"):
82
+ key = self._make_key(query, tenant_id)
83
+ # Evict oldest if at capacity
84
+ if len(self._cache) >= self.max_entries:
85
+ oldest_key = min(self._cache, key=lambda k: self._cache[k]["timestamp"])
86
+ del self._cache[oldest_key]
87
+ self._cache[key] = {"data": data, "timestamp": time.time(), "tenant_id": tenant_id}
88
+
89
+ def invalidate(self, tenant_id: str = "default"):
90
+ """Clear all cache entries for a specific tenant.
91
+ Cache keys are SHA-256 hashes of '{tenant_id}:{query}', so we must
92
+ recheck by storing the tenant_id alongside the cached data.
93
+ """
94
+ keys_to_delete = [
95
+ k for k, v in self._cache.items()
96
+ if v.get("tenant_id", "default") == tenant_id
97
+ ]
98
+ for k in keys_to_delete:
99
+ del self._cache[k]
100
+
101
+ def invalidate_all(self):
102
+ """Clear the entire cache (all tenants)."""
103
+ self._cache.clear()
104
+
105
+
106
+ # ── Auth Dependency ──────────────────────────────────────
107
+
108
+ def create_auth_dependency(auth_service: AuthService):
109
+ """
110
+ Create a FastAPI dependency for JWT authentication.
111
+ Token is OPTIONAL β€” unauthenticated requests receive a guest analyst identity.
112
+ This allows the frontend to work without login for development/demo use.
113
+ """
114
+ # Default guest identity for unauthenticated requests
115
+ GUEST_USER = {
116
+ "sub": "guest",
117
+ "username": "guest",
118
+ "role": "analyst",
119
+ "tenant_id": "default",
120
+ }
121
+
122
+ def get_current_user(request: Request) -> dict:
123
+ auth_header = request.headers.get("Authorization", "")
124
+ api_key = request.headers.get("X-API-Key", "")
125
+
126
+ # No credentials provided β€” return guest identity (no 401)
127
+ if not auth_header.startswith("Bearer ") and not api_key:
128
+ return GUEST_USER
129
+
130
+ token = auth_header[7:] if auth_header.startswith("Bearer ") else api_key
131
+
132
+ try:
133
+ payload = auth_service.verify_token(token)
134
+ return payload
135
+ except Exception as e:
136
+ metrics.increment("plainsql_auth_failures_total")
137
+ logger.warning("auth_failed", error=str(e))
138
+ # Invalid token β†’ still return guest rather than blocking (dev-friendly)
139
+ return GUEST_USER
140
+
141
+ return get_current_user
142
+
143
+
144
+
145
+ # ── Request Logging Middleware ─────���─────────────────────
146
+
147
+ class RequestLoggingMiddleware:
148
+ """Log all API requests with timing."""
149
+
150
+ def __init__(self, app):
151
+ self.app = app
152
+
153
+ async def __call__(self, scope, receive, send):
154
+ if scope["type"] != "http":
155
+ await self.app(scope, receive, send)
156
+ return
157
+
158
+ start_time = time.time()
159
+ request = Request(scope, receive)
160
+
161
+ # Track active requests
162
+ metrics.set_gauge("plainsql_active_requests", 1)
163
+
164
+ try:
165
+ await self.app(scope, receive, send)
166
+ finally:
167
+ elapsed = round((time.time() - start_time) * 1000, 2)
168
+ metrics.set_gauge("plainsql_active_requests", 0)
169
+
170
+ logger.info(
171
+ "http_request",
172
+ method=request.method,
173
+ path=request.url.path,
174
+ elapsed_ms=elapsed,
175
+ )
backend/app/api/routes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Routes Package
backend/app/api/routes/admin.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Admin Routes β€” Administrative operations requiring admin role.
3
+ Includes schema reindexing, cache invalidation, token usage, and system management.
4
+ """
5
+
6
+ from fastapi import APIRouter, Depends, HTTPException
7
+ from fastapi.responses import JSONResponse
8
+ import structlog
9
+
10
+ logger = structlog.get_logger()
11
+
12
+
13
+ def create_admin_router(
14
+ rag_retriever,
15
+ cache,
16
+ auth_dep,
17
+ db_pool,
18
+ llm_router=None,
19
+ orchestrator=None,
20
+ ):
21
+ """Factory to create admin routes with injected dependencies."""
22
+
23
+ router = APIRouter(prefix="/api/v1/admin", tags=["Admin"])
24
+
25
+ def _require_admin(user=Depends(auth_dep)):
26
+ """Ensure the authenticated user has admin role."""
27
+ if user.get("role") != "admin":
28
+ raise HTTPException(status_code=403, detail="Admin role required")
29
+ return user
30
+
31
+ @router.post("/reindex")
32
+ def reindex_schema(user=Depends(_require_admin)):
33
+ """
34
+ Re-index the database schema into RAG (ChromaDB + BM25).
35
+ Call this after schema changes (new tables, columns, etc.).
36
+ """
37
+ try:
38
+ rag_retriever.refresh_index()
39
+ doc_count = rag_retriever.collection.count()
40
+ logger.info("admin_reindex_complete", triggered_by=user.get("username"), docs=doc_count)
41
+ return {
42
+ "status": "ok",
43
+ "message": f"Schema re-indexed successfully. {doc_count} documents indexed.",
44
+ "document_count": doc_count,
45
+ }
46
+ except Exception as e:
47
+ logger.error("admin_reindex_failed", error=str(e))
48
+ return JSONResponse(
49
+ status_code=500,
50
+ content={"error": f"Reindex failed: {str(e)}"},
51
+ )
52
+
53
+ @router.post("/cache/invalidate")
54
+ def invalidate_cache(user=Depends(_require_admin)):
55
+ """Clear the entire query cache."""
56
+ try:
57
+ if hasattr(cache, "invalidate_all"):
58
+ cache.invalidate_all()
59
+ # Also clear semantic cache if available
60
+ if orchestrator and hasattr(orchestrator, "semantic_cache") and orchestrator.semantic_cache:
61
+ orchestrator.semantic_cache.invalidate_all()
62
+ logger.info("admin_cache_invalidated", triggered_by=user.get("username"))
63
+ return {"status": "ok", "message": "Cache invalidated successfully."}
64
+ except Exception as e:
65
+ logger.error("admin_cache_invalidate_failed", error=str(e))
66
+ return JSONResponse(
67
+ status_code=500,
68
+ content={"error": f"Cache invalidation failed: {str(e)}"},
69
+ )
70
+
71
+ @router.get("/pool-status")
72
+ def pool_status(user=Depends(_require_admin)):
73
+ """Get database connection pool statistics."""
74
+ try:
75
+ pool_info = db_pool.get_pool_status()
76
+ return {"status": "ok", "pool": pool_info}
77
+ except Exception as e:
78
+ return JSONResponse(
79
+ status_code=500,
80
+ content={"error": f"Pool status unavailable: {str(e)}"},
81
+ )
82
+
83
+ @router.get("/token-usage")
84
+ def token_usage(user=Depends(_require_admin)):
85
+ """
86
+ Get aggregate LLM token usage and cost statistics.
87
+
88
+ Returns:
89
+ Total input/output tokens, estimated cost, request count,
90
+ and average tokens per request.
91
+ """
92
+ if not llm_router:
93
+ return JSONResponse(
94
+ status_code=503,
95
+ content={"error": "LLM router not available"},
96
+ )
97
+ try:
98
+ usage = llm_router.get_token_usage()
99
+ # Add semantic cache stats if available
100
+ cache_stats = None
101
+ if orchestrator and hasattr(orchestrator, "semantic_cache") and orchestrator.semantic_cache:
102
+ cache_stats = orchestrator.semantic_cache.stats()
103
+
104
+ return {
105
+ "status": "ok",
106
+ "token_usage": usage,
107
+ "semantic_cache": cache_stats,
108
+ }
109
+ except Exception as e:
110
+ return JSONResponse(
111
+ status_code=500,
112
+ content={"error": f"Token usage unavailable: {str(e)}"},
113
+ )
114
+
115
+ return router
116
+
backend/app/api/routes/chat.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chat & Query Routes β€” Core API endpoints for text-to-SQL.
3
+ Includes SSE streaming for real-time pipeline feedback.
4
+ """
5
+
6
+ import json
7
+ from fastapi import APIRouter, Depends, HTTPException
8
+ from fastapi.responses import StreamingResponse
9
+ from app.api.schemas import (
10
+ GenerateSQLRequest, QueryResult,
11
+ ExecuteQueryRequest,
12
+ ExplainRequest, ExplainResponse,
13
+ InsightsRequest, InsightsResponse,
14
+ )
15
+
16
+ router = APIRouter(prefix="/api/v1", tags=["Query"])
17
+
18
+
19
+ def create_chat_router(orchestrator, auth_dep, cache, rate_limiter, tracer, explainer, insights_gen, anomaly_detector, safety_validator):
20
+ """Factory to create chat router with injected dependencies."""
21
+
22
+ @router.post("/generate-sql", response_model=QueryResult)
23
+ def generate_sql(request: GenerateSQLRequest, current_user: dict = Depends(auth_dep)):
24
+ """
25
+ Generate SQL from natural language and optionally execute it.
26
+ The full multi-agent pipeline runs here.
27
+ """
28
+ # Rate limiting
29
+ user_key = f"rl:{current_user.get('sub', 'anon')}"
30
+ if not rate_limiter.check(user_key):
31
+ raise HTTPException(429, "Rate limit exceeded. Please wait a moment.")
32
+
33
+ # Check cache
34
+ cached = cache.get(request.question, current_user.get("tenant_id", "default"))
35
+ if cached:
36
+ cached["trace_id"] = "cached"
37
+ return QueryResult(**cached)
38
+
39
+ # Run multi-agent pipeline
40
+ result = orchestrator.process_query(
41
+ user_query=request.question,
42
+ conversation_history=request.history,
43
+ tenant_id=current_user.get("tenant_id", "default"),
44
+ user_role=current_user.get("role", "viewer"),
45
+ )
46
+
47
+ # Trace the query
48
+ tracer.trace_query(result)
49
+
50
+ # Build response
51
+ response_data = {
52
+ "trace_id": result.get("trace_id", ""),
53
+ "question": request.question,
54
+ "intent": result.get("intent"),
55
+ "sql": result.get("sanitized_sql") or result.get("generated_sql"),
56
+ "sql_explanation": result.get("sql_explanation"),
57
+ "message": result.get("friendly_message", ""),
58
+ "data": result.get("query_results", []),
59
+ "row_count": result.get("row_count", 0),
60
+ "column_names": result.get("column_names", []),
61
+ "execution_time_ms": result.get("execution_time_ms", 0),
62
+ "chart_config": result.get("chart_config"),
63
+ "chart_type": result.get("chart_type"),
64
+ "insights": result.get("insights", []),
65
+ "follow_ups": result.get("follow_up_questions", []),
66
+ "error": result.get("error"),
67
+ }
68
+
69
+ # Cache successful results
70
+ if not result.get("error") and result.get("query_results"):
71
+ cache.set(request.question, response_data, current_user.get("tenant_id", "default"))
72
+
73
+ return QueryResult(**response_data)
74
+
75
+ @router.post("/chat/stream")
76
+ async def chat_stream(request: GenerateSQLRequest, current_user: dict = Depends(auth_dep)):
77
+ """
78
+ Stream chat responses via Server-Sent Events (SSE).
79
+ Each agent stage emits an event as it completes.
80
+ """
81
+ user_key = f"rl:{current_user.get('sub', 'anon')}"
82
+ if not rate_limiter.check(user_key):
83
+ raise HTTPException(429, "Rate limit exceeded.")
84
+
85
+ async def event_generator():
86
+ async for event in orchestrator.aprocess_query_streaming(
87
+ user_query=request.question,
88
+ conversation_history=request.history,
89
+ tenant_id=current_user.get("tenant_id", "default"),
90
+ user_role=current_user.get("role", "viewer"),
91
+ ):
92
+ event_type = event.get("type", "message")
93
+ yield _sse_event(event_type, event)
94
+
95
+ return StreamingResponse(
96
+ event_generator(),
97
+ media_type="text/event-stream",
98
+ headers={
99
+ "Cache-Control": "no-cache",
100
+ "Connection": "keep-alive",
101
+ "X-Accel-Buffering": "no",
102
+ },
103
+ )
104
+
105
+ @router.post("/execute-query", response_model=QueryResult)
106
+ def execute_query(request: ExecuteQueryRequest, current_user: dict = Depends(auth_dep)):
107
+ """Execute a user-provided SQL query (must pass safety validation)."""
108
+ from app.agents.sql_validation import sql_validation_node
109
+
110
+ # Validate the SQL
111
+ validation_state = {"generated_sql": request.sql, "retry_count": 0, "trace_id": "manual"}
112
+ validation_result = sql_validation_node(validation_state)
113
+
114
+ if not validation_result.get("is_valid"):
115
+ errors = validation_result.get("validation_errors", ["Unknown validation error"])
116
+ raise HTTPException(400, f"SQL blocked by safety layer: {', '.join(errors)}")
117
+
118
+ # Execute
119
+ from app.agents.execution import execution_node
120
+ exec_state = {**validation_result, "trace_id": "manual"}
121
+ exec_result = execution_node(exec_state, orchestrator.db_pool)
122
+
123
+ if exec_result.get("error"):
124
+ raise HTTPException(400, exec_result["error"])
125
+
126
+ return QueryResult(
127
+ trace_id="manual",
128
+ question="Manual SQL execution",
129
+ sql=request.sql,
130
+ message=f"Query executed successfully. {exec_result.get('row_count', 0)} rows returned.",
131
+ data=exec_result.get("query_results", []),
132
+ row_count=exec_result.get("row_count", 0),
133
+ column_names=exec_result.get("column_names", []),
134
+ execution_time_ms=exec_result.get("execution_time_ms", 0),
135
+ )
136
+
137
+ @router.post("/explain", response_model=ExplainResponse)
138
+ def explain_sql(request: ExplainRequest, current_user: dict = Depends(auth_dep)):
139
+ """Explain a SQL query in natural language."""
140
+ explanation = explainer.explain(request.sql, request.result_count)
141
+ return ExplainResponse(sql=request.sql, explanation=explanation)
142
+
143
+ @router.post("/insights", response_model=InsightsResponse)
144
+ def get_insights(request: InsightsRequest, current_user: dict = Depends(auth_dep)):
145
+ """Generate auto-insights and anomaly detection for data."""
146
+ insights = insights_gen.generate(request.data, request.query)
147
+ anomalies = anomaly_detector.detect(request.data)
148
+ return InsightsResponse(insights=insights, anomalies=anomalies)
149
+
150
+ return router
151
+
152
+
153
+ def _sse_event(event_type: str, data: dict) -> str:
154
+ """Format a Server-Sent Event."""
155
+ payload = json.dumps({"type": event_type, **data}, default=str)
156
+ return f"event: {event_type}\ndata: {payload}\n\n"
backend/app/api/routes/conversations.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversations API Router β€” CRUD for server-side chat persistence.
3
+
4
+ Provides endpoints for managing conversations and messages,
5
+ enabling cross-device chat history and user-bound data.
6
+ """
7
+
8
+ from fastapi import APIRouter, HTTPException
9
+ from pydantic import BaseModel, Field
10
+ import structlog
11
+
12
+ logger = structlog.get_logger()
13
+
14
+
15
+ def create_conversations_router(conversation_manager, auth_dep=None):
16
+ """Factory function to create the conversations router with injected dependencies."""
17
+ router = APIRouter(prefix="/api/v1/conversations", tags=["conversations"])
18
+
19
+ class CreateConversationRequest(BaseModel):
20
+ title: str = Field(default="New analysis", max_length=255)
21
+
22
+ class UpdateTitleRequest(BaseModel):
23
+ title: str = Field(..., min_length=1, max_length=255)
24
+
25
+ # ── List conversations ───────────────────────────────
26
+ @router.get("")
27
+ async def list_conversations():
28
+ """List all conversations for the current user."""
29
+ try:
30
+ conversations = conversation_manager.list_conversations(user_id="anonymous")
31
+ return {"conversations": conversations}
32
+ except Exception as e:
33
+ logger.error("list_conversations_failed", error=str(e))
34
+ raise HTTPException(status_code=500, detail="Failed to load conversations")
35
+
36
+ # ── Create conversation ──────────────────────────────
37
+ @router.post("")
38
+ async def create_conversation(request: CreateConversationRequest):
39
+ """Create a new conversation."""
40
+ try:
41
+ conv = conversation_manager.create_conversation(
42
+ title=request.title,
43
+ user_id="anonymous",
44
+ )
45
+ return conv
46
+ except Exception as e:
47
+ logger.error("create_conversation_failed", error=str(e))
48
+ raise HTTPException(status_code=500, detail="Failed to create conversation")
49
+
50
+ # ── Update conversation title ────────────────────────
51
+ @router.patch("/{conversation_id}")
52
+ async def update_conversation(conversation_id: str, request: UpdateTitleRequest):
53
+ """Update a conversation's title."""
54
+ try:
55
+ conversation_manager.update_title(conversation_id, request.title)
56
+ return {"status": "ok"}
57
+ except Exception as e:
58
+ logger.error("update_conversation_failed", error=str(e))
59
+ raise HTTPException(status_code=500, detail="Failed to update conversation")
60
+
61
+ # ── Delete conversation ──────────────────────────────
62
+ @router.delete("/{conversation_id}")
63
+ async def delete_conversation(conversation_id: str):
64
+ """Delete a conversation and all its messages."""
65
+ try:
66
+ conversation_manager.delete_conversation(conversation_id, user_id="anonymous")
67
+ return {"status": "ok"}
68
+ except Exception as e:
69
+ logger.error("delete_conversation_failed", error=str(e))
70
+ raise HTTPException(status_code=500, detail="Failed to delete conversation")
71
+
72
+ # ── Get messages ─────────────────────────────────────
73
+ @router.get("/{conversation_id}/messages")
74
+ async def get_messages(conversation_id: str):
75
+ """Get all messages in a conversation."""
76
+ try:
77
+ messages = conversation_manager.get_messages(conversation_id)
78
+ return {"messages": messages}
79
+ except Exception as e:
80
+ logger.error("get_messages_failed", error=str(e))
81
+ raise HTTPException(status_code=500, detail="Failed to load messages")
82
+
83
+ return router
backend/app/api/routes/monitoring.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Monitoring Routes β€” Prometheus-native metrics and dashboard JSON endpoint.
3
+ Exposes query volume, latency, success rates, and error breakdowns.
4
+
5
+ Uses prometheus_client when available for native Prometheus format.
6
+ Falls back to in-process metrics for local development.
7
+ """
8
+
9
+ from fastapi import APIRouter, Response
10
+ from app.observability.metrics import (
11
+ metrics,
12
+ get_prometheus_metrics,
13
+ get_prometheus_content_type,
14
+ )
15
+
16
+ router = APIRouter(prefix="/api/v1/metrics", tags=["Monitoring"])
17
+
18
+
19
+ class QueryMetricsRecorder:
20
+ """
21
+ Thin wrapper that records query-level metrics into the unified MetricsCollector.
22
+ This replaces the old duplicate MetricsCollector that was in this file.
23
+ """
24
+
25
+ def record_query(
26
+ self,
27
+ latency_ms: float,
28
+ intent: str = "unknown",
29
+ success: bool = True,
30
+ error_agent: str = None,
31
+ ):
32
+ """Record a single query execution into the unified metrics system."""
33
+ status = "success" if success else "error"
34
+ metrics.increment("plainsql_queries_total", {"intent": intent, "status": status})
35
+ metrics.observe("plainsql_query_latency_ms", latency_ms, {"intent": intent})
36
+
37
+ if not success and error_agent:
38
+ metrics.increment("plainsql_agent_errors_total", {"agent": error_agent})
39
+
40
+
41
+ # Module-level singleton
42
+ _recorder = QueryMetricsRecorder()
43
+
44
+
45
+ def get_metrics_collector() -> QueryMetricsRecorder:
46
+ """Get the global metrics recorder singleton."""
47
+ return _recorder
48
+
49
+
50
+ def create_monitoring_router() -> APIRouter:
51
+ """Factory to create monitoring router."""
52
+
53
+ @router.get("/prometheus")
54
+ def prometheus_metrics_endpoint():
55
+ """
56
+ Expose metrics in Prometheus exposition format for scraping.
57
+ Uses native prometheus_client output when available.
58
+ """
59
+ content = get_prometheus_metrics()
60
+ return Response(
61
+ content=content,
62
+ media_type=get_prometheus_content_type(),
63
+ )
64
+
65
+ @router.get("/dashboard")
66
+ def dashboard_metrics():
67
+ """JSON metrics for the frontend or internal dashboard."""
68
+ return metrics.get_all_metrics()
69
+
70
+ return router
backend/app/api/routes/system.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Auth, Schema, Analytics, and Health Routes.
3
+ """
4
+
5
+ from fastapi import APIRouter, Depends, HTTPException, status
6
+ from app.api.schemas import (
7
+ LoginRequest, RegisterRequest, TokenResponse,
8
+ APIKeyRequest, APIKeyResponse,
9
+ SchemaResponse, AnalyticsResponse, HealthResponse,
10
+ )
11
+
12
+ router = APIRouter(tags=["System"])
13
+
14
+
15
+ def create_system_router(auth_service, auth_dep, db_pool, rag_retriever, llm_router, tracer, user_repo, start_time):
16
+ """Factory to create system routes with injected dependencies."""
17
+
18
+ # ── Auth Routes ──────────────────────────────────────
19
+
20
+ auth_router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
21
+
22
+ @auth_router.post("/login", response_model=TokenResponse)
23
+ def login(request: LoginRequest):
24
+ """Authenticate and get JWT token."""
25
+ user = user_repo.get_by_username(request.username)
26
+ if not user or not auth_service.verify_password(request.password, user["password_hash"]):
27
+ raise HTTPException(
28
+ status_code=status.HTTP_401_UNAUTHORIZED,
29
+ detail="Invalid username or password",
30
+ )
31
+
32
+ token = auth_service.create_access_token(
33
+ user_id=user["id"],
34
+ username=user["username"],
35
+ role=user["role"],
36
+ tenant_id=user.get("tenant_id", "default"),
37
+ )
38
+
39
+ return TokenResponse(
40
+ access_token=token,
41
+ role=user["role"],
42
+ tenant_id=user.get("tenant_id", "default"),
43
+ )
44
+
45
+ @auth_router.post("/register", response_model=TokenResponse)
46
+ def register(request: RegisterRequest):
47
+ """Register a new user. Self-registration is always 'viewer' role.
48
+ Only admins can promote users via a separate endpoint."""
49
+ if user_repo.get_by_username(request.username):
50
+ raise HTTPException(400, "Username already exists")
51
+
52
+ password_hash = auth_service.hash_password(request.password)
53
+ user_id = f"user_{user_repo.count() + 1}"
54
+
55
+ # SECURITY: Self-registration is always viewer.
56
+ # Elevated roles (analyst, admin) must be granted by an existing admin.
57
+ assigned_role = "viewer"
58
+
59
+ success = user_repo.create(
60
+ user_id=user_id,
61
+ username=request.username,
62
+ email=request.email,
63
+ password_hash=password_hash,
64
+ role=assigned_role,
65
+ tenant_id=request.tenant_id,
66
+ )
67
+ if not success:
68
+ raise HTTPException(500, "Failed to register user")
69
+
70
+ token = auth_service.create_access_token(
71
+ user_id=user_id,
72
+ username=request.username,
73
+ role=assigned_role,
74
+ tenant_id=request.tenant_id,
75
+ )
76
+
77
+ return TokenResponse(
78
+ access_token=token,
79
+ role=assigned_role,
80
+ tenant_id=request.tenant_id,
81
+ )
82
+
83
+ @auth_router.post("/api-keys", response_model=APIKeyResponse)
84
+ def create_api_key(request: APIKeyRequest, current_user: dict = Depends(auth_dep)):
85
+ """Create a long-lived API key (admin only)."""
86
+ if current_user.get("role") != "admin":
87
+ raise HTTPException(403, "Only admins can create API keys")
88
+
89
+ api_key = auth_service.create_api_key_token(
90
+ key_name=request.key_name,
91
+ tenant_id=current_user.get("tenant_id", "default"),
92
+ role=request.role,
93
+ )
94
+
95
+ return APIKeyResponse(
96
+ key_name=request.key_name,
97
+ api_key=api_key,
98
+ role=request.role,
99
+ )
100
+
101
+ # ── Schema Route ─────────────────────────────────────
102
+
103
+ schema_router = APIRouter(prefix="/api/v1", tags=["Schema"])
104
+
105
+ @schema_router.get("/schema", response_model=SchemaResponse)
106
+ def get_schema(current_user: dict = Depends(auth_dep)):
107
+ """Get database schema for the current tenant."""
108
+ tables = db_pool.get_tables()
109
+ schema_text = db_pool.get_full_schema()
110
+ return SchemaResponse(
111
+ tables=tables,
112
+ schema_text=schema_text,
113
+ table_count=len(tables),
114
+ )
115
+
116
+ @schema_router.post("/schema/refresh")
117
+ def refresh_schema(current_user: dict = Depends(auth_dep)):
118
+ """Re-index the schema (admin only)."""
119
+ if current_user.get("role") != "admin":
120
+ raise HTTPException(403, "Only admins can refresh schema")
121
+ rag_retriever.refresh_index()
122
+ return {"message": "Schema re-indexed successfully"}
123
+
124
+ # ── Analytics Route ──────────────────────────────────
125
+
126
+ analytics_router = APIRouter(prefix="/api/v1", tags=["Analytics"])
127
+
128
+ @analytics_router.get("/analytics", response_model=AnalyticsResponse)
129
+ def get_analytics(current_user: dict = Depends(auth_dep)):
130
+ """Get usage analytics and metrics."""
131
+ if current_user.get("role") not in ("admin", "analyst"):
132
+ raise HTTPException(403, "Insufficient permissions for analytics")
133
+
134
+ dashboard = tracer.get_dashboard_metrics()
135
+ return AnalyticsResponse(**dashboard)
136
+
137
+ # ── Health Route ─────────────────────────────────────
138
+
139
+ health_router = APIRouter(tags=["Health"])
140
+
141
+ @health_router.get("/api/v1/health", response_model=HealthResponse)
142
+ def health_check():
143
+ """System health check β€” no auth required."""
144
+ import time as _time
145
+
146
+ try:
147
+ db_status = "connected"
148
+ db_pool.get_tables()
149
+ except Exception:
150
+ db_status = "disconnected"
151
+
152
+ try:
153
+ provider_status = llm_router.get_provider_status()
154
+ except Exception:
155
+ provider_status = {}
156
+
157
+ try:
158
+ rag_count = rag_retriever.collection.count()
159
+ except Exception:
160
+ rag_count = 0
161
+
162
+ return HealthResponse(
163
+ status="healthy" if db_status == "connected" else "degraded",
164
+ version="2.0.0",
165
+ database=db_status,
166
+ llm_providers=provider_status,
167
+ rag_indexed_tables=rag_count,
168
+ uptime_seconds=round(_time.time() - start_time, 2),
169
+ )
170
+
171
+ # NOTE: Prometheus metrics endpoint moved to /api/v1/metrics/prometheus
172
+ # in monitoring.py to avoid duplicate metrics systems.
173
+
174
+
175
+ @health_router.get("/api/v1/pool-status")
176
+ def pool_status(current_user: dict = Depends(auth_dep)):
177
+ """Database connection pool statistics (admin only)."""
178
+ if current_user.get("role") != "admin":
179
+ raise HTTPException(403, "Only admins can view pool status")
180
+ try:
181
+ return db_pool.get_pool_status()
182
+ except Exception as e:
183
+ return {"error": str(e)}
184
+
185
+ @health_router.get("/api/v1/prompt-templates")
186
+ def list_prompt_templates(current_user: dict = Depends(auth_dep)):
187
+ """List all registered prompt templates and their versions (admin only)."""
188
+ if current_user.get("role") != "admin":
189
+ raise HTTPException(403, "Only admins can view prompt templates")
190
+ from app.prompts.registry import get_prompt_registry
191
+ return get_prompt_registry().list_templates()
192
+
193
+ return auth_router, schema_router, analytics_router, health_router
backend/app/api/schemas.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic Request/Response Schemas β€” Type-safe API contracts.
3
+ """
4
+
5
+ from pydantic import BaseModel, Field
6
+ from typing import Optional, Any
7
+
8
+
9
+ # ── Chat / Query Schemas ─────────────────────────────────
10
+
11
+ class GenerateSQLRequest(BaseModel):
12
+ """Request to generate SQL from natural language."""
13
+ question: str = Field(..., min_length=1, max_length=1000, description="Natural language question")
14
+ history: list[dict] = Field(default=[], description="Conversation history")
15
+ execute: bool = Field(default=True, description="Execute the generated SQL immediately")
16
+
17
+
18
+ class QueryResult(BaseModel):
19
+ """Unified query response."""
20
+ trace_id: str
21
+ question: str
22
+ intent: Optional[str] = None
23
+ sql: Optional[str] = None
24
+ sql_explanation: Optional[str] = None
25
+ message: str
26
+ data: list[dict] = []
27
+ row_count: int = 0
28
+ column_names: list[str] = []
29
+ execution_time_ms: float = 0
30
+ chart_config: Optional[dict] = None
31
+ chart_type: Optional[str] = None
32
+ insights: list[str] = []
33
+ follow_ups: list[str] = []
34
+ error: Optional[str] = None
35
+
36
+
37
+ class ExecuteQueryRequest(BaseModel):
38
+ """Request to execute a specific SQL query."""
39
+ sql: str = Field(..., min_length=1, max_length=5000, description="SQL query to execute")
40
+
41
+
42
+ # ── Auth Schemas ─────────────────────────────────────────
43
+
44
+ class LoginRequest(BaseModel):
45
+ """Login credentials."""
46
+ username: str = Field(..., min_length=2, max_length=50)
47
+ password: str = Field(..., min_length=6, max_length=128)
48
+
49
+
50
+ class RegisterRequest(BaseModel):
51
+ """New user registration."""
52
+ username: str = Field(..., min_length=2, max_length=50)
53
+ password: str = Field(..., min_length=6, max_length=128)
54
+ email: str = Field(..., max_length=100)
55
+ role: str = Field(default="viewer", description="viewer | analyst | admin")
56
+ tenant_id: str = Field(default="default")
57
+
58
+
59
+ class TokenResponse(BaseModel):
60
+ """JWT token response."""
61
+ access_token: str
62
+ token_type: str = "bearer"
63
+ role: str
64
+ tenant_id: str
65
+ expires_in: int = 28800 # 8 hours in seconds
66
+
67
+
68
+ class APIKeyRequest(BaseModel):
69
+ """Create API key request."""
70
+ key_name: str = Field(..., min_length=2, max_length=50)
71
+ role: str = Field(default="analyst")
72
+
73
+
74
+ class APIKeyResponse(BaseModel):
75
+ """API key creation response."""
76
+ key_name: str
77
+ api_key: str
78
+ role: str
79
+ expires_in_days: int = 90
80
+
81
+
82
+ # ── Explain / Insights Schemas ───────────────────────────
83
+
84
+ class ExplainRequest(BaseModel):
85
+ """Request to explain SQL in natural language."""
86
+ sql: str = Field(..., min_length=1, max_length=5000)
87
+ result_count: int = Field(default=0, ge=0)
88
+
89
+
90
+ class ExplainResponse(BaseModel):
91
+ """SQL explanation response."""
92
+ sql: str
93
+ explanation: str
94
+
95
+
96
+ class InsightsRequest(BaseModel):
97
+ """Request auto-insights for data."""
98
+ data: list[dict] = Field(..., min_length=1)
99
+ query: str = Field(default="")
100
+
101
+
102
+ class InsightsResponse(BaseModel):
103
+ """Generated insights response."""
104
+ insights: list[str]
105
+ anomalies: list[dict] = []
106
+
107
+
108
+ # ── Schema / Analytics Schemas ───────────────────────────
109
+
110
+ class SchemaResponse(BaseModel):
111
+ """Database schema response."""
112
+ tables: list[str]
113
+ schema_text: str
114
+ table_count: int
115
+
116
+
117
+ class AnalyticsResponse(BaseModel):
118
+ """Usage analytics response."""
119
+ total_queries: int
120
+ successful_queries: int
121
+ failed_queries: int
122
+ latency_stats: dict
123
+ all_metrics: dict
124
+
125
+
126
+ # ── Health Check ─────────────────────────────────────────
127
+
128
+ class HealthResponse(BaseModel):
129
+ """System health check response."""
130
+ status: str
131
+ version: str
132
+ database: str
133
+ llm_providers: dict[str, Any]
134
+ rag_indexed_tables: int
135
+ uptime_seconds: float
backend/app/auth/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Auth Package
backend/app/auth/jwt_auth.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JWT Authentication Service β€” Token creation, verification, and password hashing.
3
+ Production-grade auth with bcrypt password hashing and configurable expiry.
4
+ """
5
+
6
+ import bcrypt
7
+ import structlog
8
+ from datetime import datetime, timedelta, timezone
9
+ from typing import Optional
10
+ from jose import jwt, JWTError
11
+
12
+ logger = structlog.get_logger()
13
+
14
+
15
+ class AuthService:
16
+ """
17
+ JWT-based authentication service.
18
+ Handles token creation, verification, and password hashing.
19
+ """
20
+
21
+ def __init__(self, secret_key: str, algorithm: str = "HS256", expiry_hours: int = 8):
22
+ self.secret_key = secret_key
23
+ self.algorithm = algorithm
24
+ self.expiry_hours = expiry_hours
25
+
26
+ # ── Password Hashing ─────────────────────────────────
27
+
28
+ @staticmethod
29
+ def hash_password(password: str) -> str:
30
+ """Hash a plaintext password using bcrypt."""
31
+ pwd_bytes = password.encode("utf-8")
32
+ salt = bcrypt.gensalt()
33
+ return bcrypt.hashpw(pwd_bytes, salt).decode("utf-8")
34
+
35
+ @staticmethod
36
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
37
+ """Verify a plaintext password against a bcrypt hash."""
38
+ return bcrypt.checkpw(
39
+ plain_password.encode("utf-8"),
40
+ hashed_password.encode("utf-8"),
41
+ )
42
+
43
+ # ── Token Management ─────────────────────────────────
44
+
45
+ def create_access_token(
46
+ self,
47
+ user_id: str,
48
+ username: str,
49
+ role: str,
50
+ tenant_id: str = "default",
51
+ extra_claims: Optional[dict] = None,
52
+ ) -> str:
53
+ """
54
+ Create a JWT access token.
55
+
56
+ Payload includes:
57
+ - sub: user_id
58
+ - username: display name
59
+ - role: admin | analyst | viewer
60
+ - tenant_id: multi-tenant isolation
61
+ - exp: expiration timestamp
62
+ - iat: issued-at timestamp
63
+ """
64
+ now = datetime.now(timezone.utc)
65
+ payload = {
66
+ "sub": user_id,
67
+ "username": username,
68
+ "role": role,
69
+ "tenant_id": tenant_id,
70
+ "exp": now + timedelta(hours=self.expiry_hours),
71
+ "iat": now,
72
+ "type": "access",
73
+ }
74
+
75
+ if extra_claims:
76
+ payload.update(extra_claims)
77
+
78
+ token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
79
+ logger.info("token_created", user_id=user_id, role=role, tenant_id=tenant_id)
80
+ return token
81
+
82
+ def verify_token(self, token: str) -> dict:
83
+ """
84
+ Verify and decode a JWT token.
85
+ Raises JWTError if invalid or expired.
86
+ """
87
+ try:
88
+ payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
89
+ return payload
90
+ except JWTError as e:
91
+ logger.warning("token_verification_failed", error=str(e))
92
+ raise
93
+
94
+ def create_api_key_token(self, key_name: str, tenant_id: str, role: str = "analyst") -> str:
95
+ """
96
+ Create a long-lived API key token (90 days).
97
+ Used for programmatic access.
98
+ """
99
+ now = datetime.now(timezone.utc)
100
+ payload = {
101
+ "sub": f"apikey:{key_name}",
102
+ "username": key_name,
103
+ "role": role,
104
+ "tenant_id": tenant_id,
105
+ "exp": now + timedelta(days=90),
106
+ "iat": now,
107
+ "type": "api_key",
108
+ }
109
+ return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
backend/app/auth/rbac.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Role-Based Access Control (RBAC) β€” Permission enforcement for API endpoints.
3
+ Three roles: admin, analyst, viewer with hierarchical permissions.
4
+ """
5
+
6
+ from enum import Enum
7
+ from fastapi import HTTPException, status
8
+ import structlog
9
+
10
+ logger = structlog.get_logger()
11
+
12
+
13
+ class Role(str, Enum):
14
+ """User roles with increasing privilege levels."""
15
+ VIEWER = "viewer" # Can view data only
16
+ ANALYST = "analyst" # Can execute queries and view analytics
17
+ ADMIN = "admin" # Full access including user management
18
+
19
+
20
+ class Permission(str, Enum):
21
+ """Granular permissions mapped to roles."""
22
+ READ = "read" # View query results
23
+ EXECUTE = "execute" # Execute SQL queries
24
+ VIEW_ANALYTICS = "view_analytics" # View usage analytics
25
+ MANAGE_SCHEMA = "manage_schema" # Refresh schema index
26
+ MANAGE_USERS = "manage_users" # Create/delete users
27
+ MANAGE_API_KEYS = "manage_api_keys" # Create API keys
28
+ VIEW_LOGS = "view_logs" # View system logs
29
+
30
+
31
+ # Role β†’ Permission mapping
32
+ ROLE_PERMISSIONS: dict[Role, set[Permission]] = {
33
+ Role.VIEWER: {
34
+ Permission.READ,
35
+ },
36
+ Role.ANALYST: {
37
+ Permission.READ,
38
+ Permission.EXECUTE,
39
+ Permission.VIEW_ANALYTICS,
40
+ },
41
+ Role.ADMIN: {
42
+ Permission.READ,
43
+ Permission.EXECUTE,
44
+ Permission.VIEW_ANALYTICS,
45
+ Permission.MANAGE_SCHEMA,
46
+ Permission.MANAGE_USERS,
47
+ Permission.MANAGE_API_KEYS,
48
+ Permission.VIEW_LOGS,
49
+ },
50
+ }
51
+
52
+
53
+ def check_permission(user_role: str, required_permission: Permission) -> bool:
54
+ """Check if a role has a specific permission."""
55
+ try:
56
+ role = Role(user_role)
57
+ except ValueError:
58
+ return False
59
+ return required_permission in ROLE_PERMISSIONS.get(role, set())
60
+
61
+
62
+ def require_role(minimum_role: Role):
63
+ """
64
+ FastAPI dependency that enforces minimum role level.
65
+ Usage: Depends(require_role(Role.ANALYST))
66
+ """
67
+ role_hierarchy = {Role.VIEWER: 0, Role.ANALYST: 1, Role.ADMIN: 2}
68
+
69
+ def checker(current_user: dict):
70
+ user_role = current_user.get("role", "viewer")
71
+ try:
72
+ user_level = role_hierarchy.get(Role(user_role), -1)
73
+ required_level = role_hierarchy.get(minimum_role, 99)
74
+ except ValueError:
75
+ raise HTTPException(
76
+ status_code=status.HTTP_403_FORBIDDEN,
77
+ detail=f"Invalid role: {user_role}",
78
+ )
79
+
80
+ if user_level < required_level:
81
+ logger.warning(
82
+ "access_denied",
83
+ user_role=user_role,
84
+ required_role=minimum_role.value,
85
+ user=current_user.get("sub"),
86
+ )
87
+ raise HTTPException(
88
+ status_code=status.HTTP_403_FORBIDDEN,
89
+ detail=f"Insufficient permissions. Required: {minimum_role.value}, Current: {user_role}",
90
+ )
91
+ return current_user
92
+
93
+ return checker
backend/app/cache/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Cache module
backend/app/cache/redis_client.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Redis Client β€” Production-grade cache and rate limiting backed by Redis.
3
+ Falls back to in-memory implementations when Redis is unavailable.
4
+ """
5
+
6
+ import json
7
+ import time
8
+ import hashlib
9
+ import structlog
10
+ from typing import Optional
11
+
12
+ logger = structlog.get_logger()
13
+
14
+
15
+ class RedisCache:
16
+ """
17
+ Redis-backed query cache with TTL and tenant isolation.
18
+ Replaces InMemoryQueryCache for multi-worker production deployments.
19
+ """
20
+
21
+ def __init__(self, redis_url: str, ttl_seconds: int = 300):
22
+ self.ttl = ttl_seconds
23
+ self._client = None
24
+ try:
25
+ import redis
26
+ self._client = redis.Redis.from_url(
27
+ redis_url,
28
+ decode_responses=True,
29
+ socket_connect_timeout=5,
30
+ socket_timeout=3,
31
+ retry_on_timeout=True,
32
+ )
33
+ # Verify connection
34
+ self._client.ping()
35
+ logger.info("redis_cache_connected", url=redis_url.split("@")[-1])
36
+ except Exception as e:
37
+ logger.warning("redis_cache_unavailable", error=str(e))
38
+ self._client = None
39
+
40
+ @property
41
+ def available(self) -> bool:
42
+ return self._client is not None
43
+
44
+ @staticmethod
45
+ def _make_key(query: str, tenant_id: str = "default") -> str:
46
+ raw = f"{tenant_id}:{query.strip().lower()}"
47
+ return f"plainsql:cache:{hashlib.sha256(raw.encode()).hexdigest()[:16]}"
48
+
49
+ def get(self, query: str, tenant_id: str = "default") -> Optional[dict]:
50
+ """Retrieve cached query result."""
51
+ if not self._client:
52
+ return None
53
+ try:
54
+ key = self._make_key(query, tenant_id)
55
+ data = self._client.get(key)
56
+ if data:
57
+ logger.debug("cache_hit", key=key[:20])
58
+ return json.loads(data)
59
+ except Exception as e:
60
+ logger.warning("redis_get_failed", error=str(e))
61
+ return None
62
+
63
+ def set(self, query: str, data: dict, tenant_id: str = "default"):
64
+ """Cache a query result with TTL."""
65
+ if not self._client:
66
+ return
67
+ try:
68
+ key = self._make_key(query, tenant_id)
69
+ self._client.setex(key, self.ttl, json.dumps(data, default=str))
70
+ except Exception as e:
71
+ logger.warning("redis_set_failed", error=str(e))
72
+
73
+ def invalidate(self, tenant_id: str = "default"):
74
+ """Clear all cache entries.
75
+ Note: Since cache keys are SHA-256 hashes of '{tenant_id}:{query}',
76
+ we cannot filter by tenant from the key alone. This purges all entries.
77
+ For tenant-isolated purge, store tenant_id in the value and scan.
78
+ """
79
+ if not self._client:
80
+ return
81
+ try:
82
+ pattern = "plainsql:cache:*"
83
+ cursor = 0
84
+ while True:
85
+ cursor, keys = self._client.scan(cursor, match=pattern, count=100)
86
+ if keys:
87
+ self._client.delete(*keys)
88
+ if cursor == 0:
89
+ break
90
+ except Exception as e:
91
+ logger.warning("redis_invalidate_failed", error=str(e))
92
+
93
+ def invalidate_all(self):
94
+ """Clear all cached queries."""
95
+ if not self._client:
96
+ return
97
+ try:
98
+ pattern = "plainsql:cache:*"
99
+ cursor = 0
100
+ while True:
101
+ cursor, keys = self._client.scan(cursor, match=pattern, count=100)
102
+ if keys:
103
+ self._client.delete(*keys)
104
+ if cursor == 0:
105
+ break
106
+ except Exception as e:
107
+ logger.warning("redis_invalidate_all_failed", error=str(e))
108
+
109
+
110
+ class RedisRateLimiter:
111
+ """
112
+ Redis-backed sliding window rate limiter.
113
+ Shared across all Gunicorn workers for accurate rate limiting.
114
+ """
115
+
116
+ def __init__(self, redis_url: str, requests_per_minute: int = 60):
117
+ self.rpm = requests_per_minute
118
+ self._client = None
119
+ self._consecutive_failures = 0
120
+ self._max_failures_before_deny = 3 # Fail closed after this many errors
121
+ try:
122
+ import redis
123
+ self._client = redis.Redis.from_url(
124
+ redis_url,
125
+ decode_responses=True,
126
+ socket_connect_timeout=5,
127
+ socket_timeout=2,
128
+ )
129
+ self._client.ping()
130
+ logger.info("redis_rate_limiter_connected")
131
+ except Exception as e:
132
+ logger.warning("redis_rate_limiter_unavailable", error=str(e))
133
+ self._client = None
134
+
135
+ @property
136
+ def available(self) -> bool:
137
+ return self._client is not None
138
+
139
+ def check(self, key: str) -> bool:
140
+ """Returns True if request is allowed, False if rate limited."""
141
+ if not self._client:
142
+ return True # Fail open only when Redis was never connected
143
+ try:
144
+ redis_key = f"plainsql:ratelimit:{key}"
145
+ now = time.time()
146
+ window_start = now - 60
147
+
148
+ pipe = self._client.pipeline()
149
+ # Remove old entries outside the window
150
+ pipe.zremrangebyscore(redis_key, 0, window_start)
151
+ # Count entries in current window
152
+ pipe.zcard(redis_key)
153
+ # Add current request
154
+ pipe.zadd(redis_key, {str(now): now})
155
+ # Set TTL on the key to auto-cleanup
156
+ pipe.expire(redis_key, 120)
157
+ results = pipe.execute()
158
+
159
+ current_count = results[1]
160
+ self._consecutive_failures = 0 # Reset on success
161
+ return current_count < self.rpm
162
+ except Exception as e:
163
+ self._consecutive_failures += 1
164
+ logger.warning(
165
+ "redis_rate_check_failed",
166
+ error=str(e),
167
+ consecutive_failures=self._consecutive_failures,
168
+ )
169
+ # Fail OPEN after repeated Redis failures to maintain service availability during outages
170
+ if self._consecutive_failures >= self._max_failures_before_deny:
171
+ logger.warning("rate_limiter_fail_open", reason="redis_unavailable_failing_open")
172
+ return True
173
+ return True # Allow during transient errors
174
+
175
+
176
+ def create_cache(redis_url: str = None, ttl_seconds: int = 300):
177
+ """
178
+ Factory: Returns RedisCache if Redis is available, otherwise InMemoryQueryCache.
179
+ """
180
+ if redis_url:
181
+ cache = RedisCache(redis_url, ttl_seconds)
182
+ if cache.available:
183
+ return cache
184
+ # Fallback to in-memory
185
+ from app.api.middleware import QueryCache
186
+ logger.info("using_inmemory_cache_fallback")
187
+ return QueryCache(ttl_seconds=ttl_seconds)
188
+
189
+
190
+ def create_rate_limiter(redis_url: str = None, rpm: int = 60):
191
+ """
192
+ Factory: Returns RedisRateLimiter if Redis is available, otherwise InMemoryRateLimiter.
193
+ """
194
+ if redis_url:
195
+ limiter = RedisRateLimiter(redis_url, rpm)
196
+ if limiter.available:
197
+ return limiter
198
+ # Fallback to in-memory
199
+ from app.api.middleware import InMemoryRateLimiter
200
+ logger.info("using_inmemory_rate_limiter_fallback")
201
+ return InMemoryRateLimiter(requests_per_minute=rpm)
backend/app/cache/semantic_cache.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Semantic Cache β€” Cache query results by embedding similarity.
3
+
4
+ Instead of requiring exact string matches, this cache finds semantically
5
+ similar queries that have already been processed. This means:
6
+ "Show top 5 employees by salary" β†’ cache hit for
7
+ "List the 5 highest paid employees"
8
+
9
+ Uses MiniLM-L6-v2 embeddings with cosine similarity threshold.
10
+ Falls back gracefully when sentence-transformers is unavailable.
11
+ """
12
+
13
+ import time
14
+ import os
15
+ import threading
16
+ import structlog
17
+ from typing import Optional
18
+
19
+ logger = structlog.get_logger()
20
+
21
+
22
+ class SemanticCache:
23
+ """
24
+ Embedding-based query cache with TTL and similarity threshold.
25
+
26
+ Architecture:
27
+ - Encodes queries using MiniLM-L6-v2 (384-dim embeddings)
28
+ - Stores (embedding, result, timestamp) tuples
29
+ - On lookup, computes cosine similarity against all cached embeddings
30
+ - Returns cached result if similarity >= threshold
31
+
32
+ Thread-safe for concurrent FastAPI workers.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ similarity_threshold: float = 0.95,
38
+ ttl_seconds: int = 300,
39
+ max_entries: int = 500,
40
+ ):
41
+ self._threshold = similarity_threshold
42
+ self._ttl = ttl_seconds
43
+ self._max_entries = max_entries
44
+ self._lock = threading.Lock()
45
+
46
+ # Cache entries: list of (embedding, result, timestamp, original_query)
47
+ self._entries: list[tuple] = []
48
+
49
+ # Lazy-load encoder
50
+ self._encoder = None
51
+ self._encoder_loaded = False
52
+
53
+ def _get_encoder(self):
54
+ """Lazy-load the sentence encoder on first use."""
55
+ if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"):
56
+ logger.info("semantic_cache_encoder_disabled_by_env")
57
+ return None
58
+
59
+ if not self._encoder_loaded:
60
+ self._encoder_loaded = True
61
+ try:
62
+ from sentence_transformers import SentenceTransformer
63
+ self._encoder = SentenceTransformer("all-MiniLM-L6-v2")
64
+ logger.info("semantic_cache_encoder_loaded", model="all-MiniLM-L6-v2")
65
+ except ImportError:
66
+ logger.info("semantic_cache_disabled",
67
+ reason="sentence-transformers not installed")
68
+ except Exception as e:
69
+ logger.warning("semantic_cache_encoder_failed", error=str(e))
70
+ return self._encoder
71
+
72
+ @property
73
+ def available(self) -> bool:
74
+ """Check if semantic caching is available."""
75
+ if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"):
76
+ return False
77
+ try:
78
+ import sentence_transformers
79
+ import numpy
80
+ # Reference modules to satisfy unused import checks
81
+ _ = sentence_transformers
82
+ _ = numpy
83
+ return True
84
+ except ImportError:
85
+ return False
86
+
87
+ def get(self, query: str, tenant_id: str = "default") -> Optional[dict]:
88
+ """
89
+ Look up a semantically similar cached result.
90
+
91
+ Returns the cached result dict if found, None otherwise.
92
+ """
93
+ encoder = self._get_encoder()
94
+ if not encoder:
95
+ return None
96
+
97
+ try:
98
+ import numpy as np
99
+
100
+ query_emb = encoder.encode([query])[0]
101
+ now = time.time()
102
+
103
+ with self._lock:
104
+ # Clean expired entries while searching
105
+ valid_entries = []
106
+ best_match = None
107
+ best_score = 0.0
108
+
109
+ for entry in self._entries:
110
+ emb, result, ts, original, tid = entry
111
+
112
+ # Skip expired
113
+ if now - ts > self._ttl:
114
+ continue
115
+
116
+ # Skip different tenant
117
+ if tid != tenant_id:
118
+ valid_entries.append(entry)
119
+ continue
120
+
121
+ valid_entries.append(entry)
122
+
123
+ # Cosine similarity
124
+ score = float(
125
+ np.dot(query_emb, emb)
126
+ / (np.linalg.norm(query_emb) * np.linalg.norm(emb) + 1e-8)
127
+ )
128
+
129
+ if score >= self._threshold and score > best_score:
130
+ best_score = score
131
+ best_match = result
132
+
133
+ # Update entries (removes expired)
134
+ self._entries = valid_entries
135
+
136
+ if best_match:
137
+ logger.info(
138
+ "semantic_cache_hit",
139
+ query=query[:60],
140
+ similarity=round(best_score, 3),
141
+ )
142
+ return best_match
143
+
144
+ except Exception as e:
145
+ logger.warning("semantic_cache_get_failed", error=str(e))
146
+
147
+ return None
148
+
149
+ def set(self, query: str, result: dict, tenant_id: str = "default"):
150
+ """
151
+ Cache a query result with its embedding.
152
+ """
153
+ encoder = self._get_encoder()
154
+ if not encoder:
155
+ return
156
+
157
+ try:
158
+ embedding = encoder.encode([query])[0]
159
+
160
+ with self._lock:
161
+ # Evict oldest if at capacity
162
+ if len(self._entries) >= self._max_entries:
163
+ self._entries = self._entries[-(self._max_entries // 2):]
164
+
165
+ self._entries.append(
166
+ (embedding, result, time.time(), query, tenant_id)
167
+ )
168
+
169
+ logger.debug("semantic_cache_set", query=query[:60])
170
+
171
+ except Exception as e:
172
+ logger.warning("semantic_cache_set_failed", error=str(e))
173
+
174
+ def invalidate(self, tenant_id: str = "default"):
175
+ """Clear all entries for a tenant."""
176
+ with self._lock:
177
+ self._entries = [
178
+ e for e in self._entries if e[4] != tenant_id
179
+ ]
180
+
181
+ def invalidate_all(self):
182
+ """Clear all cache entries."""
183
+ with self._lock:
184
+ self._entries.clear()
185
+
186
+ def stats(self) -> dict:
187
+ """Return cache statistics."""
188
+ with self._lock:
189
+ now = time.time()
190
+ active = sum(1 for e in self._entries if now - e[2] <= self._ttl)
191
+ return {
192
+ "total_entries": len(self._entries),
193
+ "active_entries": active,
194
+ "max_entries": self._max_entries,
195
+ "ttl_seconds": self._ttl,
196
+ "similarity_threshold": self._threshold,
197
+ "encoder_available": self._encoder is not None,
198
+ }
backend/app/config.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PlainSQL Configuration β€” Pydantic Settings with environment-based config.
3
+ All secrets loaded from .env, with sensible defaults for local dev.
4
+ """
5
+
6
+ from pydantic_settings import BaseSettings
7
+ from pydantic import Field, model_validator
8
+ from typing import Optional
9
+ from functools import lru_cache
10
+
11
+ _JWT_DEFAULT = "change-me-in-production-use-openssl-rand-hex-32"
12
+
13
+
14
+ class Settings(BaseSettings):
15
+ """Application settings loaded from environment variables."""
16
+
17
+ # ── App ──────────────────────────────────────────────
18
+ APP_NAME: str = "PlainSQL"
19
+ APP_VERSION: str = "2.0.0"
20
+ DEBUG: bool = False
21
+ ENV: str = Field(default="development", description="development | staging | production")
22
+
23
+ # ── Database ─────────────────────────────────────────
24
+ DB_URI: str = Field(..., description="MySQL connection URI")
25
+ DB_POOL_SIZE: int = 10
26
+ DB_MAX_OVERFLOW: int = 20
27
+ DB_POOL_TIMEOUT: int = 30
28
+ DB_QUERY_TIMEOUT: int = 30
29
+
30
+ # ── Redis ────────────────────────────────────────────
31
+ REDIS_URL: str = Field(default="redis://localhost:6379/0")
32
+ CACHE_TTL_SECONDS: int = 300
33
+
34
+ # ── Authentication ───────────────────────────────────
35
+ JWT_SECRET_KEY: str = Field(default=_JWT_DEFAULT)
36
+ JWT_ALGORITHM: str = "HS256"
37
+ JWT_EXPIRY_HOURS: int = 8
38
+
39
+ # ── LLM Providers ───────────────────────────────────
40
+ HUGGINGFACEHUB_API_TOKEN: Optional[str] = None
41
+ OPENAI_API_KEY: Optional[str] = None
42
+ ANTHROPIC_API_KEY: Optional[str] = None
43
+ GROQ_API_KEY: Optional[str] = None
44
+ GROQ_MODEL_PRIMARY: str = "llama-3.3-70b-versatile"
45
+ GROQ_MODEL_FAST: str = "llama-3.1-8b-instant"
46
+ GROQ_BASE_URL: str = "https://api.groq.com/openai/v1"
47
+ OLLAMA_BASE_URL: str = "http://localhost:11434"
48
+ DEFAULT_LLM_PROVIDER: str = Field(default="groq", description="groq | huggingface | openai | anthropic | ollama")
49
+ DEFAULT_MODEL: str = "Qwen/Qwen2.5-Coder-32B-Instruct"
50
+
51
+ # ── RAG ──────────────────────────────────────────────
52
+ CHROMA_PERSIST_DIR: str = "./chroma_db"
53
+ EMBEDDING_MODEL: str = "all-MiniLM-L6-v2"
54
+ RAG_TOP_K: int = 5
55
+
56
+ # ── Safety ───────────────────────────────────────────
57
+ MAX_QUERY_ROWS: int = 1000
58
+ QUERY_TIMEOUT_SECONDS: int = 30
59
+
60
+ # ── Rate Limiting ────────────────────────────────────
61
+ RATE_LIMIT_RPM: int = 60
62
+
63
+ # ── Observability ────────────────────────────────────
64
+ LANGSMITH_API_KEY: Optional[str] = None
65
+ LANGSMITH_PROJECT: str = "plainsql"
66
+ LOG_LEVEL: str = "INFO"
67
+
68
+ # ── CORS ─────────────────────────────────────────────
69
+ CORS_ORIGINS: list[str] = [
70
+ "http://localhost:3000",
71
+ "http://localhost:5173",
72
+ "http://127.0.0.1:3000",
73
+ "http://127.0.0.1:5173",
74
+ "http://localhost:5500",
75
+ ]
76
+
77
+ model_config = {
78
+ "env_file": [".env", "../.env", "../../.env"],
79
+ "env_file_encoding": "utf-8",
80
+ "case_sensitive": True,
81
+ "extra": "ignore",
82
+ }
83
+
84
+ @model_validator(mode="after")
85
+ def _validate_production_secrets(self) -> "Settings":
86
+ """Prevent deployment with default secrets in production/staging."""
87
+ if self.ENV in ("production", "staging"):
88
+ if self.JWT_SECRET_KEY == _JWT_DEFAULT:
89
+ raise ValueError(
90
+ "FATAL: JWT_SECRET_KEY must be changed from the default value "
91
+ "in production/staging. Generate one with: openssl rand -hex 32"
92
+ )
93
+ if len(self.JWT_SECRET_KEY) < 32:
94
+ raise ValueError(
95
+ "FATAL: JWT_SECRET_KEY must be at least 32 characters for production."
96
+ )
97
+ return self
98
+
99
+
100
+ @lru_cache()
101
+ def get_settings() -> Settings:
102
+ """Cached settings singleton."""
103
+ return Settings()
backend/app/db/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # DB Package
backend/app/db/connection.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database Connection Pool β€” Production-grade pooled connections via SQLAlchemy engine.
3
+ Supports multi-tenant databases via tenant_id-based connection routing.
4
+ """
5
+
6
+ import time
7
+ import re
8
+ from sqlalchemy import create_engine, text, event
9
+ from sqlalchemy.pool import QueuePool
10
+ from urllib.parse import urlparse, unquote
11
+ from typing import Optional
12
+ from contextlib import contextmanager
13
+ import structlog
14
+
15
+ logger = structlog.get_logger()
16
+
17
+ # Only allow alphanumeric + underscore in identifiers
18
+ _SAFE_IDENTIFIER = re.compile(r'^[a-zA-Z0-9_]+$')
19
+
20
+ def _validate_identifier(name: str, label: str = "identifier"):
21
+ """Validate that a SQL identifier contains only safe characters."""
22
+ if not _SAFE_IDENTIFIER.match(name):
23
+ raise ValueError(f"Invalid {label}: {name!r}")
24
+
25
+
26
+ class DatabasePool:
27
+ """
28
+ Production database connection pool.
29
+ Uses SQLAlchemy QueuePool for connection reuse, health checks, and overflow management.
30
+ Falls back to raw pymysql for schema introspection when needed.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ db_uri: str,
36
+ query_timeout: int = 30,
37
+ pool_size: int = 10,
38
+ max_overflow: int = 20,
39
+ pool_timeout: int = 30,
40
+ ):
41
+ parsed = urlparse(db_uri)
42
+ self.host = parsed.hostname
43
+ self.port = parsed.port or 3306
44
+ self.user = parsed.username
45
+ self.password = unquote(parsed.password) if parsed.password else ""
46
+ self.db_name = parsed.path[1:] if parsed.path else "chatbot"
47
+ self.query_timeout = query_timeout
48
+
49
+ # ── Build SQLAlchemy engine with connection pool ──
50
+ # Construct a clean pymysql URI (no SQLAlchemy dialect prefix issues)
51
+ safe_password = self.password.replace("@", "%40")
52
+ engine_uri = f"mysql+pymysql://{self.user}:{safe_password}@{self.host}:{self.port}/{self.db_name}"
53
+
54
+ connect_kwargs = {
55
+ "connect_timeout": 10,
56
+ "read_timeout": query_timeout,
57
+ "write_timeout": query_timeout,
58
+ }
59
+ # TiDB Cloud requires SSL
60
+ if self.host and "tidbcloud.com" in self.host:
61
+ import ssl
62
+ ssl_ctx = ssl.create_default_context()
63
+ connect_kwargs["ssl"] = ssl_ctx
64
+
65
+ self._engine = create_engine(
66
+ engine_uri,
67
+ poolclass=QueuePool,
68
+ pool_size=pool_size,
69
+ max_overflow=max_overflow,
70
+ pool_timeout=pool_timeout,
71
+ pool_pre_ping=True, # Verify connections before checkout (stale conn defense)
72
+ pool_recycle=1800, # Recycle connections every 30 min (MySQL wait_timeout defense)
73
+ connect_args=connect_kwargs,
74
+ )
75
+
76
+ # ── Set session to READ ONLY for query connections ──
77
+ @event.listens_for(self._engine, "checkout")
78
+ def _set_read_only(dbapi_conn, connection_record, connection_proxy):
79
+ """Set session to read-only on checkout for defense-in-depth."""
80
+ pass # MySQL read-only requires SUPER privilege; rely on SQL validation instead
81
+
82
+ # ── In-Memory Schema Cache ──
83
+ self._tables = None
84
+ self._table_schemas = {}
85
+ self._foreign_keys = {}
86
+
87
+ self._prepopulate_cache_from_file()
88
+
89
+ self._validate_connection()
90
+
91
+ def _prepopulate_cache_from_file(self):
92
+ """Pre-populate the schema cache from enriched_schema.json if it exists."""
93
+ import os
94
+ import json
95
+ schema_file = "./chroma_db/enriched_schema.json"
96
+ if os.path.exists(schema_file):
97
+ try:
98
+ with open(schema_file, "r", encoding="utf-8") as f:
99
+ enriched_tables = json.load(f)
100
+ tables = []
101
+ for item in enriched_tables:
102
+ table_name = item.get("table_name")
103
+ if not table_name:
104
+ continue
105
+ tables.append(table_name)
106
+ if "raw_columns" in item:
107
+ self._table_schemas[table_name] = item["raw_columns"]
108
+ if "raw_fks" in item:
109
+ self._foreign_keys[table_name] = item["raw_fks"]
110
+ if tables:
111
+ self._tables = tables
112
+ logger.info("prepopulated_database_schema_cache_from_file", tables=len(tables))
113
+ except Exception as e:
114
+ logger.warning("failed_to_prepopulate_schema_cache", error=str(e))
115
+
116
+ def _validate_connection(self):
117
+ """Validate database connectivity on startup."""
118
+ try:
119
+ with self._engine.connect() as conn:
120
+ conn.execute(text("SELECT 1"))
121
+ logger.info("database_connected", host=self.host, database=self.db_name,
122
+ pool_size=self._engine.pool.size())
123
+ except Exception as e:
124
+ logger.error("database_connection_failed", error=str(e))
125
+ raise
126
+
127
+ @contextmanager
128
+ def get_connection(self):
129
+ """Context manager for pooled database connections."""
130
+ conn = self._engine.connect()
131
+ try:
132
+ yield conn
133
+ finally:
134
+ conn.close()
135
+
136
+ def execute_query(self, query: str, params: Optional[dict] = None) -> list[dict]:
137
+ """Execute a read-only query and return results as list of dicts."""
138
+ start_time = time.perf_counter()
139
+ try:
140
+ with self._engine.connect() as conn:
141
+ # Enforce statement-level timeout (milliseconds) to prevent
142
+ # runaway queries from blocking the thread pool forever.
143
+ # The socket read_timeout only handles network stalls, not slow SQL.
144
+ timeout_ms = self.query_timeout * 1000
145
+ try:
146
+ conn.execute(text(f"SET SESSION max_execution_time = {timeout_ms}"))
147
+ except Exception:
148
+ pass # Non-critical β€” older MySQL versions may not support this
149
+
150
+ if params:
151
+ result = conn.execute(text(query), params)
152
+ else:
153
+ result = conn.execute(text(query))
154
+ columns = result.keys()
155
+ rows = [dict(zip(columns, row)) for row in result.fetchall()]
156
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
157
+ logger.info("db_query_executed", query=query[:200], elapsed_ms=elapsed_ms, row_count=len(rows))
158
+ return rows
159
+ except Exception as e:
160
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
161
+ logger.error("db_query_failed", query=query[:200], elapsed_ms=elapsed_ms, error=str(e))
162
+ raise
163
+
164
+ def _execute_write_internal(self, query: str, params: Optional[tuple] = None):
165
+ """
166
+ Execute a write query. INTERNAL USE ONLY β€” for schema setup and migrations.
167
+ User-facing queries MUST go through execute_query after SQL validation.
168
+ """
169
+ start_time = time.perf_counter()
170
+ try:
171
+ with self._engine.begin() as conn:
172
+ if params:
173
+ # Build named params dict matching :p0, :p1, :p2... placeholders
174
+ param_dict = {f"p{i}": v for i, v in enumerate(params)}
175
+ conn.execute(text(query), param_dict)
176
+ else:
177
+ conn.execute(text(query))
178
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
179
+ logger.info("db_write_executed", query=query[:200], elapsed_ms=elapsed_ms)
180
+ except Exception as e:
181
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
182
+ logger.error("db_write_failed", query=query[:200], elapsed_ms=elapsed_ms, error=str(e))
183
+ raise
184
+
185
+ def get_tables(self) -> list[str]:
186
+ """Returns all table names in the current database."""
187
+ if self._tables is None:
188
+ rows = self.execute_query("SHOW TABLES")
189
+ self._tables = [list(row.values())[0] for row in rows]
190
+ return self._tables
191
+
192
+ def get_table_schema(self, table_name: str) -> list[dict]:
193
+ """Returns column details for a specific table."""
194
+ if table_name not in self._table_schemas:
195
+ _validate_identifier(table_name, "table_name")
196
+ rows = self.execute_query(f"DESCRIBE `{table_name}`")
197
+ self._table_schemas[table_name] = [
198
+ {
199
+ "name": row["Field"],
200
+ "type": row["Type"],
201
+ "null": row["Null"],
202
+ "key": row["Key"],
203
+ "default": row["Default"],
204
+ }
205
+ for row in rows
206
+ ]
207
+ return self._table_schemas[table_name]
208
+
209
+ def get_foreign_keys(self, table_name: str) -> list[dict]:
210
+ """Returns foreign key relationships for a table."""
211
+ if table_name not in self._foreign_keys:
212
+ query = """
213
+ SELECT
214
+ COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
215
+ FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
216
+ WHERE TABLE_SCHEMA = :schema_name
217
+ AND TABLE_NAME = :table_name
218
+ AND REFERENCED_TABLE_NAME IS NOT NULL
219
+ """
220
+ self._foreign_keys[table_name] = self.execute_query(query, {"schema_name": self.db_name, "table_name": table_name})
221
+ return self._foreign_keys[table_name]
222
+
223
+ def clear_schema_cache(self):
224
+ """Clears all schema caching to allow schema refreshes."""
225
+ self._tables = None
226
+ self._table_schemas.clear()
227
+ self._foreign_keys.clear()
228
+ logger.info("database_schema_cache_cleared")
229
+
230
+ def get_sample_values(self, table_name: str, column_name: str, limit: int = 5) -> list:
231
+ """Returns sample distinct values for a column."""
232
+ _validate_identifier(table_name, "table_name")
233
+ _validate_identifier(column_name, "column_name")
234
+ try:
235
+ query = f"SELECT DISTINCT `{column_name}` FROM `{table_name}` LIMIT :lim"
236
+ rows = self.execute_query(query, {"lim": limit})
237
+ return [list(r.values())[0] for r in rows]
238
+ except Exception:
239
+ return []
240
+
241
+ def get_row_count(self, table_name: str) -> int:
242
+ """Returns approximate row count for a table."""
243
+ try:
244
+ rows = self.execute_query(f"SELECT COUNT(*) as cnt FROM `{table_name}`")
245
+ return rows[0]["cnt"] if rows else 0
246
+ except Exception:
247
+ return 0
248
+
249
+ def get_full_schema(self) -> str:
250
+ """Generates a complete text representation of the database schema."""
251
+ tables = self.get_tables()
252
+ schema_text = ""
253
+
254
+ for table in tables:
255
+ columns = self.get_table_schema(table)
256
+ schema_text += f"Table: {table}\nColumns:\n"
257
+ for col in columns:
258
+ schema_text += f" - {col['name']} ({col['type']})"
259
+ if col['key'] == 'PRI':
260
+ schema_text += " [PRIMARY KEY]"
261
+ if col['key'] == 'MUL':
262
+ schema_text += " [FOREIGN KEY]"
263
+ schema_text += "\n"
264
+
265
+ # Add foreign key relationships
266
+ fks = self.get_foreign_keys(table)
267
+ if fks:
268
+ schema_text += "Relationships:\n"
269
+ for fk in fks:
270
+ schema_text += f" - {fk['COLUMN_NAME']} β†’ {fk['REFERENCED_TABLE_NAME']}.{fk['REFERENCED_COLUMN_NAME']}\n"
271
+ schema_text += "\n"
272
+
273
+ return schema_text
274
+
275
+ def get_pool_status(self) -> dict:
276
+ """Returns current connection pool statistics."""
277
+ pool = self._engine.pool
278
+ return {
279
+ "pool_size": pool.size(),
280
+ "checked_out": pool.checkedout(),
281
+ "overflow": pool.overflow(),
282
+ "checked_in": pool.checkedin(),
283
+ }
284
+
285
+
286
+ class TenantRegistry:
287
+ """
288
+ Multi-tenant database connection registry.
289
+ Maps tenant_id β†’ DatabasePool for isolated data access.
290
+
291
+ NOTE: Currently scaffolding β€” not used in production.
292
+ The system operates as single-tenant with tenant_id used only for
293
+ cache isolation. For true multi-tenancy, instantiate this registry
294
+ in main.py and pass tenant-specific pools to the orchestrator.
295
+ """
296
+
297
+ def __init__(self):
298
+ self._pools: dict[str, DatabasePool] = {}
299
+
300
+ def register(self, tenant_id: str, db_uri: str, query_timeout: int = 30):
301
+ """Register a new tenant database."""
302
+ self._pools[tenant_id] = DatabasePool(db_uri, query_timeout)
303
+ logger.info("tenant_registered", tenant_id=tenant_id)
304
+
305
+ def get_pool(self, tenant_id: str) -> DatabasePool:
306
+ """Get the database pool for a tenant."""
307
+ pool = self._pools.get(tenant_id)
308
+ if not pool:
309
+ raise ValueError(f"No database registered for tenant: {tenant_id}")
310
+ return pool
311
+
312
+ def list_tenants(self) -> list[str]:
313
+ """List all registered tenant IDs."""
314
+ return list(self._pools.keys())
backend/app/db/persistence.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation Persistence β€” MySQL-backed chat history management.
3
+
4
+ Provides CRUD operations for conversations and messages, enabling
5
+ cross-device chat persistence and server-side state management.
6
+ """
7
+
8
+ import uuid
9
+ from typing import Optional
10
+ import structlog
11
+
12
+ logger = structlog.get_logger()
13
+
14
+ # ── Schema Migration ─────────────────────────────────────────
15
+
16
+ CONVERSATIONS_DDL = """
17
+ CREATE TABLE IF NOT EXISTS conversations (
18
+ id VARCHAR(36) PRIMARY KEY,
19
+ user_id VARCHAR(64) NOT NULL DEFAULT 'anonymous',
20
+ title VARCHAR(255) NOT NULL DEFAULT 'New analysis',
21
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
22
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
23
+ INDEX idx_user (user_id),
24
+ INDEX idx_updated (updated_at DESC)
25
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
26
+ """
27
+
28
+ MESSAGES_DDL = """
29
+ CREATE TABLE IF NOT EXISTS messages (
30
+ id VARCHAR(36) PRIMARY KEY,
31
+ conversation_id VARCHAR(36) NOT NULL,
32
+ role ENUM('user', 'assistant') NOT NULL,
33
+ content TEXT,
34
+ generated_sql TEXT,
35
+ explanation TEXT,
36
+ friendly_message TEXT,
37
+ intent VARCHAR(32),
38
+ execution_time_ms FLOAT DEFAULT 0,
39
+ row_count INT DEFAULT 0,
40
+ result_data JSON,
41
+ feedback ENUM('up', 'down') DEFAULT NULL,
42
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
43
+ INDEX idx_conversation (conversation_id),
44
+ INDEX idx_created (created_at),
45
+ FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE
46
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
47
+ """
48
+
49
+
50
+ def ensure_tables(db_pool) -> bool:
51
+ """Auto-create conversations and messages tables on startup."""
52
+ try:
53
+ db_pool._execute_write_internal(CONVERSATIONS_DDL)
54
+ db_pool._execute_write_internal(MESSAGES_DDL)
55
+ logger.info("persistence_tables_ready")
56
+ return True
57
+ except Exception as e:
58
+ logger.warning("persistence_migration_failed", error=str(e))
59
+ return False
60
+
61
+
62
+ # ── Conversation Manager ─────────────────────────────────────
63
+
64
+ class ConversationManager:
65
+ """
66
+ Server-side conversation and message persistence.
67
+ Replaces localStorage-based chat history with MySQL storage.
68
+ """
69
+
70
+ def __init__(self, db_pool):
71
+ self.db_pool = db_pool
72
+
73
+ # ── Conversations ────────────────────────────────────
74
+
75
+ def list_conversations(self, user_id: str = "anonymous", limit: int = 50) -> list[dict]:
76
+ """List conversations for a user, most recent first."""
77
+ rows = self.db_pool.execute_query(
78
+ """SELECT c.id, c.title, c.created_at, c.updated_at,
79
+ COUNT(m.id) as message_count
80
+ FROM conversations c
81
+ LEFT JOIN messages m ON m.conversation_id = c.id
82
+ WHERE c.user_id = :user_id
83
+ GROUP BY c.id
84
+ ORDER BY c.updated_at DESC
85
+ LIMIT :lim""",
86
+ {"user_id": user_id, "lim": limit},
87
+ )
88
+ return [
89
+ {
90
+ "id": r["id"],
91
+ "title": r["title"],
92
+ "message_count": r["message_count"],
93
+ "created_at": str(r["created_at"]),
94
+ "updated_at": str(r["updated_at"]),
95
+ }
96
+ for r in rows
97
+ ]
98
+
99
+ def create_conversation(self, title: str = "New analysis", user_id: str = "anonymous") -> dict:
100
+ """Create a new conversation and return its metadata."""
101
+ conv_id = str(uuid.uuid4())[:36]
102
+ self.db_pool._execute_write_internal(
103
+ "INSERT INTO conversations (id, user_id, title) VALUES (:p0, :p1, :p2)",
104
+ (conv_id, user_id, title[:255]),
105
+ )
106
+ logger.info("conversation_created", conversation_id=conv_id)
107
+ return {"id": conv_id, "title": title, "message_count": 0}
108
+
109
+ def update_title(self, conversation_id: str, title: str):
110
+ """Update a conversation's title."""
111
+ self.db_pool._execute_write_internal(
112
+ "UPDATE conversations SET title = :p0 WHERE id = :p1",
113
+ (title[:255], conversation_id),
114
+ )
115
+
116
+ def delete_conversation(self, conversation_id: str, user_id: str = "anonymous"):
117
+ """Delete a conversation and all its messages (cascade)."""
118
+ self.db_pool._execute_write_internal(
119
+ "DELETE FROM conversations WHERE id = :p0 AND user_id = :p1",
120
+ (conversation_id, user_id),
121
+ )
122
+ logger.info("conversation_deleted", conversation_id=conversation_id)
123
+
124
+ # ── Messages ─────────────────────────────────────────
125
+
126
+ def get_messages(self, conversation_id: str, limit: int = 200) -> list[dict]:
127
+ """Get all messages in a conversation, oldest first."""
128
+ rows = self.db_pool.execute_query(
129
+ """SELECT id, role, content, generated_sql, explanation,
130
+ friendly_message, intent, execution_time_ms,
131
+ row_count, result_data, feedback, created_at
132
+ FROM messages
133
+ WHERE conversation_id = :conv_id
134
+ ORDER BY created_at ASC
135
+ LIMIT :lim""",
136
+ {"conv_id": conversation_id, "lim": limit},
137
+ )
138
+ results = []
139
+ for r in rows:
140
+ msg = {
141
+ "id": r["id"],
142
+ "role": r["role"],
143
+ "content": r["content"] or "",
144
+ "created_at": str(r["created_at"]),
145
+ }
146
+ if r["role"] == "assistant":
147
+ msg["data"] = {
148
+ "sql": r["generated_sql"] or "",
149
+ "explanation": r["explanation"] or "",
150
+ "message": r["friendly_message"] or "",
151
+ "intent": r["intent"] or "",
152
+ "execution_time_ms": r["execution_time_ms"] or 0,
153
+ "row_count": r["row_count"] or 0,
154
+ }
155
+ # Parse stored JSON result data
156
+ if r["result_data"]:
157
+ try:
158
+ import json
159
+ msg["data"]["answer"] = json.loads(r["result_data"]) if isinstance(r["result_data"], str) else r["result_data"]
160
+ except (json.JSONDecodeError, TypeError):
161
+ msg["data"]["answer"] = []
162
+ msg["_feedback"] = r["feedback"]
163
+ results.append(msg)
164
+ return results
165
+
166
+ def save_user_message(self, conversation_id: str, content: str) -> str:
167
+ """Save a user message and return its ID."""
168
+ msg_id = str(uuid.uuid4())[:36]
169
+ self.db_pool._execute_write_internal(
170
+ """INSERT INTO messages (id, conversation_id, role, content)
171
+ VALUES (:p0, :p1, :p2, :p3)""",
172
+ (msg_id, conversation_id, "user", content),
173
+ )
174
+ return msg_id
175
+
176
+ def save_assistant_message(
177
+ self,
178
+ conversation_id: str,
179
+ content: str,
180
+ generated_sql: str = "",
181
+ explanation: str = "",
182
+ friendly_message: str = "",
183
+ intent: str = "",
184
+ execution_time_ms: float = 0,
185
+ row_count: int = 0,
186
+ result_data: Optional[list] = None,
187
+ ) -> str:
188
+ """Save an assistant response and return its ID."""
189
+ import json
190
+ msg_id = str(uuid.uuid4())[:36]
191
+ result_json = json.dumps(result_data[:100] if result_data else [], default=str)
192
+ self.db_pool._execute_write_internal(
193
+ """INSERT INTO messages
194
+ (id, conversation_id, role, content, generated_sql, explanation,
195
+ friendly_message, intent, execution_time_ms, row_count, result_data)
196
+ VALUES (:p0, :p1, :p2, :p3, :p4, :p5, :p6, :p7, :p8, :p9, :p10)""",
197
+ (
198
+ msg_id, conversation_id, "assistant", content,
199
+ generated_sql, explanation, friendly_message,
200
+ intent, execution_time_ms, row_count, result_json,
201
+ ),
202
+ )
203
+ return msg_id
204
+
205
+ def update_feedback(self, message_id: str, rating: str):
206
+ """Update feedback rating on a message."""
207
+ self.db_pool._execute_write_internal(
208
+ "UPDATE messages SET feedback = :p0 WHERE id = :p1",
209
+ (rating, message_id),
210
+ )
211
+
212
+ def get_conversation_context(self, conversation_id: str, limit: int = 6) -> list[dict]:
213
+ """Get recent user/sql pairs for conversation context (used by SQL generation)."""
214
+ rows = self.db_pool.execute_query(
215
+ """SELECT role, content, generated_sql
216
+ FROM messages
217
+ WHERE conversation_id = :conv_id
218
+ ORDER BY created_at DESC
219
+ LIMIT :lim""",
220
+ {"conv_id": conversation_id, "lim": limit * 2},
221
+ )
222
+ context = []
223
+ for r in reversed(rows):
224
+ if r["role"] == "user":
225
+ context.append({"user": r["content"]})
226
+ elif r["role"] == "assistant" and r["generated_sql"] and context:
227
+ context[-1]["sql"] = r["generated_sql"]
228
+ return context[-limit:]