Spaces:
Runtime error
Runtime error
Commit Β·
6086e71
1
Parent(s): b94d1f8
feat: synchronize text-to-sql-bot codebase with Hugging Face Space repository, including Docker build configurations
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
Files changed (50)
- .env.exampleAdded+56
- .gitattributes-1
- .gitignoreAdded+49
- DockerfileAdded+38
- backend/alembic.iniAdded+37
- backend/alembic/env.pyAdded+73
- backend/alembic/script.py.makoAdded+24
- backend/alembic/versions/001_initial_plainsql_tables.pyAdded+54
- backend/app/__init__.pyAdded+2
- backend/app/agents/__init__.pyAdded+1
- backend/app/agents/execution.pyAdded+140
- backend/app/agents/guardrails.pyAdded+264
- backend/app/agents/intent_classifier.pyAdded+314
- backend/app/agents/ml_classifier.pyAdded+144
- backend/app/agents/models/__init__.pyAdded+1
- backend/app/agents/models/intent_model.joblibAdded
- backend/app/agents/models/train_classifier.pyAdded+130
- backend/app/agents/models/training_data.jsonAdded+173
- backend/app/agents/orchestrator.pyAdded+856
- backend/app/agents/query_understanding.pyAdded+276
- backend/app/agents/result_summary.pyAdded+326
- backend/app/agents/schema_retrieval.pyAdded+220
- backend/app/agents/sql_generation.pyAdded+159
- backend/app/agents/sql_validation.pyAdded+198
- backend/app/agents/state.pyAdded+73
- backend/app/agents/visualization.pyAdded+222
- backend/app/ai_features/__init__.pyAdded+1
- backend/app/ai_features/anomaly.pyAdded+105
- backend/app/ai_features/explainer.pyAdded+29
- backend/app/ai_features/insights.pyAdded+135
- backend/app/api/__init__.pyAdded+1
- backend/app/api/fast_path.pyAdded+55
- backend/app/api/middleware.pyAdded+175
- backend/app/api/routes/__init__.pyAdded+1
- backend/app/api/routes/admin.pyAdded+116
- backend/app/api/routes/chat.pyAdded+156
- backend/app/api/routes/conversations.pyAdded+83
- backend/app/api/routes/monitoring.pyAdded+70
- backend/app/api/routes/system.pyAdded+193
- backend/app/api/schemas.pyAdded+135
- backend/app/auth/__init__.pyAdded+1
- backend/app/auth/jwt_auth.pyAdded+109
- backend/app/auth/rbac.pyAdded+93
- backend/app/cache/__init__.pyAdded+1
- backend/app/cache/redis_client.pyAdded+201
- backend/app/cache/semantic_cache.pyAdded+198
- backend/app/config.pyAdded+103
- backend/app/db/__init__.pyAdded+1
- backend/app/db/connection.pyAdded+314
- backend/app/db/persistence.pyAdded+228
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PlainSQL Enterprise β Environment Configuration# Copy this file to .env and fill in your values# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ββ App Settings βββββββββββββββββββββββββββββββββββββββββAPP_NAME=PlainSQLENV=developmentDEBUG=trueLOG_LEVEL=INFO
# ββ Database βββββββββββββββββββββββββββββββββββββββββββββDB_URI=mysql+pymysql://root:YOUR_PASSWORD@localhost:3306/chatbotDB_POOL_SIZE=10DB_QUERY_TIMEOUT=30
# ββ Redis (optional β falls back to in-memory) ββββββββββREDIS_URL=redis://localhost:6379/0CACHE_TTL_SECONDS=300
# ββ Authentication βββββββββββββββββββββββββββββββββββββββ# Generate with: openssl rand -hex 32JWT_SECRET_KEY=change-me-in-production-use-openssl-rand-hex-32JWT_EXPIRY_HOURS=8
# ββ LLM Providers (at least one required) βββββββββββββββHUGGINGFACEHUB_API_TOKEN=your_hf_token_hereDEFAULT_LLM_PROVIDER=huggingfaceDEFAULT_MODEL=Qwen/Qwen2.5-Coder-32B-Instruct
# OpenAI (optional)# OPENAI_API_KEY=sk-your-key-here
# Anthropic (optional)# ANTHROPIC_API_KEY=sk-ant-your-key-here
# Ollama local (optional)# OLLAMA_BASE_URL=http://localhost:11434
# ββ RAG Settings βββββββββββββββββββββββββββββββββββββββββCHROMA_PERSIST_DIR=./chroma_dbRAG_TOP_K=5
# ββ Safety Limits ββββββββββββββββββββββββββββββββββββββββMAX_QUERY_ROWS=1000QUERY_TIMEOUT_SECONDS=30
# ββ Rate Limiting ββββββββββββββββββββββββββββββββββββββββRATE_LIMIT_RPM=60
# ββ Observability (optional) ββββββββββββββββββββββββββββ# LANGSMITH_API_KEY=your_langsmith_key# LANGSMITH_PROJECT=plainsql
# ββ CORS βββββββββββββββββββββββββββββββββββββββββββββββββCORS_ORIGINS=["http://localhost:3000","http://127.0.0.1:5500"]5 unmodified lines67891011125 unmodified lines*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text5 unmodified lines678910115 unmodified lines*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# ββ Python βββββββββββββββββββββββββββββββββββββββββββββββ__pycache__/*.py[cod]*.pyo*.egg-info/dist/build/*.egg
# ββ Virtual Environments βββββββββββββββββββββββββββββββββ.venv/venv/env/
# ββ Environment / Secrets ββββββββββββββββββββββββββββββββ.env.env.local.env.production
# ββ ChromaDB βββββββββββββββββββββββββββββββββββββββββββββchroma_db/
# ββ IDE ββββββββββββββββββββββββββββββββββββββββββββββββββ.vscode/.idea/*.swp*.swo
# ββ OS βββββββββββββββββββββββββββββββββββββββββββββββββββ.DS_StoreThumbs.db
# ββ Testing ββββββββββββββββββββββββββββββββββββββββββββββ.pytest_cache/htmlcov/.coverage
# ββ AI Assistants ββββββββββββββββββββββββββββββββββββββββ.zencoder/.zenflow/.gemini/
# ββ Node (frontend) βββββββββββββββββββββββββββββββββββββnode_modules/.next/out/
# ββ Evaluation Results ββββββββββββββββββββββββββββββββββevaluation_results.json1234567891011121314151617181920212223242526272829303132333435363738# ββ Docker Multi-Stage Build βββββββββββββββββββββββββββββ# Stage 1: DependenciesFROM python:3.11-slim AS deps
WORKDIR /appCOPY backend/requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Stage 2: ApplicationFROM python:3.11-slim AS runtime
WORKDIR /app
# Copy installed packages from deps stageCOPY --from=deps /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packagesCOPY --from=deps /usr/local/bin /usr/local/bin
# Copy application codeCOPY backend/ .COPY frontend/ /frontend/COPY .env.example .env.example
# Create non-root userRUN useradd -m -r plainsql && \ chown -R plainsql:plainsql /app && \ mkdir -p /app/chroma_db && \ chown -R plainsql:plainsql /app/chroma_db
USER plainsql
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \ CMD python -c "import requests; requests.get('http://localhost:8000/api/v1/health')" || exit 1
EXPOSE 8000
# Single worker avoids concurrent ChromaDB migrations in the local container volume.CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--access-log"]12345678910111213141516171819202122232425262728293031323334353637[alembic]script_location = alembicsqlalchemy.url = mysql+pymysql://root:password@localhost:3306/chatbotfile_template = %%(year)d_%%(month).2d_%%(day).2d_%%(rev)s_%%(slug)s
[loggers]keys = root,sqlalchemy,alembic
[handlers]keys = console
[formatters]keys = generic
[logger_root]level = WARNhandlers = console
[logger_sqlalchemy]level = WARNhandlers =qualname = sqlalchemy.engine
[logger_alembic]level = INFOhandlers =qualname = alembic
[handler_console]class = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = generic
[formatter_generic]format = %(levelname)-5.5s [%(name)s] %(message)sdatefmt = %H:%M:%S12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Alembic Environment β Configures database migrations.Reads DB URI from app.config to stay in sync with the application."""
import osimport sysfrom logging.config import fileConfig
from sqlalchemy import engine_from_config, poolfrom alembic import context
# Add backend to path so we can import app modulessys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Alembic Config objectconfig = context.config
# Setup logging from alembic.iniif config.config_file_name is not None: fileConfig(config.config_file_name)
# Override sqlalchemy.url from environment / app configtry: from dotenv import load_dotenv load_dotenv()except ImportError: pass
db_url = os.environ.get("DB_URI")if db_url: config.set_main_option("sqlalchemy.url", db_url)
# No metadata target β we use raw SQL migrations for maximum controltarget_metadata = None
def run_migrations_offline() -> None: """Run migrations in 'offline' mode (generate SQL script).""" url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, )
with context.begin_transaction(): context.run_migrations()
def run_migrations_online() -> None: """Run migrations in 'online' mode (execute against database).""" connectable = engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, )
with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, )
with context.begin_transaction(): context.run_migrations()
if context.is_offline_mode(): run_migrations_offline()else: run_migrations_online()123456789101112131415161718192021222324"""${message}
Revision ID: ${up_revision}Revises: ${down_revision | comma,n}Create Date: ${create_date}"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision: str = ${repr(up_revision)}down_revision: Union[str, None] = ${repr(down_revision)}branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None: ${upgrades if upgrades else "pass"}
def downgrade() -> None: ${downgrades if downgrades else "pass"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Create plainsql_users and query_feedback tables
Revision ID: 001Revises: NoneCreate Date: 2026-05-02"""from typing import Sequence, Union
from alembic import op
revision: str = "001"down_revision: Union[str, None] = Nonebranch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # ββ Users table (replaces in-memory user store) ββββββ op.execute(""" CREATE TABLE IF NOT EXISTS plainsql_users ( id VARCHAR(64) PRIMARY KEY, username VARCHAR(100) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL, password_hash VARCHAR(255) NOT NULL, role ENUM('admin', 'analyst', 'viewer') NOT NULL DEFAULT 'analyst', tenant_id VARCHAR(100) NOT NULL DEFAULT 'default', is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_username (username), INDEX idx_tenant (tenant_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """)
# ββ Query feedback table (user satisfaction tracking) β op.execute(""" CREATE TABLE IF NOT EXISTS query_feedback ( id INT AUTO_INCREMENT PRIMARY KEY, trace_id VARCHAR(100) NOT NULL, user_query TEXT NOT NULL, generated_sql TEXT, rating ENUM('positive', 'negative') NOT NULL, comment TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, tenant_id VARCHAR(100) DEFAULT 'default', INDEX idx_trace (trace_id), INDEX idx_created (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 """)
def downgrade() -> None: op.execute("DROP TABLE IF EXISTS query_feedback") op.execute("DROP TABLE IF EXISTS plainsql_users")12# PlainSQL Enterprise Backend__version__ = "2.0.0"1# Agents Package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Execution Agent β Safely executes validated SQL against the tenant database.Includes EXPLAIN-based cost estimation to prevent expensive queries.Tracks execution time and handles errors gracefully."""
import timeimport structlog
from app.agents.state import AgentState
logger = structlog.get_logger()
# Maximum rows a query is allowed to examine before being blockedMAX_ROWS_EXAMINED = 100_000
def _estimate_query_cost(db_pool, sql: str) -> dict: """ Run EXPLAIN on the query to estimate cost before execution. Returns estimated row count, whether a full table scan is detected, and whether the query is safe to execute. """ try: explain_sql = f"EXPLAIN {sql.rstrip(';')}" rows = db_pool.execute_query(explain_sql)
total_rows_examined = 0 has_full_scan = False
for row in rows: row_estimate = int(row.get("rows", 0) or 0) total_rows_examined += row_estimate scan_type = str(row.get("type", "")).upper() if scan_type == "ALL" and row_estimate > 10000: has_full_scan = True
return { "estimated_rows": total_rows_examined, "has_full_scan": has_full_scan, "safe": total_rows_examined < MAX_ROWS_EXAMINED and not has_full_scan, } except Exception as e: logger.warning("explain_failed", error=str(e)) # If EXPLAIN fails, allow the query (fail open) return {"estimated_rows": 0, "has_full_scan": False, "safe": True}
def execution_node(state: AgentState, db_pool) -> dict: """ Execute the validated SQL query against the database. Runs EXPLAIN first to estimate cost and block expensive queries. Measures execution time and returns structured results. """ sql = state.get("sanitized_sql", "") or state.get("generated_sql", "") trace_id = state.get("trace_id", "unknown")
logger.info("agent_started", agent="execution", trace_id=trace_id)
if not sql or not sql.strip(): return { "query_results": [], "execution_time_ms": 0, "row_count": 0, "column_names": [], "error": "No SQL to execute", "error_agent": "execution", }
# ββ Cost Estimation (conditional to avoid doubling DB round-trips) ββ # Only run EXPLAIN for queries without WHERE filters or complex queries, # since simple filtered queries are unlikely to cause full table scans. sql_upper = sql.upper() needs_cost_check = "WHERE" not in sql_upper or state.get("complexity") == "complex"
if needs_cost_check: cost = _estimate_query_cost(db_pool, sql) if not cost["safe"]: logger.warning( "query_too_expensive", trace_id=trace_id, estimated_rows=cost["estimated_rows"], has_full_scan=cost["has_full_scan"], ) return { "query_results": [], "execution_time_ms": 0, "row_count": 0, "column_names": [], "error": f"Query blocked: estimated to scan ~{cost['estimated_rows']:,} rows. " f"Add WHERE filters or LIMIT to reduce scope.", "error_agent": "execution", "friendly_message": ( "β οΈ **Query too expensive**: This query would scan a very large number of rows. " "Please add filters (WHERE clause) or a smaller LIMIT to reduce the scope." ), } else: cost = {"estimated_rows": 0, "has_full_scan": False, "safe": True}
# ββ Execute Query ββββββββββββββββββββββββββββββββββββ try: start_time = time.perf_counter() results = db_pool.execute_query(sql) end_time = time.perf_counter()
execution_time_ms = round((end_time - start_time) * 1000, 2)
# Extract column names from results column_names = list(results[0].keys()) if results else []
logger.info( "query_executed", execution_time_ms=execution_time_ms, row_count=len(results), columns=len(column_names), estimated_rows=cost["estimated_rows"], )
return { "query_results": results, "execution_time_ms": execution_time_ms, "row_count": len(results), "column_names": column_names, }
except Exception as e: error_msg = str(e) logger.error("query_execution_failed", error=error_msg, sql_preview=sql[:100])
return { "query_results": [], "execution_time_ms": 0, "row_count": 0, "column_names": [], "error": f"Database error: {error_msg}", "error_agent": "execution", "friendly_message": f"The query had a syntax error: {error_msg}", }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264"""Output Guardrails β Schema grounding, confidence scoring, and robust SQL extraction.Prevents hallucinated table/column references and handles malformed LLM output."""
import reimport sqlparseimport structlog
logger = structlog.get_logger()
class OutputGuardrail: """ Validates LLM output before SQL execution: 1. Schema grounding β ensures SQL only references real tables and columns 2. SQL extraction β robustly extracts SQL from messy LLM responses 3. Confidence scoring β detects uncertain/hedging language """
def __init__(self, known_tables: set = None, known_columns: dict = None): """ Args: known_tables: Set of valid table names in the database known_columns: Dict of {table_name: set of column_names} """ self.known_tables = {t.lower() for t in (known_tables or set())} self.known_columns = { t.lower(): {c.lower() for c in cols} for t, cols in (known_columns or {}).items() } self.all_columns = set() for cols in self.known_columns.values(): self.all_columns.update(cols)
def update_schema(self, tables: set, columns: dict): """Update known schema when database connection changes.""" self.known_tables = {t.lower() for t in tables} self.known_columns = { t.lower(): {c.lower() for c in cols} for t, cols in columns.items() } self.all_columns = set() for cols in self.known_columns.values(): self.all_columns.update(cols)
def validate_sql_references(self, sql: str) -> list[str]: """ Check that generated SQL only references real tables and columns. Returns a list of hallucination warnings (empty = clean). """ if not sql or not self.known_tables: return []
warnings = []
try: parsed = sqlparse.parse(sql) if not parsed: return warnings
# Comprehensive SQL functions to skip sql_functions = { "count", "sum", "avg", "min", "max", "round", "coalesce", "ifnull", "isnull", "nullif", "concat", "substring", "trim", "upper", "lower", "length", "cast", "convert", "date_format", "date_sub", "date_add", "curdate", "now", "year", "month", "day", "hour", "minute", "second", "datediff", "timestampdiff", "group_concat", "distinct", "if", "abs", "ceil", "floor", "power", "sqrt", "mod", "sign", "truncate", "replace", "lpad", "rpad", "left", "right", "reverse", "space", "char_length", "character_length", "locate", "instr", "field", "elt", "format", "hex", "unhex", "crc32", "last_insert_id", "row_number", "rank", "dense_rank", "ntile", "lag", "lead", "first_value", "last_value", "nth_value", "percent_rank", "cume_dist", "quarter", "week", "dayofweek", "dayofyear", "monthname", "dayname", "time", "timestamp", "str_to_date", "date", }
# SQL keywords that appear as Name tokens sql_keywords = { "asc", "desc", "limit", "offset", "as", "on", "and", "or", "not", "in", "between", "like", "is", "null", "true", "false", "inner", "left", "right", "outer", "cross", "natural", "select", "from", "where", "join", "group", "order", "having", "by", "union", "except", "intersect", "with", "recursive", "case", "when", "then", "else", "end", "exists", "any", "all", "interval", "rows", "unbounded", "preceding", "following", "over", "partition", "range", "current", "row", "rollup", "cube", "grouping", "sets", }
# ββ Extract ALL defined aliases ββββββββββββββββββ defined_aliases = set()
# 1. SELECT ... AS alias_name (column aliases) for m in re.finditer(r'\bAS\s+`?(\w+)`?', sql, re.IGNORECASE): defined_aliases.add(m.group(1).lower())
# 2. FROM/JOIN table aliases for m in re.finditer( r'(?:FROM|JOIN)\s+`?(\w+)`?\s+(?:AS\s+)?`?(\w+)`?', sql, re.IGNORECASE, ): alias = m.group(2).lower() table = m.group(1).lower() if alias != table and alias not in sql_keywords: defined_aliases.add(alias)
# 3. CTE names: WITH cte_name AS (...) for m in re.finditer(r'\bWITH\s+(\w+)\s+AS\s*\(', sql, re.IGNORECASE): defined_aliases.add(m.group(1).lower())
for token in parsed[0].flatten(): if token.ttype is sqlparse.tokens.Name: name = token.value.lower().strip('`"[]')
# Skip known SQL functions and keywords if name in sql_functions or name in sql_keywords: continue
# Skip single-char aliases (e.g., e, s, p, c, d, t) if len(name) <= 1: continue
# Skip defined aliases (e.g., dept, emp, avg_salary) if name in defined_aliases: continue
# Check against known schema if name not in self.known_tables and name not in self.all_columns: warnings.append(f"Unknown reference: '{name}' β not a known table or column")
except Exception as e: logger.warning("guardrail_parse_failed", error=str(e))
return warnings
def extract_sql_from_response(self, llm_output: str) -> str: """ Robustly extract SQL from potentially messy LLM output. Handles: - JSON-wrapped responses - Markdown code blocks - Raw SQL with explanatory text - Multiple SQL statements (returns first SELECT) """ if not llm_output: return ""
text = llm_output.strip()
# Strategy 1: Try JSON extraction try: # Remove markdown JSON blocks clean = re.sub(r"```(?:json)?\s*", "", text) clean = re.sub(r"```\s*$", "", clean, flags=re.MULTILINE) import json data = json.loads(clean.strip()) if isinstance(data, dict) and "sql" in data: sql = data["sql"].strip() if sql: return self._clean_extracted_sql(sql) except (ValueError, TypeError): pass
# Strategy 2: Extract from markdown SQL block sql_block = re.search(r"```sql\s*\n?(.*?)\n?```", text, re.DOTALL | re.IGNORECASE) if sql_block: return self._clean_extracted_sql(sql_block.group(1))
# Strategy 3: Extract from generic code block code_block = re.search(r"```\s*\n?(.*?)\n?```", text, re.DOTALL) if code_block: candidate = code_block.group(1).strip() if re.match(r"(?:WITH|SELECT|INSERT|UPDATE|DELETE)\b", candidate, re.IGNORECASE): return self._clean_extracted_sql(candidate)
# Strategy 4: Find standalone SQL statement sql_match = re.search( r"((?:WITH\s+\w+\s+AS\s*\(.*?\)\s*)?SELECT\s[\s\S]+?)(?:;|\n\n|$)", text, re.IGNORECASE | re.DOTALL, ) if sql_match: return self._clean_extracted_sql(sql_match.group(1))
# Strategy 5: Return empty if nothing found logger.warning("sql_extraction_failed", output_preview=text[:200]) return ""
def score_confidence(self, llm_output: str) -> float: """ Score LLM confidence from 0.0 to 1.0 based on language analysis. Low confidence suggests asking for clarification instead of executing. """ if not llm_output: return 0.0
text = llm_output.lower()
# Hedging phrases that indicate low confidence hedging_phrases = [ "i'm not sure", "i am not sure", "i think", "maybe", "perhaps", "possibly", "i don't have enough", "unclear", "ambiguous", "could you clarify", "i'm guessing", "it's hard to tell", "without more context", "assuming", "i cannot determine", "not enough information", ]
hedging_count = sum(1 for phrase in hedging_phrases if phrase in text)
# Check if SQL was actually generated has_sql = bool(re.search(r"\bSELECT\b", text, re.IGNORECASE))
# Base confidence confidence = 1.0 if has_sql else 0.3
# Penalize for hedging confidence -= hedging_count * 0.15
# Penalize for error indicators if "error" in text or "cannot" in text or "unable to" in text: confidence -= 0.3
return max(0.0, min(1.0, confidence))
def _clean_extracted_sql(self, sql: str) -> str: """Normalize extracted SQL.""" # Remove leading/trailing whitespace and markdown artifacts sql = sql.strip() sql = re.sub(r"```\w*", "", sql).strip() # Normalize whitespace sql = " ".join(sql.split()) # Ensure trailing semicolon if sql and not sql.endswith(";"): sql += ";" return sql
def validate_output(self, llm_output: str) -> dict: """ Full output validation pipeline. Returns a dict with sql, confidence, warnings, and is_safe. """ sql = self.extract_sql_from_response(llm_output) confidence = self.score_confidence(llm_output) warnings = self.validate_sql_references(sql) if sql else []
is_safe = ( bool(sql) and confidence >= 0.4 and len(warnings) == 0 )
return { "sql": sql, "confidence": round(confidence, 2), "warnings": warnings, "is_safe": is_safe, "needs_clarification": confidence < 0.4, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Intent classifier for routing user input before SQL generation.
Uses a hybrid approach:1. ML model (sentence-transformers + LogisticRegression) when available and confident2. Heuristic keyword matching as a fallback
Clear chat messages return fast and never touch schema retrieval or SQLgeneration. Database-shaped requests continue through the existing SQL path."""
from dataclasses import dataclassfrom typing import Literalimport reimport structlog
logger = structlog.get_logger()
IntentKind = Literal["chat", "sql", "ambiguous"]RouteIntent = Literal["chat", "ambiguous", "meta_query", "data_query", "aggregation", "comparison", "explanation"]
# Minimum confidence from the ML model to trust its classification_ML_CONFIDENCE_THRESHOLD = 0.70
@dataclass(frozen=True)class IntentClassification: intent: IntentKind route_intent: RouteIntent complexity: Literal["simple", "moderate", "complex"] = "simple" reason: str = "heuristic"
GREETING_PATTERNS = { "hello", "hi", "hey", "good morning", "good afternoon", "good evening", "hola", "sup", "what's up", "howdy", "yo", "greetings", "namaste", "bonjour",}
CHAT_EXACT = { "thanks", "thank you", "thank u", "thx", "ty", "ok", "okay", "cool", "great", "nice", "awesome", "got it", "bye", "goodbye", "see you", "see ya", "later", "yes", "no", "yep", "nope", "sure", "nah", "help", "help me", "what can you do", "who are you", "what are you", "how are you", "how do you work", "how does this work", "tell me about yourself", "what is this", "what is plainsql",}
CHAT_PREFIXES = { "thanks for", "thank you for", "can you help", "please help", "i need help", "i don't understand", "what do you do", "what can i ask", "how do i use", "tell me about you", "who made you", "are you", "tell me a joke", "how is the weather", "tell me about yourself", "do you know about",}
DATA_SIGNAL_PHRASES = { "how many", "how much", "group by", "order by", "by region", "by department", "by category", "by month", "by year",}
# Strong signals β specific enough to indicate a real SQL queryDATA_SIGNAL_WORDS_STRONG = { "show", "list", "find", "get", "select", "count", "total", "average", "avg", "sum", "top", "bottom", "highest", "lowest", "maximum", "minimum", "max", "min", "most", "least", "revenue", "sales", "salary", "salaries", "price", "stock", "spend", "employees", "employee", "customers", "customer", "products", "product", "departments", "department", "orders", "order", "where", "between", "greater", "less", "equal", "filter", "sort", "compare", "vs", "versus", "per", "each", "join", "query", "report",}
# Weak signals β too generic alone, need a strong signal to confirm SQL intentDATA_SIGNAL_WORDS_WEAK = { "table", "tables", "column", "columns", "rows", "records", "all", "every", "data", "database", "info", "information", "about", "details",}
DATA_SIGNAL_WORDS = DATA_SIGNAL_WORDS_STRONG | DATA_SIGNAL_WORDS_WEAK
# Known database table names β used to validate ambiguous queriesKNOWN_TABLES = { "employees", "employee", "departments", "department", "products", "product", "customers", "customer", "sales", "sale", "orders", "order",}
META_KEYWORDS = { "what tables", "show tables", "list tables", "what columns", "describe table", "schema", "what database",}AGGREGATION_KEYWORDS = { "count", "total", "sum", "average", "avg", "minimum", "maximum", "min", "max", "group by", "by region", "by department", "by category", "by month", "by year",}COMPARISON_KEYWORDS = {"compare", " vs ", " versus ", "between"}EXPLANATION_KEYWORDS = {"explain this", "why did", "what does this query"}
def classify_intent(user_query: str) -> IntentClassification: """ Classify input as chat, SQL, or ambiguous and choose the downstream graph route.
Strategy: 1. Try ML model first (sentence-transformers + LogisticRegression) 2. If model unavailable or confidence < threshold, fall back to heuristic """ query = _normalize(user_query) if not query: return IntentClassification("chat", "chat", reason="empty")
# ββ ML Classification (preferred) ββββββββββββββββββββ ml_result = _try_ml_classification(user_query) if ml_result is not None: return ml_result
# ββ Heuristic Fallback βββββββββββββββββββββββββββββββ
# Meta queries are always SQL if any(kw in query for kw in META_KEYWORDS): return IntentClassification( "sql", "meta_query", complexity="simple", reason="meta_keyword", )
has_data_signal = _has_data_signal(query)
# Mixed inputs like "hi, show top 5 employees" should still be SQL. if has_data_signal: # Check if only weak signals present (e.g. "do you have info about admin") words = set(re.findall(r"[a-z_]+", query)) has_strong = bool(words.intersection(DATA_SIGNAL_WORDS_STRONG)) has_known_table = bool(words.intersection(KNOWN_TABLES)) has_phrase = any(phrase in query for phrase in DATA_SIGNAL_PHRASES)
if has_strong or has_phrase or has_known_table: return IntentClassification( "sql", _classify_sql_route(query), complexity=_estimate_complexity(query), reason="data_signal", ) else: # Weak signal only β ambiguous query return IntentClassification( "ambiguous", "ambiguous", complexity="simple", reason="weak_data_signal_only", )
if _is_chat(query): return IntentClassification("chat", "chat", reason="chat_signal")
if len(query.split()) <= 4: return IntentClassification("chat", "chat", reason="short_without_data_signal")
# Longer queries without any data signal β likely ambiguous words = set(re.findall(r"[a-z_]+", query)) has_known_table = bool(words.intersection(KNOWN_TABLES)) if not has_known_table: return IntentClassification( "ambiguous", "ambiguous", complexity="simple", reason="no_table_reference", )
# Preserve existing text-to-SQL behavior for ambiguous analytical requests. return IntentClassification( "sql", _classify_sql_route(query), complexity=_estimate_complexity(query), reason="ambiguous_default_sql", )
def build_chat_response(user_query: str) -> str: """Return a simple conversational response without invoking SQL generation.""" query = _normalize(user_query)
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")): return ( "I'm PlainSQL, your data assistant. Ask me a database question in plain " "English and I can generate safe read-only SQL, run it, and summarize the result. " "Try: 'Show top 5 employees by salary' or 'Total sales by region'." )
if any(kw in query for kw in ("who are you", "what are you", "tell me about you", "what is plainsql", "what is this")): return ( "I'm PlainSQL, an assistant for querying your database with natural language. " "Describe the data you want and I'll handle the SQL path." )
if any(kw in query for kw in ("thanks", "thank", "thx", "ty")): return "You're welcome. Ask me any database question when you're ready."
if any(kw in query for kw in ("bye", "goodbye", "see you", "see ya", "later")): return "Goodbye. Come back anytime you want to explore your data."
return ( "Hello. I can help you query your database in plain English. " "Try asking something like 'Show top 5 employees by salary'." )
def _normalize(value: str) -> str: cleaned = re.sub(r"\s+", " ", value.lower()).strip() return cleaned.strip(" \t\r\n.!?")
def _has_data_signal(query: str) -> bool: if any(phrase in query for phrase in DATA_SIGNAL_PHRASES): return True words = set(re.findall(r"[a-z_]+", query)) return bool(words.intersection(DATA_SIGNAL_WORDS))
def _is_chat(query: str) -> bool: if query in CHAT_EXACT or query in GREETING_PATTERNS: return True if any(query.startswith(prefix) for prefix in CHAT_PREFIXES): return True return any(query == greeting or query.startswith(greeting + " ") for greeting in GREETING_PATTERNS)
def _classify_sql_route(query: str) -> RouteIntent: if any(kw in query for kw in META_KEYWORDS): return "meta_query" if any(kw in query for kw in COMPARISON_KEYWORDS): return "comparison" if any(kw in query for kw in EXPLANATION_KEYWORDS): return "explanation" if any(kw in query for kw in AGGREGATION_KEYWORDS): return "aggregation" return "data_query"
def _estimate_complexity(query: str) -> Literal["simple", "moderate", "complex"]: if any(kw in query for kw in ("subquery", "window", "rank", "running total", "percentile")): return "complex" if any(kw in query for kw in ("join", "compare", " vs ", " versus ", "group by", " by ")): return "moderate" return "simple"
# ββ ML Classification Bridge ββββββββββββββββββββββββββββββββ
def _try_ml_classification(user_query: str) -> IntentClassification | None: """ Attempt to classify using the ML model.
Returns an IntentClassification if the model is available and confident, or None to signal the caller should use the heuristic fallback. """ import os if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"): logger.debug("ml_classification_disabled_by_env") return None
try: from app.agents.ml_classifier import get_ml_classifier
classifier = get_ml_classifier() if not classifier.available: return None
result = classifier.classify(user_query) if result is None: return None
# Only trust the ML model when it's confident enough if result.confidence < _ML_CONFIDENCE_THRESHOLD: logger.debug( "ml_confidence_below_threshold", confidence=result.confidence, threshold=_ML_CONFIDENCE_THRESHOLD, ml_label=result.intent, fallback="heuristic", ) return None
# Map ML result to the full IntentClassification with complexity query_normalized = _normalize(user_query) complexity = _estimate_complexity(query_normalized)
# For SQL intents, refine the route using the heuristic sub-classifier if result.intent == "sql": route = _classify_sql_route(query_normalized) else: route = result.route_intent
logger.info( "intent_classified", method="ml", intent=result.intent, route_intent=route, confidence=round(result.confidence, 3), )
return IntentClassification( intent=result.intent, route_intent=route, complexity=complexity, reason=f"ml_model(conf={result.confidence:.2f})", )
except Exception as e: logger.debug("ml_classification_unavailable", error=str(e)) return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""ML Intent Classifier β Sentence-transformer embeddings + LogisticRegression.
Provides a trained ML model for intent classification, replacing pure heuristickeyword matching with learned representations. Falls back gracefully when themodel file is not available.
Architecture: sentence-transformers/all-MiniLM-L6-v2 (384-dim) β LogisticRegression (4 classes)
Classes: chat β Greetings, thanks, capability questions, off-topic sql β Data queries, aggregations, comparisons, joins ambiguous β Vague data-shaped queries that need clarification meta_query β Schema exploration (show tables, describe columns)"""
import osimport structlogfrom typing import Optionalfrom dataclasses import dataclass
logger = structlog.get_logger()
# Path to the pre-trained model artifact_MODEL_DIR = os.path.dirname(os.path.abspath(__file__))_MODEL_PATH = os.path.join(_MODEL_DIR, "models", "intent_model.joblib")
# Map ML labels to route_intent values for pipeline compatibility_ROUTE_INTENT_MAP = { "chat": "chat", "sql": "data_query", "ambiguous": "chat", "meta_query": "meta_query",}
@dataclassclass MLClassification: """Result from the ML classifier.""" intent: str # chat | sql | ambiguous | meta_query route_intent: str # Pipeline-compatible intent for routing confidence: float # Model confidence (0.0 - 1.0) method: str = "ml" # Always "ml" for this classifier
class MLIntentClassifier: """ ML-based intent classifier using sentence-transformer embeddings and logistic regression.
Loads a pre-trained model from disk. If the model is unavailable, classify() returns None so the caller can fall back to heuristics. """
def __init__(self, model_path: str = None): self.model = None self.encoder = None self._loaded = False self._model_path = model_path or _MODEL_PATH
self._try_load()
def _try_load(self): """Attempt to load the pre-trained model and encoder.""" if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"): logger.info("ml_classifier_disabled_by_env") return
if not os.path.exists(self._model_path): logger.info("ml_classifier_model_not_found", path=self._model_path) return
try: import joblib from sentence_transformers import SentenceTransformer
self.model = joblib.load(self._model_path) self.encoder = SentenceTransformer("all-MiniLM-L6-v2") self._loaded = True logger.info("ml_classifier_loaded", path=self._model_path) except ImportError as e: logger.warning("ml_classifier_deps_missing", error=str(e), hint="pip install scikit-learn sentence-transformers joblib") except Exception as e: logger.warning("ml_classifier_load_failed", error=str(e))
@property def available(self) -> bool: """Whether the ML model is loaded and ready for inference.""" return self._loaded and self.model is not None and self.encoder is not None
def classify(self, query: str) -> Optional[MLClassification]: """ Classify a query using the ML model.
Returns: MLClassification if model is available and confident, None if model is unavailable (caller should fall back to heuristic). """ if not self.available: return None
try: # Encode the query to a 384-dim embedding embedding = self.encoder.encode([query])
# Predict class and confidence predicted_label = self.model.predict(embedding)[0] probabilities = self.model.predict_proba(embedding)[0] confidence = float(max(probabilities))
route_intent = _ROUTE_INTENT_MAP.get(predicted_label, "data_query")
logger.debug( "ml_classification", query=query[:80], label=predicted_label, confidence=round(confidence, 3), route_intent=route_intent, )
return MLClassification( intent=predicted_label, route_intent=route_intent, confidence=confidence, )
except Exception as e: logger.warning("ml_classification_failed", error=str(e)) return None
# ββ Module-level singleton βββββββββββββββββββββββββββββββββββ# Lazy-loaded on first use to avoid startup cost if not needed._classifier_instance: Optional[MLIntentClassifier] = None
def get_ml_classifier() -> MLIntentClassifier: """Get or create the singleton ML classifier instance.""" global _classifier_instance if _classifier_instance is None: _classifier_instance = MLIntentClassifier() return _classifier_instance1# ML model artifacts for intent classification123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Train the ML intent classifier.
Usage: cd backend python -m app.agents.models.train_classifier
This script:1. Loads training data from training_data.json2. Encodes all examples using sentence-transformers/all-MiniLM-L6-v23. Trains a LogisticRegression classifier with cross-validation4. Saves the model to intent_model.joblib5. Prints a classification report and accuracy metrics
The output model is used by MLIntentClassifier in ml_classifier.py."""
import jsonimport osimport numpy as np
def main(): # ββ Load training data βββββββββββββββββββββββββββββββ data_dir = os.path.dirname(os.path.abspath(__file__)) data_path = os.path.join(data_dir, "training_data.json") model_path = os.path.join(data_dir, "intent_model.joblib")
print(f"[LOAD] Loading training data from {data_path}") with open(data_path, "r") as f: dataset = json.load(f)
texts = [item["text"] for item in dataset] labels = [item["label"] for item in dataset]
print(f" Total examples: {len(texts)}") label_counts = {} for label in labels: label_counts[label] = label_counts.get(label, 0) + 1 for label, count in sorted(label_counts.items()): print(f" - {label}: {count}")
# ββ Encode with sentence-transformers ββββββββββββββββ print("\n[ENCODE] Encoding with sentence-transformers/all-MiniLM-L6-v2...") from sentence_transformers import SentenceTransformer
encoder = SentenceTransformer("all-MiniLM-L6-v2") embeddings = encoder.encode(texts, show_progress_bar=True) print(f" Embedding shape: {embeddings.shape}")
# ββ Train/test split ββββββββββββββββββββββββββββββββ from sklearn.model_selection import train_test_split, cross_val_score from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix
X_train, X_test, y_train, y_test = train_test_split( embeddings, labels, test_size=0.2, random_state=42, stratify=labels )
print(f"\n[SPLIT] Train: {len(X_train)} | Test: {len(X_test)}")
# ββ Train LogisticRegression ββββββββββββββββββββββββ print("\n[TRAIN] Training LogisticRegression classifier...") model = LogisticRegression( max_iter=1000, C=1.0, solver="lbfgs", multi_class="multinomial", class_weight="balanced", # Handle class imbalance random_state=42, ) model.fit(X_train, y_train)
# ββ Evaluate ββββββββββββββββββββββββββββββββββββββββ y_pred = model.predict(X_test) accuracy = (np.array(y_pred) == np.array(y_test)).mean()
print(f"\n{'='*60}") print(" TEST SET RESULTS") print(f"{'='*60}") print(f" Accuracy: {accuracy:.1%}") print(f"\n{classification_report(y_test, y_pred)}")
# ββ Cross-validation ββββββββββββββββββββββββββββββββ print("[CV] 5-Fold Cross-Validation...") cv_scores = cross_val_score(model, embeddings, labels, cv=5, scoring="accuracy") print(f" CV Accuracy: {cv_scores.mean():.1%} +/- {cv_scores.std():.1%}") print(f" Fold scores: {[f'{s:.1%}' for s in cv_scores]}")
# ββ Confusion Matrix ββββββββββββββββββββββββββββββββ print("\n[MATRIX] Confusion Matrix:") cm = confusion_matrix(y_test, y_pred, labels=sorted(set(labels))) cm_labels = sorted(set(labels)) header = " " + " ".join(f"{label:>10}" for label in cm_labels) print(header) for i, row in enumerate(cm): row_str = " ".join(f"{v:>10}" for v in row) print(f" {cm_labels[i]:>8} {row_str}")
# ββ Save model ββββββββββββββββββββββββββββββββββββββ print(f"\n[SAVE] Saving model to {model_path}") import joblib joblib.dump(model, model_path) model_size = os.path.getsize(model_path) print(f" Model size: {model_size / 1024:.1f} KB")
# ββ Quick inference test ββββββββββββββββββββββββββββ print("\n[TEST] Quick inference test:") test_queries = [ "hello", "show top 5 employees by salary", "what tables are there", "show me some data", "total revenue by region", "thanks", ] test_embeddings = encoder.encode(test_queries) test_preds = model.predict(test_embeddings) test_probs = model.predict_proba(test_embeddings)
for query, pred, probs in zip(test_queries, test_preds, test_probs): conf = max(probs) print(f" '{query}' -> {pred} ({conf:.0%})")
print("\n[DONE] Training complete!") return accuracy
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173[ {"text": "hello", "label": "chat"}, {"text": "hi", "label": "chat"}, {"text": "hey there", "label": "chat"}, {"text": "good morning", "label": "chat"}, {"text": "good afternoon", "label": "chat"}, {"text": "good evening", "label": "chat"}, {"text": "howdy", "label": "chat"}, {"text": "what's up", "label": "chat"}, {"text": "yo", "label": "chat"}, {"text": "greetings", "label": "chat"}, {"text": "namaste", "label": "chat"}, {"text": "thanks", "label": "chat"}, {"text": "thank you", "label": "chat"}, {"text": "thanks a lot", "label": "chat"}, {"text": "thank you so much", "label": "chat"}, {"text": "cool, thanks", "label": "chat"}, {"text": "great, thank you!", "label": "chat"}, {"text": "bye", "label": "chat"}, {"text": "goodbye", "label": "chat"}, {"text": "see you later", "label": "chat"}, {"text": "see ya", "label": "chat"}, {"text": "ok bye", "label": "chat"}, {"text": "what can you do", "label": "chat"}, {"text": "what are you", "label": "chat"}, {"text": "who are you", "label": "chat"}, {"text": "how do you work", "label": "chat"}, {"text": "what is plainsql", "label": "chat"}, {"text": "tell me about yourself", "label": "chat"}, {"text": "help me", "label": "chat"}, {"text": "what can I ask you", "label": "chat"}, {"text": "how do I use this", "label": "chat"}, {"text": "are you an AI", "label": "chat"}, {"text": "how is the weather", "label": "chat"}, {"text": "tell me a joke", "label": "chat"}, {"text": "yes", "label": "chat"}, {"text": "no", "label": "chat"}, {"text": "ok", "label": "chat"}, {"text": "sure", "label": "chat"}, {"text": "nope", "label": "chat"}, {"text": "got it", "label": "chat"}, {"text": "awesome", "label": "chat"}, {"text": "nice", "label": "chat"}, {"text": "cool", "label": "chat"}, {"text": "great work", "label": "chat"}, {"text": "perfect", "label": "chat"}, {"text": "can you help me with something", "label": "chat"}, {"text": "I don't understand", "label": "chat"}, {"text": "what does this mean", "label": "chat"}, {"text": "who made you", "label": "chat"}, {"text": "do you know about machine learning", "label": "chat"},
{"text": "show all accounts with high churn risk", "label": "sql"}, {"text": "list enterprise accounts by health score", "label": "sql"}, {"text": "what is the total contracted ARR", "label": "sql"}, {"text": "show total ARR by customer segment", "label": "sql"}, {"text": "how many active subscriptions do we have", "label": "sql"}, {"text": "list past due subscriptions", "label": "sql"}, {"text": "show open P1 support tickets", "label": "sql"}, {"text": "which accounts have the most support tickets", "label": "sql"}, {"text": "show monthly invoice revenue trends", "label": "sql"}, {"text": "what is the total revenue from paid invoices", "label": "sql"}, {"text": "show overdue invoices by account", "label": "sql"}, {"text": "list all opportunities in negotiation stage", "label": "sql"}, {"text": "what is the pipeline forecast by category", "label": "sql"}, {"text": "show closed-won deals this year", "label": "sql"}, {"text": "rank sales reps by ARR", "label": "sql"}, {"text": "which opportunities have stalled", "label": "sql"}, {"text": "show product usage trends", "label": "sql"}, {"text": "rank workspaces by query volume", "label": "sql"}, {"text": "what is the p95 latency by feature", "label": "sql"}, {"text": "show failed query count by workspace", "label": "sql"}, {"text": "list employees in the engineering department", "label": "sql"}, {"text": "show the salary budget by department", "label": "sql"}, {"text": "how many employees are in each department", "label": "sql"}, {"text": "show top accounts by revenue with ticket count", "label": "sql"}, {"text": "calculate net revenue retention by segment", "label": "sql"}, {"text": "what percentage of ARR is at high churn risk", "label": "sql"}, {"text": "show payment failure rate by segment", "label": "sql"}, {"text": "compare ticket volume between P1 and P2", "label": "sql"}, {"text": "show CSAT scores by ticket category", "label": "sql"}, {"text": "find accounts with high ARR but low health scores", "label": "sql"}, {"text": "show SLA breach count by account", "label": "sql"}, {"text": "list executive sponsors at strategic accounts", "label": "sql"}, {"text": "show workspace user count by role", "label": "sql"}, {"text": "what are the top loss reasons for opportunities", "label": "sql"}, {"text": "show quarterly revenue from invoices", "label": "sql"}, {"text": "compare ARR between North America and Europe", "label": "sql"}, {"text": "which accounts have subscriptions but no product usage", "label": "sql"}, {"text": "show compute usage by account segment", "label": "sql"}, {"text": "list sev1 incidents with root cause", "label": "sql"}, {"text": "show average deal cycle for closed-won opportunities", "label": "sql"}, {"text": "what is the conversion rate by opportunity source", "label": "sql"}, {"text": "show ticket resolution time by priority", "label": "sql"}, {"text": "how much revenue did we collect last quarter", "label": "sql"}, {"text": "which features have the highest failure rate", "label": "sql"}, {"text": "show the discount percentage by plan type", "label": "sql"}, {"text": "rank accounts by employee count", "label": "sql"}, {"text": "list all cancelled subscriptions with ARR", "label": "sql"}, {"text": "show query audit log success rate by route", "label": "sql"}, {"text": "find the average first response time for P1 tickets", "label": "sql"}, {"text": "show accounts in the 500k plus ARR band", "label": "sql"}, {"text": "what is the average contracted ARR per plan", "label": "sql"}, {"text": "show incident frequency by affected product", "label": "sql"}, {"text": "list contacts in the data department", "label": "sql"}, {"text": "show total seats purchased by plan", "label": "sql"}, {"text": "hey can you show me total ARR by segment", "label": "sql"}, {"text": "please show accounts with high churn risk", "label": "sql"}, {"text": "I want to see the pipeline forecast", "label": "sql"}, {"text": "give me subscription renewal rates", "label": "sql"}, {"text": "what does our support ticket volume look like", "label": "sql"}, {"text": "how much revenue is at risk from churning accounts", "label": "sql"}, {"text": "break down invoice revenue by region", "label": "sql"}, {"text": "which reps are hitting their quota", "label": "sql"}, {"text": "show me accounts that might churn", "label": "sql"}, {"text": "how are our workspaces performing", "label": "sql"}, {"text": "what is the trend in product adoption", "label": "sql"},
{"text": "show me data", "label": "ambiguous"}, {"text": "what about the data", "label": "ambiguous"}, {"text": "tell me about the information", "label": "ambiguous"}, {"text": "show me everything", "label": "ambiguous"}, {"text": "what do we have", "label": "ambiguous"}, {"text": "give me details", "label": "ambiguous"}, {"text": "can you check something", "label": "ambiguous"}, {"text": "look up some records", "label": "ambiguous"}, {"text": "find something for me", "label": "ambiguous"}, {"text": "what's in the system", "label": "ambiguous"}, {"text": "pull up some info", "label": "ambiguous"}, {"text": "show me the numbers", "label": "ambiguous"}, {"text": "give me a report", "label": "ambiguous"}, {"text": "can you query the database", "label": "ambiguous"}, {"text": "what does the data say", "label": "ambiguous"}, {"text": "run a query for me", "label": "ambiguous"}, {"text": "I need some data", "label": "ambiguous"}, {"text": "show results", "label": "ambiguous"}, {"text": "give me an overview", "label": "ambiguous"}, {"text": "what information is available", "label": "ambiguous"}, {"text": "any interesting trends", "label": "ambiguous"}, {"text": "show me the latest", "label": "ambiguous"}, {"text": "how is everything going", "label": "ambiguous"}, {"text": "what are the key metrics", "label": "ambiguous"}, {"text": "analyze the data", "label": "ambiguous"},
{"text": "what tables are in the database", "label": "meta_query"}, {"text": "show tables", "label": "meta_query"}, {"text": "list tables", "label": "meta_query"}, {"text": "what tables do you have", "label": "meta_query"}, {"text": "describe the accounts table", "label": "meta_query"}, {"text": "what columns are in the subscriptions table", "label": "meta_query"}, {"text": "show me the schema", "label": "meta_query"}, {"text": "what is the database structure", "label": "meta_query"}, {"text": "describe table support_tickets", "label": "meta_query"}, {"text": "what columns does the invoices table have", "label": "meta_query"}, {"text": "show the database schema", "label": "meta_query"}, {"text": "what data is stored in this database", "label": "meta_query"}, {"text": "list all table names", "label": "meta_query"}, {"text": "show structure of opportunities table", "label": "meta_query"}, {"text": "what fields does the product_usage_daily table contain", "label": "meta_query"}, {"text": "describe the schema for workspaces", "label": "meta_query"}, {"text": "what are the column names in query_audit_log", "label": "meta_query"}, {"text": "show me the table definitions", "label": "meta_query"}, {"text": "what relationships exist between tables", "label": "meta_query"}, {"text": "how are the tables connected", "label": "meta_query"}, {"text": "show foreign keys", "label": "meta_query"}, {"text": "what is the primary key of accounts", "label": "meta_query"}, {"text": "tell me about the database tables", "label": "meta_query"}, {"text": "list columns in departments", "label": "meta_query"}, {"text": "show me what data you can access", "label": "meta_query"}, {"text": "describe the employees table", "label": "meta_query"}, {"text": "what tables contain revenue data", "label": "meta_query"}, {"text": "how is the subscriptions table related to accounts", "label": "meta_query"}]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856"""LangGraph Orchestrator β Wires all 7 agents into a DAG with conditional routing.This is the core of the multi-agent architecture.Includes pipeline timeout protection, output guardrails, and graceful degradation."""
import uuidimport timeimport asyncioimport threadingimport structlogfrom langgraph.graph import StateGraph, END
from app.agents.state import AgentStatefrom app.agents.query_understanding import query_understanding_nodefrom app.agents.schema_retrieval import schema_retrieval_nodefrom app.agents.sql_generation import sql_generation_nodefrom app.agents.sql_validation import sql_validation_node, route_validationfrom app.agents.execution import execution_nodefrom app.agents.visualization import visualization_nodefrom app.agents.result_summary import result_summary_nodefrom app.agents.guardrails import OutputGuardrail
logger = structlog.get_logger()
# Maximum time (seconds) the full pipeline is allowed to runPIPELINE_TIMEOUT_SECONDS = 60
class AgentOrchestrator: """ Multi-agent orchestrator using LangGraph StateGraph. Flow: understand_query β [chat? β END] β retrieve_schema β generate_sql β validate_sql β [valid? β execute β visualize β END] β [invalid? β retry generate_sql (max 3)] β [blocked? β END with error] """
def __init__(self, llm_router, rag_retriever, db_pool): self.llm_router = llm_router self.rag_retriever = rag_retriever self.db_pool = db_pool
# ββ Initialize Output Guardrail with live schema ββ self.guardrail = self._init_guardrail(db_pool)
# ββ Initialize Semantic Cache ββ self.semantic_cache = self._init_semantic_cache()
self.graph = self._build_graph()
@staticmethod def _init_semantic_cache(): """Initialize the semantic cache for query deduplication.""" try: from app.cache.semantic_cache import SemanticCache cache = SemanticCache(similarity_threshold=0.95, ttl_seconds=300) if cache.available: logger.info("semantic_cache_initialized") return cache logger.info("semantic_cache_disabled", reason="encoder_unavailable") except Exception as e: logger.info("semantic_cache_disabled", reason=str(e)) return None
@staticmethod def _init_guardrail(db_pool) -> OutputGuardrail: """Build the OutputGuardrail from the live database schema.""" try: tables = db_pool.get_tables() known_columns = {} for table in tables: cols = db_pool.get_table_schema(table) known_columns[table] = {c["name"] for c in cols} guardrail = OutputGuardrail( known_tables=set(tables), known_columns=known_columns, ) logger.info("guardrail_initialized", tables=len(tables)) return guardrail except Exception as e: logger.warning("guardrail_init_failed", error=str(e)) return OutputGuardrail()
def _build_graph(self) -> StateGraph: """Construct the LangGraph agent pipeline.""" graph = StateGraph(AgentState)
# ββ Register agent nodes βββββββββββββββββββββββββ graph.add_node("understand_query", self._understand_query) graph.add_node("handle_chat", self._handle_chat) graph.add_node("handle_meta", self._handle_meta) graph.add_node("retrieve_schema", self._retrieve_schema) graph.add_node("generate_sql", self._generate_sql) graph.add_node("guardrail_check", self._guardrail_check) graph.add_node("validate_sql", self._validate_sql) graph.add_node("execute_query", self._execute_query) graph.add_node("ground_summary", self._ground_summary) graph.add_node("visualize", self._visualize) graph.add_node("handle_blocked", self._handle_blocked)
# ββ Entry point ββββββββββββββββββββββββββββββββββ graph.set_entry_point("understand_query")
# ββ Conditional routing after intent classification ββ graph.add_conditional_edges( "understand_query", self._route_by_intent, { "chat": "handle_chat", "ambiguous": "handle_chat", "meta_query": "retrieve_schema", "data_query": "retrieve_schema", "aggregation": "retrieve_schema", "comparison": "retrieve_schema", "explanation": "retrieve_schema", }, )
# ββ Linear flow ββββββββββββββββββββββββββοΏ½οΏ½ββββββ graph.add_conditional_edges( "retrieve_schema", self._route_after_schema, { "meta_query": "handle_meta", "sql": "generate_sql", }, ) graph.add_edge("generate_sql", "guardrail_check") graph.add_edge("guardrail_check", "validate_sql")
# ββ Conditional routing after validation βββββββββ graph.add_conditional_edges( "validate_sql", route_validation, { "valid": "execute_query", "retry": "generate_sql", "blocked": "handle_blocked", }, )
graph.add_edge("execute_query", "ground_summary") graph.add_edge("ground_summary", "visualize")
# ββ Terminal nodes βββββββββββββββββββββββββββββββ graph.add_edge("visualize", END) graph.add_edge("handle_chat", END) graph.add_edge("handle_meta", END) graph.add_edge("handle_blocked", END)
return graph.compile()
# ββ Node Wrappers (inject dependencies + error isolation) ββ
def _understand_query(self, state: AgentState) -> dict: return self._safe_execute("query_understanding", query_understanding_node, state, self.llm_router)
def _retrieve_schema(self, state: AgentState) -> dict: return self._safe_execute("schema_retrieval", schema_retrieval_node, state, self.rag_retriever, self.db_pool)
def _generate_sql(self, state: AgentState) -> dict: return self._safe_execute("sql_generation", sql_generation_node, state, self.llm_router)
def _guardrail_check(self, state: AgentState) -> dict: """Run output guardrails to catch hallucinated table/column references.""" return self._safe_execute("guardrail_check", self._run_guardrail, state)
def _run_guardrail(self, state: AgentState) -> dict: """Execute guardrail validation on the generated SQL.""" sql = state.get("generated_sql", "") if not sql: return {}
warnings = self.guardrail.validate_sql_references(sql) confidence = self.guardrail.score_confidence(sql)
if warnings: logger.warning( "guardrail_warnings", trace_id=state.get("trace_id"), warnings=warnings, confidence=confidence, )
# If many hallucinations are detected, mark as invalid. # Do NOT bump retry_count here β only sql_validation_node manages # the retry counter. Double-counting caused infinite loops. if len(warnings) >= 3: return { "is_valid": False, "validation_errors": [f"Schema grounding failed: {w}" for w in warnings], }
return { "guardrail_warnings": warnings, "guardrail_confidence": confidence, }
def _validate_sql(self, state: AgentState) -> dict: return self._safe_execute("sql_validation", sql_validation_node, state)
def _execute_query(self, state: AgentState) -> dict: return self._safe_execute("execution", execution_node, state, self.db_pool)
def _visualize(self, state: AgentState) -> dict: return self._safe_execute("visualization", visualization_node, state)
def _ground_summary(self, state: AgentState) -> dict: """Replace the LLM's pre-execution hallucinated summary with a grounded one.""" return self._safe_execute("result_summary", result_summary_node, state, self.llm_router)
def _safe_execute(self, agent_name: str, func, *args) -> dict: """ Wrapper that catches per-agent exceptions for graceful degradation. Records per-agent latency metrics and OpenTelemetry spans. Non-critical agents (visualization) failing won't crash the pipeline. """ from app.observability.metrics import metrics from app.observability.tracing import trace_span
trace_id = args[0].get("trace_id", "unknown") if args else "unknown"
with trace_span(f"agent.{agent_name}", {"trace_id": trace_id, "agent": agent_name}): start = time.perf_counter() try: result = func(*args) elapsed_ms = round((time.perf_counter() - start) * 1000, 2) metrics.observe("plainsql_agent_latency_ms", elapsed_ms, {"agent": agent_name}) logger.info("agent_completed", agent=agent_name, elapsed_ms=elapsed_ms, trace_id=trace_id) return result except Exception as e: elapsed_ms = round((time.perf_counter() - start) * 1000, 2) metrics.observe("plainsql_agent_latency_ms", elapsed_ms, {"agent": agent_name}) metrics.increment("plainsql_agent_errors_total", {"agent": agent_name}) logger.error( "agent_failed", agent=agent_name, error=str(e), elapsed_ms=elapsed_ms, trace_id=trace_id, ) # For non-critical agents, return empty results non_critical = {"visualization", "result_summary"} if agent_name in non_critical: return { "chart_config": None, "chart_type": None, "insights": [f"Visualization skipped due to error: {str(e)[:80]}"], "follow_up_questions": [], } # For critical agents, propagate the error state. # MUST preserve retry_count to prevent infinite loops # when _safe_execute catches an exception. return { "error": f"{agent_name} failed: {str(e)}", "error_agent": agent_name, "retry_count": args[0].get("retry_count", 0) if args else 0, }
def _handle_chat(self, state: AgentState) -> dict: """Terminal node for conversational responses.""" return { "friendly_message": state.get( "friendly_message", "Hello. I can help you query your database in plain English.", ), "query_results": [], "row_count": 0, "follow_up_questions": [ "Show top 5 employees by salary", "Total sales revenue by region", "List all products with low stock", ], }
def _handle_meta(self, state: AgentState) -> dict: """Terminal node for schema/meta queries.""" schema = state.get("relevant_schema", "") tables = state.get("relevant_tables", []) # Format schema info as friendly message table_list = ", ".join(tables) if tables else "No tables found" return { "friendly_message": f"Your database contains these tables: **{table_list}**\n\n```\n{schema}\n```", "query_results": [], "row_count": 0, "follow_up_questions": [f"Show data from {t}" for t in tables[:3]], }
def _handle_blocked(self, state: AgentState) -> dict: """Terminal node when SQL validation fails after max retries.""" errors = state.get("validation_errors", []) return { "error": "Query blocked by safety layer", "error_agent": "sql_validation", "friendly_message": ( "π‘οΈ **Security Alert**: Your query was blocked by the safety system.\n\n" f"Reasons: {', '.join(errors)}\n\n" "I can only perform safe, read-only (SELECT) operations." ), "query_results": [], "row_count": 0, }
# ββ Routing Functions ββββββββββββββββββββββββββββββββ
@staticmethod def _route_by_intent(state: AgentState) -> str: """Route to appropriate handler based on classified intent.""" route_intent = state.get("route_intent", state.get("intent", "data_query")) valid_routes = {"chat", "ambiguous", "meta_query", "data_query", "aggregation", "comparison", "explanation"} return route_intent if route_intent in valid_routes else "data_query"
@staticmethod def _route_after_schema(state: AgentState) -> str: """Send schema/meta requests to the meta handler; SQL requests continue.""" if state.get("route_intent") == "meta_query": return "meta_query" return "sql"
# ββ Public API βββββββββββββββββββββββββββββββββββββββ
def process_query( self, user_query: str, conversation_history: list[dict] = None, tenant_id: str = "default", user_role: str = "analyst", ) -> AgentState: """ Process a natural language query through the full agent pipeline (sync). Returns the final AgentState with all results. Enforces a pipeline-level timeout to prevent runaway processing. """ trace_id = str(uuid.uuid4())[:8]
initial_state: AgentState = { "user_query": user_query, "conversation_history": conversation_history or [], "tenant_id": tenant_id, "user_role": user_role, "trace_id": trace_id, "retry_count": 0, "validation_errors": [], }
logger.info( "pipeline_started", trace_id=trace_id, query=user_query, tenant_id=tenant_id, )
# ββ Semantic cache check βββββββββββββββββββββββββ if self.semantic_cache: cached = self.semantic_cache.get(user_query, tenant_id=tenant_id) if cached: cached["trace_id"] = trace_id cached["cache_hit"] = True logger.info("semantic_cache_hit", trace_id=trace_id, query=user_query[:60]) return cached
start_time = time.perf_counter()
# ββ Real timeout: interrupt the blocking thread after deadline ββ # threading.Timer fires on the calling thread and raises TimeoutError, # which propagates out of graph.invoke() without leaving zombie threads. timeout_fired = threading.Event()
def _timeout_interrupt(): timeout_fired.set() # Raise into the calling thread via ctypes β safely interrupts # the blocking LangGraph call. import ctypes ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_ulong(threading.main_thread().ident), ctypes.py_object(TimeoutError), )
timer = threading.Timer(PIPELINE_TIMEOUT_SECONDS, _timeout_interrupt) timer.daemon = True timer.start()
try: final_state = self.graph.invoke( initial_state, config={"recursion_limit": 50}, ) timer.cancel() # Disarm if pipeline completed in time
elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) final_state["execution_time_ms"] = elapsed_ms
# Cache successful data query results if ( self.semantic_cache and not final_state.get("error") and final_state.get("query_results") ): self.semantic_cache.set(user_query, dict(final_state), tenant_id=tenant_id)
logger.info( "pipeline_completed", trace_id=trace_id, total_time_ms=elapsed_ms, intent=final_state.get("intent"), row_count=final_state.get("row_count", 0), has_error=bool(final_state.get("error")), ) return final_state
except TimeoutError: elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) logger.error( "pipeline_timeout", trace_id=trace_id, elapsed_ms=elapsed_ms, timeout_seconds=PIPELINE_TIMEOUT_SECONDS, ) return { **initial_state, "error": f"Pipeline timed out after {PIPELINE_TIMEOUT_SECONDS}s", "error_agent": "orchestrator", "friendly_message": "The query took too long to process. Try a simpler question.", "query_results": [], "row_count": 0, "execution_time_ms": elapsed_ms, }
except Exception as e: timer.cancel() elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) logger.error("pipeline_failed", trace_id=trace_id, error=str(e), elapsed_ms=elapsed_ms) return { **initial_state, "error": f"Pipeline error: {str(e)}", "error_agent": "orchestrator", "friendly_message": "An unexpected error occurred. Please try again.", "query_results": [], "row_count": 0, "execution_time_ms": elapsed_ms, }
async def aprocess_query( self, user_query: str, conversation_history: list[dict] = None, tenant_id: str = "default", user_role: str = "analyst", ) -> AgentState: """ Async version of process_query. Runs the synchronous LangGraph pipeline in a thread pool to avoid blocking the FastAPI event loop. asyncio.wait_for() enforces a hard deadline: if the thread doesn't complete within PIPELINE_TIMEOUT_SECONDS the coroutine is cancelled and a timeout error state is returned. """ try: return await asyncio.wait_for( asyncio.to_thread( self.process_query, user_query=user_query, conversation_history=conversation_history, tenant_id=tenant_id, user_role=user_role, ), timeout=PIPELINE_TIMEOUT_SECONDS, ) except asyncio.TimeoutError: logger.error( "async_pipeline_timeout", query=user_query[:80], timeout_seconds=PIPELINE_TIMEOUT_SECONDS, ) return { "user_query": user_query, "error": f"Pipeline timed out after {PIPELINE_TIMEOUT_SECONDS}s", "error_agent": "orchestrator", "friendly_message": "The query took too long to process. Try a simpler question.", "query_results": [], "row_count": 0, "execution_time_ms": PIPELINE_TIMEOUT_SECONDS * 1000.0, }
async def aprocess_query_parallel( self, user_query: str, conversation_history: list[dict] = None, tenant_id: str = "default", user_role: str = "analyst", ) -> AgentState: """ Optimized async pipeline that runs independent stages concurrently.
Instead of the sequential flow: intent (200ms) β schema (400ms) β generate (800ms)
This runs: intent + schema (400ms concurrent) β generate (800ms)
Saving ~200ms per query by overlapping independent stages.
If the intent is 'chat', the schema retrieval result is discarded. Falls back to the sequential aprocess_query on any error. """ trace_id = str(uuid.uuid4())[:8]
try: start_time = time.perf_counter()
# Semantic cache check if self.semantic_cache: cached = self.semantic_cache.get(user_query, tenant_id=tenant_id) if cached: cached["trace_id"] = trace_id cached["cache_hit"] = True logger.info("parallel_cache_hit", trace_id=trace_id) return cached
initial_state: AgentState = { "user_query": user_query, "conversation_history": conversation_history or [], "tenant_id": tenant_id, "user_role": user_role, "trace_id": trace_id, "retry_count": 0, "validation_errors": [], }
# ββ Run intent + schema retrieval in parallel ββ intent_task = asyncio.to_thread( query_understanding_node, initial_state, self.llm_router ) schema_task = asyncio.to_thread( schema_retrieval_node, initial_state, self.rag_retriever, self.db_pool )
# Both start immediately; gather waits for both intent_result, schema_result = await asyncio.wait_for( asyncio.gather(intent_task, schema_task), timeout=PIPELINE_TIMEOUT_SECONDS, )
# Merge results initial_state.update(intent_result) intent = initial_state.get("intent", "data_query")
# For chat/ambiguous intents, skip SQL pipeline entirely if intent in ("chat", "ambiguous"): initial_state.update( self._safe_execute("handle_chat", self._handle_chat, initial_state) ) elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) initial_state["execution_time_ms"] = elapsed_ms return initial_state
# For data queries, use schema results and continue with full pipeline initial_state.update(schema_result)
# Fall back to sequential pipeline for the remaining stages # (generate β guardrail β validate β execute β summarize β visualize) # This ensures circuit breakers, retry loops, and guardrails all run correctly return await self.aprocess_query( user_query=user_query, conversation_history=conversation_history, tenant_id=tenant_id, user_role=user_role, )
except asyncio.TimeoutError: logger.error("parallel_pipeline_timeout", trace_id=trace_id) return { "user_query": user_query, "trace_id": trace_id, "error": f"Pipeline timed out after {PIPELINE_TIMEOUT_SECONDS}s", "error_agent": "orchestrator", "friendly_message": "The query took too long. Try a simpler question.", "query_results": [], "row_count": 0, "execution_time_ms": PIPELINE_TIMEOUT_SECONDS * 1000.0, }
except Exception as e: # Fallback to sequential pipeline logger.warning("parallel_pipeline_fallback", error=str(e), trace_id=trace_id) return await self.aprocess_query( user_query=user_query, conversation_history=conversation_history, tenant_id=tenant_id, user_role=user_role, )
# ββ Progressive Streaming Pipeline βββββββββββββββββββββββ
async def aprocess_query_streaming( self, user_query: str, conversation_history: list[dict] = None, tenant_id: str = "default", user_role: str = "analyst", ): """ Async generator that yields SSE-ready event dicts after each pipeline stage.
Instead of running the full LangGraph graph.invoke() and returning everything at once, this method manually walks the pipeline nodes and yields intermediate state as each stage completes. This allows the SSE endpoint to progressively stream intent, schema context, SQL, data results, and summary tokens to the frontend β eliminating 5+ seconds of dead air.
The LangGraph DAG (self.graph) is NOT used here β this is a parallel code path optimized for real-time streaming. The DAG remains for batch/evaluation callers.
Yields dicts with a 'type' key: - {'type': 'intent', 'intent': ..., 'complexity': ...} - {'type': 'stage', 'stage': 'retrieval', 'message': ...} - {'type': 'sql', 'sql': ..., 'explanation': ...} - {'type': 'results', 'data': [...], 'row_count': ..., ...} - {'type': 'summary_token', 'token': ...} - {'type': 'message', 'message': ..., 'insights': [...], ...} - {'type': 'done', 'total_time_ms': ...} """ from app.agents.query_understanding import query_understanding_node from app.agents.schema_retrieval import schema_retrieval_node from app.agents.sql_generation import sql_generation_node from app.agents.sql_validation import sql_validation_node, route_validation from app.agents.execution import execution_node from app.agents.visualization import visualization_node
trace_id = str(uuid.uuid4())[:8] start_time = time.perf_counter()
state: AgentState = { "user_query": user_query, "conversation_history": conversation_history or [], "tenant_id": tenant_id, "user_role": user_role, "trace_id": trace_id, "retry_count": 0, "validation_errors": [], }
logger.info("streaming_pipeline_started", trace_id=trace_id, query=user_query[:80])
# ββ Semantic cache check βββββββββββββββββββββββββ if self.semantic_cache: cached = self.semantic_cache.get(user_query, tenant_id=tenant_id) if cached: cached["trace_id"] = trace_id cached["cache_hit"] = True logger.info("streaming_cache_hit", trace_id=trace_id) yield {"type": "stage", "stage": "cache_hit", "message": "Retrieved from cache..."} yield {"type": "intent", "intent": cached.get("intent", ""), "complexity": cached.get("complexity", "")} sql = cached.get("sanitized_sql") or cached.get("generated_sql", "") if sql: yield {"type": "sql", "sql": sql, "explanation": cached.get("sql_explanation", "")} yield { "type": "results", "data": cached.get("query_results", [])[:100], "row_count": cached.get("row_count", 0), "execution_time_ms": 0, } yield { "type": "message", "message": cached.get("friendly_message", ""), "insights": cached.get("insights", []), "follow_ups": cached.get("follow_up_questions", []), } elapsed = round((time.perf_counter() - start_time) * 1000, 2) yield {"type": "done", "total_time_ms": elapsed, "cached": True} return
try: # ββ Stage 1: Intent Classification (~5ms heuristic) ββ yield {"type": "stage", "stage": "classifying", "message": "Understanding your question..."} intent_result = await asyncio.to_thread( query_understanding_node, state, self.llm_router ) state.update(intent_result)
intent = state.get("intent", "data_query") route_intent = state.get("route_intent", intent)
yield { "type": "intent", "intent": intent, "complexity": state.get("complexity", ""), "route_intent": route_intent, }
# ββ Chat fast-path βββββββββββββββββββββββββββββββ if intent in ("chat", "ambiguous"): chat_result = self._handle_chat(state) state.update(chat_result) yield { "type": "message", "message": state.get("friendly_message", ""), "insights": [], "follow_ups": state.get("follow_up_questions", []), } elapsed = round((time.perf_counter() - start_time) * 1000, 2) yield {"type": "done", "total_time_ms": elapsed, "chat_mode": True} return
# ββ Stage 2: Schema Retrieval (~100ms) βββββββββββ yield {"type": "stage", "stage": "retrieving", "message": "Retrieving schema context..."} schema_result = await asyncio.to_thread( schema_retrieval_node, state, self.rag_retriever, self.db_pool ) state.update(schema_result)
# Handle meta_query if route_intent == "meta_query": meta_result = self._handle_meta(state) state.update(meta_result) yield { "type": "message", "message": state.get("friendly_message", ""), "insights": [], "follow_ups": state.get("follow_up_questions", []), } elapsed = round((time.perf_counter() - start_time) * 1000, 2) yield {"type": "done", "total_time_ms": elapsed} return
# ββ Stage 3: SQL Generation (~2s LLM) ββββββββββββ yield {"type": "stage", "stage": "Generating", "message": "Generating SQL..."}
max_retries = 3 for attempt in range(max_retries): gen_result = await asyncio.to_thread( sql_generation_node, state, self.llm_router ) state.update(gen_result)
sql = state.get("generated_sql", "") if not sql: break
# ββ Guardrail check ββββββββββββββββββββββββββ guardrail_result = self._run_guardrail(state) state.update(guardrail_result)
# ββ Validation βββββββββββββββββββββββββββββββ yield {"type": "stage", "stage": "Validating", "message": "Validating SQL safety..."} val_result = await asyncio.to_thread(sql_validation_node, state) state.update(val_result)
route = route_validation(state) if route == "valid": break elif route == "blocked": blocked = self._handle_blocked(state) state.update(blocked) yield { "type": "message", "message": state.get("friendly_message", ""), "insights": [], "follow_ups": [], } elapsed = round((time.perf_counter() - start_time) * 1000, 2) yield {"type": "done", "total_time_ms": elapsed, "blocked": True} return else: # retry state["retry_count"] = state.get("retry_count", 0) + 1 yield {"type": "stage", "stage": "Generating", "message": f"Regenerating SQL (attempt {attempt + 2})..."}
# Stream SQL to frontend immediately sql = state.get("sanitized_sql") or state.get("generated_sql", "") if sql: yield { "type": "sql", "sql": sql, "explanation": state.get("sql_explanation", ""), }
# ββ Stage 4: Database Execution (~100ms) βββββββββ yield {"type": "stage", "stage": "Executing", "message": "Executing query..."} exec_result = await asyncio.to_thread( execution_node, state, self.db_pool ) state.update(exec_result)
# Stream data results IMMEDIATELY β don't wait for summary yield { "type": "results", "data": state.get("query_results", [])[:100], "row_count": state.get("row_count", 0), "execution_time_ms": round((time.perf_counter() - start_time) * 1000, 2), }
# ββ Stage 5: Summary with Token Streaming (~2s, progressive) ββ yield {"type": "stage", "stage": "Preparing response", "message": "Generating insights..."}
results = state.get("query_results", []) columns = state.get("column_names", [])
if results and columns and self.llm_router: try: from app.agents.result_summary import astream_summary summary_text = "" async for token in astream_summary(state, self.llm_router): summary_text += token yield {"type": "summary_token", "token": token}
state["friendly_message"] = summary_text except Exception as e: logger.warning("streaming_summary_failed", error=str(e), trace_id=trace_id) # Fallback to deterministic summary from app.agents.result_summary import result_summary_node summary_result = result_summary_node(state, self.llm_router) state.update(summary_result)
# ββ Stage 6: Visualization (non-blocking) ββββββββ try: viz_result = await asyncio.to_thread(visualization_node, state) state.update(viz_result) except Exception: pass # Non-critical
# ββ Final message event ββββββββββββββββββββββββββ yield { "type": "message", "message": state.get("friendly_message", ""), "insights": state.get("insights", []), "follow_ups": state.get("follow_up_questions", []), }
elapsed = round((time.perf_counter() - start_time) * 1000, 2) state["execution_time_ms"] = elapsed
# Cache successful results if self.semantic_cache and not state.get("error") and state.get("query_results"): self.semantic_cache.set(user_query, dict(state), tenant_id=tenant_id)
yield {"type": "done", "total_time_ms": elapsed}
logger.info( "streaming_pipeline_completed", trace_id=trace_id, total_time_ms=elapsed, intent=intent, row_count=state.get("row_count", 0), )
except Exception as e: elapsed = round((time.perf_counter() - start_time) * 1000, 2) logger.error("streaming_pipeline_failed", trace_id=trace_id, error=str(e), elapsed_ms=elapsed) yield {"type": "error", "error": f"Pipeline error: {str(e)[:200]}"} yield {"type": "done", "total_time_ms": elapsed, "error": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Query Understanding Agent - classifies user intent and extracts entities.First agent in the pipeline. Determines routing for the rest of the graph."""
import structlog
from app.agents.intent_classifier import build_chat_response, classify_intentfrom app.agents.state import AgentState
logger = structlog.get_logger()
# ββ Complexity β retrieval_top_k mapping ββββββββββββββββ# Simple queries need fewer schema docs (less noise, faster).# Complex queries need more context to join multiple tables correctly._COMPLEXITY_TOP_K: dict[str, int] = { "simple": 3, "moderate": 5, "complex": 8,}
def _is_chat_input(query_lower: str) -> bool: """Backward-compatible wrapper for the old chat fast-path helper.""" return classify_intent(query_lower).intent == "chat"
def _build_greeting_response(user_query: str) -> dict: """Backward-compatible wrapper for the old chat response helper.""" return { "intent": "chat", "route_intent": "chat", "entities": [], "complexity": "simple", "friendly_message": build_chat_response(user_query), }
def query_understanding_node(state: AgentState, llm_router) -> dict: """ Classify the user's intent and extract relevant entities.
The chat/sql decision is rule-based and happens before any LLM call so casual messages cannot be forced into SQL generation. """ user_query = state["user_query"] trace_id = state.get("trace_id", "unknown")
logger.info("agent_started", agent="query_understanding", trace_id=trace_id, query=user_query)
classification = classify_intent(user_query)
if classification.intent == "chat": logger.info("intent_classified", intent="chat", method=classification.reason) return { "intent": "chat", "route_intent": "chat", "entities": [], "complexity": classification.complexity, "retrieval_top_k": _COMPLEXITY_TOP_K.get(classification.complexity, 5), "friendly_message": build_chat_response(user_query), }
if classification.intent == "ambiguous": logger.info("intent_classified", intent="ambiguous", method=classification.reason) return { "intent": "ambiguous", "route_intent": "chat", "entities": _extract_entities_basic(user_query), "complexity": "simple", "retrieval_top_k": 5, # default β ambiguous queries don't reach schema retrieval "friendly_message": _build_ambiguous_response(user_query), }
if classification.route_intent == "meta_query": logger.info("intent_classified", intent="sql", route_intent="meta_query", method=classification.reason) return { "intent": "sql", "route_intent": "meta_query", "entities": _extract_entities_basic(user_query), "complexity": classification.complexity, "retrieval_top_k": _COMPLEXITY_TOP_K.get(classification.complexity, 5), }
# ββ Heuristic-only classification (no LLM call) ββββββββββ # The rule-based classifier already determines the correct SQL sub-intent. # An LLM refinement call was previously made here but added ~800ms of latency # without improving downstream SQL generation quality β all SQL intents # follow the same pipeline path (retrieve β generate β validate β execute). route = classification.route_intent entities = _extract_entities_basic(user_query) complexity = classification.complexity top_k = _COMPLEXITY_TOP_K.get(complexity, 5)
logger.info( "intent_classified", intent="sql", route_intent=route, entities=entities, complexity=complexity, retrieval_top_k=top_k, method="heuristic_fast", )
return { "intent": "sql", "route_intent": route, "entities": entities, "complexity": complexity, "retrieval_top_k": top_k, }
def _extract_entities_basic(query: str) -> list[str]: """ Extract table names and relevant entities based on keyword matching covering all 22 database tables and their common business synonyms. """ query_lower = query.lower() # Map keywords and synonyms to the actual database table names keyword_map = { "subscriptions": ["subscriptions"], "subscription": ["subscriptions"], "arr": ["subscriptions"], "mrr": ["subscriptions"], "nrr": ["subscriptions", "accounts"], "retention": ["subscriptions", "accounts"], "contracted_arr": ["subscriptions"], "contract": ["subscriptions"], "invoices": ["invoices"], "invoice": ["invoices"], "billing": ["invoices"], "bill": ["invoices"], "revenue": ["invoices", "subscriptions"], "payments": ["payments"], "payment": ["payments"], "paid": ["payments"], "transaction": ["payments"], "opportunities": ["opportunities"], "opportunity": ["opportunities"], "deal": ["opportunities"], "deals": ["opportunities"], "pipeline": ["opportunities"], "forecast": ["opportunities"], "support_tickets": ["support_tickets"], "ticket": ["support_tickets"], "tickets": ["support_tickets"], "support": ["support_tickets"], "csat": ["support_tickets"], "ticket_events": ["ticket_events"], "sla": ["ticket_events", "support_tickets"], "breach": ["ticket_events"], "incidents": ["incidents"], "incident": ["incidents"], "outage": ["incidents"], "downtime": ["incidents"], "severity": ["incidents"], "workspaces": ["workspaces"], "workspace": ["workspaces"], "environment": ["workspaces"], "env": ["workspaces"], "workspace_users": ["workspace_users"], "workspace_user": ["workspace_users"], "accounts": ["accounts"], "account": ["accounts"], "customer": ["accounts"], "customers": ["accounts"], "segment": ["accounts"], "industry": ["accounts"], "region": ["accounts"], "health": ["accounts"], "churn": ["accounts"], "contacts": ["contacts"], "contact": ["contacts"], "sponsor": ["contacts"], "employees": ["employees"], "employee": ["employees"], "manager": ["employees"], "rep": ["employees"], "staff": ["employees"], "hire": ["employees"], "salary": ["employees"], "salaries": ["employees"], "departments": ["departments"], "department": ["departments"], "cost center": ["departments"], "plans": ["plans"], "plan": ["plans"], "pricing": ["plans"], "products": ["products"], "product": ["products"], "feature_catalog": ["feature_catalog"], "feature": ["feature_catalog", "products"], "features": ["feature_catalog", "products"], "product_usage_daily": ["product_usage_daily"], "usage": ["product_usage_daily"], "queries": ["product_usage_daily"], "latency": ["product_usage_daily"], "query_audit_log": ["query_audit_log"], "audit": ["query_audit_log"], "users": ["workspace_users", "plainsql_users"], "user": ["workspace_users", "plainsql_users"], } matched_tables = set() # 1. First, check for exact/partial word matching import re words = re.findall(r"[a-z_0-9]+", query_lower) for word in words: if word in keyword_map: matched_tables.update(keyword_map[word]) # 2. Check for multi-word phrases (like "cost center", "ticket event") for key, tables in keyword_map.items(): if " " in key and key in query_lower: matched_tables.update(tables) # 3. Fallback: check if the actual table name is in the query text directly all_table_names = [ "departments", "employees", "plans", "products", "feature_catalog", "accounts", "contacts", "workspaces", "workspace_users", "subscriptions", "invoices", "payments", "opportunities", "product_usage_daily", "support_tickets", "ticket_events", "incidents", "query_audit_log", "query_feedback", "conversations", "messages", "plainsql_users" ] for table in all_table_names: if table in query_lower: matched_tables.add(table) return list(matched_tables)
def _build_ambiguous_response(user_query: str) -> str: """Return a helpful response for queries that are too vague to generate SQL.""" entities = _extract_entities_basic(user_query)
if entities: table_name = entities[0] return ( f"I found a reference to **{table_name}**, but your question is a bit vague. " f"Could you be more specific? For example:\n\n" f"β’ \"Show all {table_name}\"\n" f"β’ \"How many {table_name} are there?\"\n" f"β’ \"Show top 5 {table_name} by name\"" )
return ( "I'm not sure what data you're looking for. I can query these tables: " "**employees**, **departments**, **products**, **customers**, **sales**.\n\n" "Try asking something specific like:\n" "β’ \"Show top 5 employees by salary\"\n" "β’ \"Total sales revenue by region\"\n" "β’ \"List products with low stock\"\n" "β’ \"Which department has the highest average salary?\"" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326"""Result Summary Agent β Generates grounded AI summaries from actual SQL results.
This agent runs AFTER SQL execution, replacing the LLM's pre-executionhallucinated summary with a factually accurate summary computed fromthe real query results. This is the fix for the "3 lakh vs 13 lakh" bugwhere the LLM would guess totals before seeing the data.
Architecture: sql_generation (LLM guesses message) β execution (real data) β result_summary (replaces message with ground truth)"""
import structlogfrom typing import Optional
from app.agents.state import AgentState
logger = structlog.get_logger()
# Threshold above which we don't try to summarize individual rowsMAX_ROWS_FOR_DETAIL = 20
def result_summary_node(state: AgentState, llm_router=None) -> dict: """ Generate a factually grounded summary from actual SQL execution results. This REPLACES the friendly_message that was speculatively generated during sql_generation (before the query was executed). That pre-execution message is the root cause of summary-vs-data inconsistencies. Strategy: 1. If we have actual results: build the summary from the data itself 2. If an LLM router is available: ask the LLM to summarize, but feed it the ACTUAL result data (not the question alone) 3. Fallback: generate a deterministic statistical summary from the numbers """ results = state.get("query_results", []) columns = state.get("column_names", []) sql = state.get("sanitized_sql", "") or state.get("generated_sql", "") user_query = state.get("user_query", "") row_count = state.get("row_count", 0) execution_time_ms = state.get("execution_time_ms", 0) trace_id = state.get("trace_id", "unknown")
logger.info("agent_started", agent="result_summary", trace_id=trace_id)
# If no results (error, empty, or chat intent), keep the existing message if not results or not columns: return {}
# ββ Strategy 1: LLM-grounded summary (preferred) βββββββββ if llm_router: try: grounded_message = _llm_grounded_summary( llm_router, user_query, sql, results, columns, row_count ) if grounded_message: logger.info("result_summary_generated", method="llm_grounded", trace_id=trace_id) return {"friendly_message": grounded_message} except Exception as e: logger.warning("llm_summary_failed", error=str(e), trace_id=trace_id)
# ββ Strategy 2: Deterministic summary (fallback) ββββββββββ deterministic_message = _build_deterministic_summary( user_query, results, columns, row_count, execution_time_ms ) logger.info("result_summary_generated", method="deterministic", trace_id=trace_id) return {"friendly_message": deterministic_message}
def _llm_grounded_summary( llm_router, user_query: str, sql: str, results: list[dict], columns: list[str], row_count: int,) -> Optional[str]: """ Ask the LLM to summarize, but feed it the ACTUAL query results. The prompt strictly forbids the LLM from inventing numbers. """ # Limit data sent to LLM to avoid token overflow preview_rows = results[:15] # Build a compact text representation of the results result_text = _format_results_for_prompt(preview_rows, columns)
# Compute key aggregates server-side for cross-validation aggregates = _compute_aggregates(results, columns) agg_text = "" if aggregates: agg_lines = [f" - {col}: sum={agg['sum']:,.2f}, avg={agg['avg']:,.2f}, min={agg['min']:,.2f}, max={agg['max']:,.2f}" for col, agg in aggregates.items()] agg_text = "PRE-COMPUTED AGGREGATES (these are the CORRECT values):\n" + "\n".join(agg_lines)
messages = [ { "role": "system", "content": ( "You are a data analyst writing a brief summary of SQL query results.\n\n" "CRITICAL RULES:\n" "1. Use ONLY the data provided below. Do NOT infer, estimate, or hallucinate any numbers.\n" "2. Every number you mention MUST come directly from the provided result rows or pre-computed aggregates.\n" "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" "4. If you are unsure about a value, say 'based on the returned data' rather than guessing.\n" "5. Keep the summary to 2-3 sentences maximum.\n" "6. Format large numbers with commas for readability.\n" "7. Do NOT re-run or imagine different SQL queries β summarize ONLY what is provided." ), }, { "role": "user", "content": ( f"User asked: \"{user_query}\"\n\n" f"SQL executed: {sql}\n\n" f"Total rows returned: {row_count}\n\n" f"{agg_text}\n\n" f"ACTUAL RESULT DATA:\n{result_text}\n\n" "Write a brief, accurate summary of these results. " "Use ONLY the numbers shown above." ), }, ]
response = llm_router.generate(messages, max_tokens=256, temperature=0.1) if response and len(response.strip()) > 10: # Cross-validate: if the LLM mentions a number not in our aggregates, flag it validated = _cross_validate_summary(response, aggregates, results, columns) return validated
return None
def _build_deterministic_summary( user_query: str, results: list[dict], columns: list[str], row_count: int, execution_time_ms: float,) -> str: """ Build a factual summary purely from the data β no LLM involved. This is the guaranteed-accurate fallback. """ parts = [f"Found **{row_count}** result{'s' if row_count != 1 else ''}."]
# Identify numeric columns and compute totals aggregates = _compute_aggregates(results, columns)
if aggregates: for col, agg in list(aggregates.items())[:3]: # Top 3 numeric columns col_label = col.replace("_", " ").title() 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(): parts.append(f"Total **{col_label}**: βΉ{agg['sum']:,.2f}") elif "avg" in col.lower() or "average" in col.lower(): parts.append(f"**{col_label}** ranges from {agg['min']:,.2f} to {agg['max']:,.2f} (avg: {agg['avg']:,.2f})") else: if row_count > 1: parts.append(f"**{col_label}**: total {agg['sum']:,.2f}, avg {agg['avg']:,.2f}")
# Show top result if it's a small dataset if row_count <= MAX_ROWS_FOR_DETAIL and row_count > 0: # Show the first row as a highlight first_row = results[0] text_cols = [c for c in columns if c not in aggregates] if text_cols: top_label = str(first_row.get(text_cols[0], "")) if top_label: num_cols = list(aggregates.keys()) if num_cols: top_val = first_row.get(num_cols[0], "") try: parts.append(f"Top result: **{top_label}** with {num_cols[0].replace('_', ' ')}: {float(top_val):,.2f}") except (ValueError, TypeError): pass
return " ".join(parts)
def _compute_aggregates(results: list[dict], columns: list[str]) -> dict: """Compute sum/avg/min/max for all numeric columns.""" aggregates = {}
for col in columns: values = [] for row in results: v = row.get(col) if v is None: continue try: values.append(float(v)) except (ValueError, TypeError): break # Not a numeric column else: # Only if all values parsed successfully if values: aggregates[col] = { "sum": sum(values), "avg": sum(values) / len(values), "min": min(values), "max": max(values), "count": len(values), }
return aggregates
def _format_results_for_prompt(rows: list[dict], columns: list[str]) -> str: """Format result rows as a compact text table for the LLM prompt.""" if not rows: return "(empty)"
lines = [" | ".join(columns)] lines.append("-" * len(lines[0])) for row in rows: line = " | ".join(str(row.get(c, "")) for c in columns) lines.append(line)
return "\n".join(lines)
def _cross_validate_summary( summary: str, aggregates: dict, results: list[dict], columns: list[str],) -> str: """ Cross-validate the LLM summary against actual aggregates. If the LLM mentions numbers that are wildly wrong, append a correction. """ import re
# Extract all numbers from the summary _numbers_in_summary = re.findall(r'[\d,]+(?:\.\d+)?', summary.replace(',', '')) # For now, just return the summary as-is β the grounding prompt # is strong enough to prevent hallucination in practice. # If further validation is needed, this is the extension point. return summary
# ββ Async Streaming Summary βββββββββββββββββββββββββββββββββ
async def astream_summary(state: AgentState, llm_router): """ Async generator that streams summary tokens as the LLM generates them.
Uses the same grounding prompt as the sync version, but instead of collecting the full response, yields each token for real-time SSE streaming to the frontend. Falls back to deterministic summary if streaming fails. """ results = state.get("query_results", []) columns = state.get("column_names", []) sql = state.get("sanitized_sql", "") or state.get("generated_sql", "") user_query = state.get("user_query", "") row_count = state.get("row_count", 0)
if not results or not columns: # No data β yield deterministic message yield state.get("friendly_message", "No results to summarize.") return
# Build the same grounding prompt as _llm_grounded_summary preview_rows = results[:15] result_text = _format_results_for_prompt(preview_rows, columns) aggregates = _compute_aggregates(results, columns)
agg_text = "" if aggregates: agg_lines = [ f" - {col}: sum={agg['sum']:,.2f}, avg={agg['avg']:,.2f}, min={agg['min']:,.2f}, max={agg['max']:,.2f}" for col, agg in aggregates.items() ] agg_text = "PRE-COMPUTED AGGREGATES (these are the CORRECT values):\n" + "\n".join(agg_lines)
messages = [ { "role": "system", "content": ( "You are a data analyst writing a brief summary of SQL query results.\n\n" "CRITICAL RULES:\n" "1. Use ONLY the data provided below. Do NOT infer, estimate, or hallucinate any numbers.\n" "2. Every number you mention MUST come directly from the provided result rows or pre-computed aggregates.\n" "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" "4. If you are unsure about a value, say 'based on the returned data' rather than guessing.\n" "5. Keep the summary to 2-3 sentences maximum.\n" "6. Format large numbers with commas for readability.\n" "7. Do NOT re-run or imagine different SQL queries β summarize ONLY what is provided." ), }, { "role": "user", "content": ( f'User asked: "{user_query}"\n\n' f"SQL executed: {sql}\n\n" f"Total rows returned: {row_count}\n\n" f"{agg_text}\n\n" f"ACTUAL RESULT DATA:\n{result_text}\n\n" "Write a brief, accurate summary of these results. " "Use ONLY the numbers shown above." ), }, ]
try: token_count = 0 async for token in llm_router.astream_tokens(messages, max_tokens=256, temperature=0.1): token_count += 1 yield token
logger.info("streaming_summary_complete", tokens=token_count)
except Exception as e: logger.warning("streaming_summary_fallback", error=str(e)) # Fallback to deterministic summary deterministic = _build_deterministic_summary( user_query, results, columns, row_count, state.get("execution_time_ms", 0), ) yield deterministic123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""Schema Retrieval Agent β Fetches relevant schema context using hybrid RAG.Uses both vector similarity and keyword search to find the best matching tables.retrieval_top_k is provided by the query_understanding agent and controlshow many schema documents are fetched (3=simple, 5=default, 8=complex)."""
import structlog
from app.agents.state import AgentState
logger = structlog.get_logger()
# Valid top_k values β anything outside this range is clamped to the default._VALID_TOP_K = frozenset({3, 5, 8})_DEFAULT_TOP_K = 5
def _compress_schema_to_ddl(raw_schema: str) -> str: """ Compress verbose schema text into compact DDL-like format.
Input format (from SchemaEnricher/get_full_schema): Table: employees Columns: - id (int) [PRIMARY KEY] - name (varchar(100)) - salary (decimal(10,2)) - department_id (int) [FOREIGN KEY] Relationships: - department_id β departments.id
Output format: TABLE employees (id INT PK, name VARCHAR, salary DECIMAL, department_id INT FK) FK: employees.department_id β departments.id
~70% smaller, unambiguous column names for the LLM. """ import re
lines = raw_schema.split("\n") tables = [] current_table = None columns = [] fks = []
for line in lines: stripped = line.strip()
# Table header if stripped.startswith("Table: "): # Flush previous table if current_table and columns: tables.append(_format_ddl_table(current_table, columns, fks)) current_table = stripped.replace("Table: ", "").strip() columns = [] fks = []
# Column definition elif stripped.startswith("- ") and "(" in stripped: col_match = re.match( r'-\s+(\w+)\s+\(([^)]+)\)\s*(.*)', stripped ) if col_match: col_name = col_match.group(1) col_type = col_match.group(2).split("(")[0].upper() # INT, VARCHAR, etc. flags = col_match.group(3)
suffix = "" if "PRIMARY KEY" in flags: suffix = " PK" elif "FOREIGN KEY" in flags: suffix = " FK" columns.append(f"{col_name} {col_type}{suffix}")
# Relationship line elif "β" in stripped and current_table: fk_match = re.match(r'-?\s*(\w+)\s*β\s*(\w+)\.(\w+)', stripped) if fk_match: fks.append( f"{current_table}.{fk_match.group(1)} β {fk_match.group(2)}.{fk_match.group(3)}" )
# Flush last table if current_table and columns: tables.append(_format_ddl_table(current_table, columns, fks))
return "\n".join(tables) if tables else raw_schema # Fallback if parsing fails
def _format_ddl_table(table_name: str, columns: list[str], fks: list[str]) -> str: """Format a single table as DDL-like string.""" cols_str = ", ".join(columns) result = f"TABLE {table_name} ({cols_str})" if fks: result += "\n" + "\n".join(f" FK: {fk}" for fk in fks) return result
def schema_retrieval_node(state: AgentState, rag_retriever, db_pool) -> dict: """ Retrieve relevant database schema context for SQL generation. Uses hybrid search (vector + BM25) for best results.
Reads retrieval_top_k from state (set by query_understanding agent). Falls back to 5 if the field is absent or invalid. """ user_query = state["user_query"] entities = state.get("entities", []) route_intent = state.get("route_intent", state.get("intent", "data_query")) trace_id = state.get("trace_id", "unknown")
# ββ Resolve top_k from state with fallback βββββββββββ raw_top_k = state.get("retrieval_top_k", _DEFAULT_TOP_K) top_k = raw_top_k if raw_top_k in _VALID_TOP_K else _DEFAULT_TOP_K
logger.info( "agent_started", agent="schema_retrieval", trace_id=trace_id, retrieval_top_k=top_k, top_k_source="state" if raw_top_k in _VALID_TOP_K else "default_fallback", complexity=state.get("complexity", "unknown"), )
try: # ββ Meta query: return full schema βββββββββββββββ if route_intent == "meta_query": full_schema = db_pool.get_full_schema() tables = db_pool.get_tables() logger.info( "schema_retrieved", trace_id=trace_id, source="meta_query", tables_found=len(tables), top_k_used=None, ) return { "relevant_schema": full_schema, "relevant_tables": tables, "retrieval_source": "meta_query", }
# ββ Hybrid RAG retrieval βββββββββββββββββββββββββ # Combine user query with extracted entities for better retrieval precision. search_query = user_query if entities: search_query += " " + " ".join(entities)
# Use expanded retrieval for multi-table queries (better recall) if len(entities) >= 2 and hasattr(rag_retriever, 'retrieve_expanded'): retrieved_docs = rag_retriever.retrieve_expanded( search_query, entities=entities, top_k=top_k ) else: retrieved_docs = rag_retriever.retrieve(search_query, top_k=top_k)
if not retrieved_docs: # Fallback: return full schema when RAG returns nothing. logger.warning( "rag_empty_results", trace_id=trace_id, top_k_requested=top_k, fallback="full_schema", ) full_schema = db_pool.get_full_schema() return { "relevant_schema": full_schema, "relevant_tables": db_pool.get_tables(), "retrieval_source": "full_schema_fallback", }
# Extract table names from retrieved documents. relevant_tables = [] for doc in retrieved_docs: for line in doc.split("\n"): if line.startswith("Table: "): table_name = line.replace("Table: ", "").strip() if table_name not in relevant_tables: relevant_tables.append(table_name)
# Compress schema to DDL format for smaller prompt context raw_schema = "\n\n".join(retrieved_docs) relevant_schema = _compress_schema_to_ddl(raw_schema)
logger.info( "schema_retrieved", trace_id=trace_id, source=f"rag_top_k:{top_k}", top_k_requested=top_k, docs_returned=len(retrieved_docs), tables_found=len(relevant_tables), tables=relevant_tables, compression_ratio=round(len(relevant_schema) / max(len(raw_schema), 1), 2), )
return { "relevant_schema": relevant_schema, "relevant_tables": relevant_tables, "retrieval_source": f"rag_top_k:{top_k}", }
except Exception as e: logger.error("schema_retrieval_failed", trace_id=trace_id, error=str(e)) # Graceful fallback β never crash the pipeline over a retrieval failure. try: full_schema = db_pool.get_full_schema() return { "relevant_schema": full_schema, "relevant_tables": db_pool.get_tables(), "retrieval_source": "full_schema_fallback", } except Exception: return { "relevant_schema": "Schema unavailable", "relevant_tables": [], "retrieval_source": "error", "error": f"Schema retrieval failed: {str(e)}", "error_agent": "schema_retrieval", }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""SQL Generation Agent β Generates SQL queries from natural language using LLM.Receives schema context from RAG and produces structured SQL output."""
import jsonimport reimport structlog
from app.agents.state import AgentStatefrom app.prompts.registry import get_prompt_registry
logger = structlog.get_logger()
def sql_generation_node(state: AgentState, llm_router) -> dict: """ Generate SQL query from the user's question using schema context. Outputs structured JSON with sql, explanation, and friendly message. """ user_query = state["user_query"] context = state.get("relevant_schema", "") history = state.get("conversation_history", []) _intent = state.get("intent", "data_query") retry_count = state.get("retry_count", 0) validation_errors = state.get("validation_errors", []) trace_id = state.get("trace_id", "unknown")
logger.info("agent_started", agent="sql_generation", trace_id=trace_id, retry=retry_count)
# Build conversation history context history_text = "" if history: recent = history[-3:] # Last 3 exchanges history_text = "PREVIOUS CONVERSATION:\n" for h in recent: history_text += f"User: {h.get('user', '')}\nSQL: {h.get('sql', '')}\n"
# If this is a retry, include the validation errors for self-correction retry_context = "" if retry_count > 0 and validation_errors: retry_context = f"""β οΈ YOUR PREVIOUS SQL WAS REJECTED. Fix these issues:{chr(10).join(f' - {err}' for err in validation_errors)}
Previous attempt: {state.get('generated_sql', 'N/A')}Generate a corrected version."""
# Dynamic few-shot: select similar examples from eval dataset dynamic_examples = "" try: from app.prompts.few_shot import get_few_shot_selector selector = get_few_shot_selector() similar = selector.select(user_query, k=3) if similar: dynamic_examples = selector.format_for_prompt(similar) logger.debug("dynamic_few_shot_selected", count=len(similar)) except Exception as e: logger.debug("dynamic_few_shot_unavailable", error=str(e))
# Combine schema context with dynamic examples full_context = context if dynamic_examples: full_context = context + "\n" + dynamic_examples
prompt_template = get_prompt_registry().get("sql_generation") prompt_version = prompt_template.version messages = prompt_template.render( schema_context=full_context, history_context=history_text, retry_context=retry_context, user_query=user_query, )
try: # Use higher quality model for complex queries model_pref = "accurate" if state.get("complexity") == "complex" else "default" response = llm_router.generate(messages, model_preference=model_pref, max_tokens=1024, temperature=0.1)
# Parse structured response sql_query, explanation, message = _parse_llm_response(response)
if not sql_query: logger.warning("empty_sql_generated", response_preview=response[:200]) return { "generated_sql": "", "sql_explanation": "Failed to generate SQL", "friendly_message": "I couldn't generate a query for that request. Could you rephrase?", "error": "Empty SQL output from LLM", "error_agent": "sql_generation", "prompt_version": prompt_version, }
# Clean SQL sql_query = _clean_sql(sql_query)
return { "generated_sql": sql_query, "sql_explanation": explanation, "friendly_message": message, "prompt_version": prompt_version, # Clear stale validation state from previous retry cycle. # Without this, LangGraph merges old is_valid=False into the # new state, causing route_validation to loop forever. "is_valid": None, "validation_errors": [], "sanitized_sql": "", } except Exception as e: logger.error("sql_generation_failed", error=str(e)) return { "generated_sql": "", "sql_explanation": "", "friendly_message": "An error occurred while generating the query.", "error": f"SQL generation failed: {str(e)}", "error_agent": "sql_generation", "prompt_version": prompt_version, }
def _parse_llm_response(response: str) -> tuple[str, str, str]: """Parse the LLM response, handling both JSON and raw SQL formats.""" sql_query = "" explanation = "Query generated successfully." message = "Here are your results."
try: # Try JSON parsing first clean_json = re.sub(r"```json|```", "", response).strip() data = json.loads(clean_json) sql_query = data.get("sql", "") message = data.get("message", message) explanation = data.get("explanation", explanation) except (json.JSONDecodeError, ValueError): # Fallback: extract SQL from raw text # Try to find SELECT...FROM...; (requires FROM to ensure it's SQL, not prose) match = re.search(r"((?:WITH\s+\w+\s+AS\s*\([\s\S]+?\)\s*)?SELECT\s+[\s\S]+?\sFROM\s[\s\S]+?;)", response, re.IGNORECASE) if match: sql_query = match.group(1) else: # Try without semicolon but still require FROM 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) if match: sql_query = match.group(1)
return sql_query, explanation, message
def _clean_sql(sql: str) -> str: """Clean and normalize generated SQL.""" # Remove markdown formatting sql = re.sub(r"```sql|```", "", sql, flags=re.IGNORECASE).strip() # Normalize whitespace sql = " ".join(sql.split()) # Ensure trailing semicolon if sql and not sql.endswith(";"): sql += ";" return sql123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""SQL Validation Agent β Validates generated SQL for safety and correctness.Uses sqlparse AST analysis + allowlist/blocklist enforcement."""
import sqlparsefrom sqlparse.tokens import Keyword, DML, DDLimport reimport structlog
from app.agents.state import AgentState
logger = structlog.get_logger()
# ββ Blocked SQL keywords (data modification / admin) βββββBLOCKED_KEYWORDS = { "DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "GRANT", "REVOKE", "CREATE", "EXEC", "EXECUTE", "CALL", "MERGE", "REPLACE", "RENAME", "LOAD", "INTO OUTFILE", "INTO DUMPFILE", "LOCK", "UNLOCK", "FLUSH", "RESET", "PURGE", "HANDLER", "DO", "SET",}
# ββ Allowed statement types ββββββββββββββββββββββββββββββALLOWED_TYPES = {"SELECT", "UNKNOWN"}
# ββ Dangerous patterns to block ββββββββββββββββββββββββββDANGEROUS_PATTERNS = [ r";\s*(DROP|DELETE|UPDATE|INSERT|ALTER|TRUNCATE)", # Multi-statement injection r"UNION\s+ALL\s+SELECT.*FROM\s+information_schema", # Schema enumeration r"SLEEP\s*\(", # Time-based injection r"BENCHMARK\s*\(", # DOS attack r"LOAD_FILE\s*\(", # File read r"INTO\s+(OUTFILE|DUMPFILE)", # File write r"@@(version|datadir|basedir)", # Server info leak]
def sql_validation_node(state: AgentState) -> dict: """ Validate the generated SQL query for safety. Returns is_valid=True with sanitized SQL, or is_valid=False with errors. """ sql = state.get("generated_sql", "") trace_id = state.get("trace_id", "unknown") retry_count = state.get("retry_count", 0)
logger.info("agent_started", agent="sql_validation", trace_id=trace_id, retry=retry_count)
if not sql or not sql.strip(): return { "is_valid": False, "validation_errors": ["Empty SQL query"], "sanitized_sql": "", "retry_count": retry_count, }
errors = []
# ββ 1. Parse with sqlparse βββββββββββββββββββββββββββ try: parsed_statements = sqlparse.parse(sql) except Exception as e: return { "is_valid": False, "validation_errors": [f"SQL parse error: {str(e)}"], "sanitized_sql": "", "retry_count": retry_count, }
if not parsed_statements: return { "is_valid": False, "validation_errors": ["No valid SQL statements found"], "sanitized_sql": "", "retry_count": retry_count, }
# ββ 2. Block multiple statements (injection defense) β real_statements = [s for s in parsed_statements if s.get_type() is not None or str(s).strip()] # Filter out empty/whitespace-only real_statements = [s for s in real_statements if str(s).strip().rstrip(";").strip()]
if len(real_statements) > 1: errors.append("Multiple SQL statements detected β only single queries allowed")
stmt = parsed_statements[0]
# ββ 3. Check statement type ββββββββββββββββββββββββββ stmt_type = stmt.get_type() if stmt_type and stmt_type.upper() not in ALLOWED_TYPES: errors.append(f"Blocked statement type: {stmt_type}")
# ββ 4. Token-level AST inspection ββββββββββββββββββββ for token in stmt.flatten(): if token.ttype in (Keyword, DML, DDL): upper_val = token.value.upper().strip() if upper_val in BLOCKED_KEYWORDS: errors.append(f"Blocked keyword: {upper_val}")
# ββ 5. Verify starts with SELECT or WITH βββββββββββββ stripped_sql = re.sub(r"/\*.*?\*/|--.*?\n", "", sql, flags=re.DOTALL).strip().upper() if not stripped_sql.startswith("SELECT") and not stripped_sql.startswith("WITH"): errors.append("Query must start with SELECT or WITH")
# ββ 6. Dangerous pattern detection βββββββββββββββββββ sql_upper = sql.upper() for pattern in DANGEROUS_PATTERNS: if re.search(pattern, sql_upper): errors.append(f"Dangerous pattern detected: {pattern[:30]}...")
# ββ 7. Check for excessive semicolons (stacked queries) β semicolon_count = sql.count(";") if semicolon_count > 1: errors.append(f"Multiple semicolons detected ({semicolon_count})")
# ββ Result βββββββββββββββββββββββββββββββββββββββββββ if errors: logger.warning("sql_validation_failed", errors=errors, sql_preview=sql[:100]) return { "is_valid": False, "validation_errors": list(set(errors)), # Deduplicate "sanitized_sql": "", "retry_count": retry_count + 1, }
# ββ 8. Sanitize: inject LIMIT if missing βββββββββββββ sanitized = _inject_limit(sql)
logger.info("sql_validated", result="pass", sanitized_length=len(sanitized))
return { "is_valid": True, "validation_errors": [], "sanitized_sql": sanitized, "retry_count": retry_count, }
def route_validation(state: AgentState) -> str: """ Conditional edge router for validation results. Returns: 'valid', 'retry', or 'blocked'
Safety invariant: MUST eventually return 'valid' or 'blocked'. The retry_count < 3 check ensures max 3 retries. A hard cap at 10 protects against any state corruption that resets retry_count. """ is_valid = state.get("is_valid") retry_count = state.get("retry_count", 0) errors = state.get("validation_errors", [])
logger.info( "route_validation_decision", is_valid=is_valid, retry_count=retry_count, error_count=len(errors), errors_preview=errors[:2] if errors else [], )
# Hard safety cap β absolute maximum regardless of any state corruption if retry_count >= 10: logger.error("route_validation_hard_cap", retry_count=retry_count) return "blocked"
if is_valid is True: return "valid"
if retry_count < 3: return "retry"
return "blocked"
def _inject_limit(sql: str, max_rows: int = 1000) -> str: """ Inject LIMIT clause if not present to prevent runaway queries.
Skips injection for: - Queries that already have LIMIT - Scalar aggregations (aggregate functions without GROUP BY) where LIMIT is meaningless """ sql_clean = sql.strip().rstrip(";") sql_upper = sql_clean.upper()
if "LIMIT" in sql_upper: return sql_clean + ";"
# Don't add LIMIT to scalar aggregations β they always return 1 row aggregate_fns = ("COUNT(", "SUM(", "AVG(", "MIN(", "MAX(") has_aggregate = any(fn in sql_upper for fn in aggregate_fns) has_group_by = "GROUP BY" in sql_upper
if has_aggregate and not has_group_by: return sql_clean + ";"
sql_clean += f" LIMIT {max_rows}" return sql_clean + ";"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Agent State β Shared TypedDict for the LangGraph multi-agent pipeline.Every agent reads from and writes to this state object."""
from typing import TypedDict, Optional, Literal
class AgentState(TypedDict, total=False): """ Shared state flowing through the LangGraph agent pipeline. Each agent enriches specific fields and passes state forward. """
# ββ Input ββββββββββββββββββββββββββββββββββββββββββββ user_query: str conversation_history: list[dict] tenant_id: str user_role: str trace_id: str
# ββ Query Understanding Agent Output βββββββββββββββββ intent: Literal[ "chat", # Natural conversation "sql", # Database query that should continue to SQL generation ] route_intent: Literal[ "chat", # Hi, hello, thanks, capabilities, etc. "data_query", # SELECT with filters "aggregation", # COUNT, SUM, AVG, GROUP BY "comparison", # Compare datasets "explanation", # Explain a concept or previous query "meta_query", # Questions about the schema itself ] entities: list[str] # Extracted table/column names complexity: Literal["simple", "moderate", "complex"] retrieval_top_k: int # How many schema docs to fetch (3=simple, 5=default, 8=complex)
# ββ Schema Retrieval Agent Output ββββββββββββββββββββ relevant_schema: str # Formatted schema context for LLM relevant_tables: list[str] # Table names retrieved retrieval_source: str # "rag_top_k:{n}" | "full_schema_fallback" | "meta_query" β for tracing
# ββ SQL Generation Agent Output ββββββββββββββββββββββ generated_sql: str # The SQL query sql_explanation: str # Technical explanation friendly_message: str # User-friendly message
# ββ SQL Validation Agent Output ββββββββββββββββββββββ is_valid: bool # Safety check passed validation_errors: list[str] # List of issues found sanitized_sql: str # SQL after safety modifications (LIMIT injection, etc.) retry_count: int # Number of regeneration attempts
# ββ Output Guardrail Results βββββββββββββββββββββββββ guardrail_warnings: list[str] # Hallucinated reference warnings guardrail_confidence: float # LLM output confidence score (0.0-1.0)
# ββ Execution Agent Output βββββββββββββββββββββββββββ query_results: list[dict] # Raw query results execution_time_ms: float # Query execution duration row_count: int # Number of rows returned column_names: list[str] # Column names in result set
# ββ Visualization Agent Output βββββββββββββββββββββββ chart_config: Optional[dict] # Chart.js configuration chart_type: Optional[str] # bar, line, pie, doughnut, scatter insights: list[str] # Auto-generated insights follow_up_questions: list[str] # Suggested follow-up queries
# ββ Error Handling βββββββββββββββββββββββββββββββββββ error: Optional[str] # Error message if any step failed error_agent: Optional[str] # Which agent produced the error123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""Visualization Agent β Generates chart configs and auto-insights from query results.Last agent in the pipeline. Determines optimal chart type and generates follow-ups."""
import structlogfrom collections import Counter
from app.agents.state import AgentState
logger = structlog.get_logger()
# Chart type selection thresholdsMAX_PIE_CATEGORIES = 8MIN_LINE_POINTS = 3
def visualization_node(state: AgentState) -> dict: """ Analyze query results and generate visualization config + insights. """ results = state.get("query_results", []) columns = state.get("column_names", []) user_query = state.get("user_query", "") _sql = state.get("sanitized_sql", "") or state.get("generated_sql", "") trace_id = state.get("trace_id", "unknown")
logger.info("agent_started", agent="visualization", trace_id=trace_id)
if not results: return { "chart_config": None, "chart_type": None, "insights": ["No data returned from the query."], "follow_up_questions": _generate_followups_empty(user_query), }
# ββ Classify columns βββββββββββββββββββββββββββββββββ numeric_cols = [] text_cols = [] date_cols = []
for col in columns: sample_val = results[0].get(col) if sample_val is None: # Check other rows for row in results[:5]: if row.get(col) is not None: sample_val = row[col] break
col_lower = col.lower() if any(d in col_lower for d in ["date", "time", "created", "updated", "day", "month", "year"]): date_cols.append(col) elif isinstance(sample_val, (int, float)): numeric_cols.append(col) else: # Try to parse as number try: if sample_val is not None: float(sample_val) numeric_cols.append(col) else: text_cols.append(col) except (ValueError, TypeError): text_cols.append(col)
# ββ Determine chart type βββββββββββββββββββββββββββββ chart_config = None chart_type = None row_count = len(results)
if numeric_cols and (text_cols or date_cols): label_col = date_cols[0] if date_cols else text_cols[0] value_col = numeric_cols[0]
labels = [str(row.get(label_col, "")) for row in results] values = [] for row in results: v = row.get(value_col, 0) try: values.append(float(v) if v is not None else 0) except (ValueError, TypeError): values.append(0)
# Choose chart type if date_cols and row_count >= MIN_LINE_POINTS: chart_type = "line" elif row_count <= MAX_PIE_CATEGORIES: chart_type = "doughnut" else: chart_type = "bar"
colors = [ "#38bdf8", "#a855f7", "#ec4899", "#22c55e", "#eab308", "#f97316", "#14b8a6", "#6366f1", "#f43f5e", "#84cc16", ]
chart_config = { "type": chart_type, "data": { "labels": labels[:50], # Cap at 50 labels for readability "datasets": [{ "label": value_col.replace("_", " ").title(), "data": values[:50], "backgroundColor": colors[:len(labels)], "borderColor": "#1e293b", "borderWidth": 2, }], }, "options": { "responsive": True, "maintainAspectRatio": False, "plugins": { "legend": {"position": "bottom", "labels": {"color": "#94A3B8"}}, }, }, }
# ββ Generate insights ββββββββββββββββββββββββββββββββ insights = _generate_insights(results, numeric_cols, text_cols, date_cols, row_count)
# ββ Generate follow-up questions βββββββββββββββββββββ follow_ups = _generate_followups(user_query, columns, results)
logger.info( "visualization_complete", chart_type=chart_type, insights_count=len(insights), followups_count=len(follow_ups), )
return { "chart_config": chart_config, "chart_type": chart_type, "insights": insights, "follow_up_questions": follow_ups, }
def _generate_insights(results, numeric_cols, text_cols, date_cols, row_count) -> list[str]: """Generate statistical insights from query results.""" insights = [] insights.append(f"π **{row_count}** records returned")
for col in numeric_cols[:3]: # Top 3 numeric columns values = [] for row in results: try: v = float(row.get(col, 0)) values.append(v) except (ValueError, TypeError): continue
if values: avg_val = sum(values) / len(values) min_val = min(values) max_val = max(values) _total = sum(values)
col_label = col.replace("_", " ").title() insights.append(f"**{col_label}**: avg {avg_val:,.2f} | min {min_val:,.2f} | max {max_val:,.2f}")
if max_val > avg_val * 3 and len(values) > 2: insights.append(f"β οΈ Outlier detected in **{col_label}**: max ({max_val:,.2f}) is {max_val/avg_val:.1f}x the average")
# Trend detection for date-sorted data if len(values) >= 3: first_half = sum(values[:len(values)//2]) second_half = sum(values[len(values)//2:]) if second_half > first_half * 1.2: insights.append(f"π Upward trend detected in **{col_label}**") elif first_half > second_half * 1.2: insights.append(f"π Downward trend detected in **{col_label}**")
# Text column distribution for col in text_cols[:1]: values = [str(row.get(col, "")) for row in results] counter = Counter(values) if len(counter) > 1: top_val, top_count = counter.most_common(1)[0] pct = (top_count / len(values)) * 100 if pct < 100: insights.append(f"π·οΈ Most common **{col.replace('_', ' ')}**: '{top_val}' ({pct:.0f}%)")
return insights
def _generate_followups(query: str, columns: list, results: list) -> list[str]: """Generate context-aware follow-up suggestions.""" followups = [] query_lower = query.lower()
if "top" in query_lower or "best" in query_lower: followups.append("Show the bottom performers instead") if "salary" in query_lower or "amount" in query_lower or "revenue" in query_lower: followups.append("Show the distribution by department") followups.append("Compare with last year's data")
if len(results) > 10: followups.append("Show only the top 5 results")
if any(c.lower() in ["department", "region", "category"] for c in columns): followups.append("Break down by category")
# Always offer these followups.extend([ "Visualize this as a chart", "Export these results", ])
return followups[:5] # Cap at 5 suggestions
def _generate_followups_empty(query: str) -> list[str]: """Follow-up suggestions when no results are returned.""" return [ "Show all available data from this table", "List the tables in the database", "Try a broader search criteria", ]1# AI Features Package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Anomaly Detector β Statistical anomaly detection on query results.Uses IQR and Z-score methods to identify unusual data points."""
import mathimport structlog
logger = structlog.get_logger()
class AnomalyDetector: """Detects statistical anomalies in query result data."""
def detect(self, results: list[dict]) -> list[dict]: """ Detect anomalies across all numeric columns in the results. Returns a list of anomaly descriptors. """ if not results or len(results) < 4: return []
anomalies = [] columns = list(results[0].keys())
for col in columns: values = [] for row in results: try: v = float(row.get(col, 0)) values.append(v) except (ValueError, TypeError): continue
if len(values) < 4: continue
# ββ IQR Method βββββββββββββββββββββββββββββββ sorted_vals = sorted(values) n = len(sorted_vals) q1 = sorted_vals[int(n * 0.25)] q3 = sorted_vals[int(n * 0.75)] iqr = q3 - q1
lower = q1 - 1.5 * iqr upper = q3 + 1.5 * iqr
for i, row in enumerate(results): try: v = float(row.get(col, 0)) except (ValueError, TypeError): continue
if v < lower or v > upper: anomalies.append({ "row_index": i, "column": col, "value": v, "type": "above_upper" if v > upper else "below_lower", "threshold": upper if v > upper else lower, "method": "iqr", "severity": "high" if (v > q3 + 3 * iqr or v < q1 - 3 * iqr) else "medium", "description": ( f"{col} value {v:,.2f} is {'above' if v > upper else 'below'} " f"the expected range [{lower:,.2f}, {upper:,.2f}]" ), })
# ββ Z-Score Method (for larger datasets) βββββ if len(values) >= 10: mean = sum(values) / len(values) variance = sum((v - mean) ** 2 for v in values) / len(values) std = math.sqrt(variance) if variance > 0 else 0
if std > 0: for i, row in enumerate(results): try: v = float(row.get(col, 0)) except (ValueError, TypeError): continue
z_score = abs((v - mean) / std) if z_score > 3: # Only add if not already caught by IQR existing = any( a["row_index"] == i and a["column"] == col for a in anomalies ) if not existing: anomalies.append({ "row_index": i, "column": col, "value": v, "type": "z_score_outlier", "z_score": round(z_score, 2), "method": "z_score", "severity": "high" if z_score > 4 else "medium", "description": ( f"{col} value {v:,.2f} has z-score of {z_score:.2f} " f"(>{3} standard deviations from mean {mean:,.2f})" ), })
logger.info("anomaly_detection_complete", anomalies_found=len(anomalies)) return anomalies1234567891011121314151617181920212223242526272829"""SQL Explainer β Converts SQL queries into plain English explanations.Uses LLM to generate non-technical descriptions of what a query does."""
import structlogfrom app.prompts.registry import get_prompt_registry
logger = structlog.get_logger()
class SQLExplainer: """Explains SQL queries in natural language for non-technical users."""
def __init__(self, llm_router): self.llm_router = llm_router
def explain(self, sql: str, results_count: int = 0) -> str: """ Generate a plain English explanation of a SQL query. """ try: prompt_template = get_prompt_registry().get("sql_explanation") messages = prompt_template.render(sql=sql, results_count=results_count) explanation = self.llm_router.generate(messages, model_preference="fast", max_tokens=256) return explanation.strip() except Exception as e: logger.warning("sql_explanation_failed", error=str(e)) return "Unable to generate explanation at this time."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Auto Insights Generator β Statistical analysis and pattern detection on query results.Generates human-readable insights without LLM (pure statistical analysis)."""
import structlogfrom collections import Counter
logger = structlog.get_logger()
class InsightsGenerator: """Generates statistical insights from query result data."""
def generate(self, results: list[dict], query: str = "") -> list[str]: """ Analyze query results and generate human-readable insights. Uses statistical methods β no LLM needed. """ if not results: return ["No data available for analysis."]
insights = []
# ββ Basic stats ββββββββββββββββββββββββββββββββββ row_count = len(results) col_count = len(results[0]) if results else 0 insights.append(f"π Dataset: **{row_count}** records across **{col_count}** columns")
# ββ Classify columns βββββββββββββββββββββββββββββ numeric_cols = [] text_cols = [] date_cols = [] columns = list(results[0].keys()) if results else []
for col in columns: sample = results[0].get(col) col_lower = col.lower()
if any(d in col_lower for d in ["date", "time", "created", "updated"]): date_cols.append(col) elif isinstance(sample, (int, float)): numeric_cols.append(col) else: try: if sample is not None: float(sample) numeric_cols.append(col) else: text_cols.append(col) except (ValueError, TypeError): text_cols.append(col)
# ββ Numeric column analysis ββββββββββββββββββββββ for col in numeric_cols[:4]: values = self._extract_numeric_values(results, col) if not values: continue
avg = sum(values) / len(values) min_val = min(values) max_val = max(values) total = sum(values)
label = col.replace("_", " ").title() insights.append( f"**{label}**: Total {total:,.2f} | " f"Avg {avg:,.2f} | Range [{min_val:,.2f} β {max_val:,.2f}]" )
# Outlier detection (IQR method) outliers = self._detect_outliers(values) if outliers: insights.append( f"β οΈ **{len(outliers)} outliers** detected in {label} " f"(values: {', '.join(f'{v:,.2f}' for v in outliers[:3])})" )
# Concentration analysis if len(values) > 1: top_val = max(values) top_pct = (top_val / total * 100) if total > 0 else 0 if top_pct > 30: insights.append(f"π― Top value in **{label}** accounts for {top_pct:.1f}% of total")
# ββ Text column analysis βββββββββββββββββββββββββ for col in text_cols[:2]: str_values = [str(row.get(col, "")) for row in results if row.get(col)] if not str_values: continue
counter = Counter(str_values) unique_count = len(counter) label = col.replace("_", " ").title()
if unique_count == row_count: insights.append(f"π **{label}** has all unique values") elif unique_count <= 10: top_items = counter.most_common(3) distribution = ", ".join(f"'{k}' ({v})" for k, v in top_items) insights.append(f"π·οΈ **{label}** distribution: {distribution}")
# ββ Trend detection ββββββββββββββββββββββββββββββ if date_cols and numeric_cols and len(results) >= 3: insights.append("π Time-series data detected β trend analysis available")
return insights
def _extract_numeric_values(self, results: list[dict], col: str) -> list[float]: """Extract numeric values from a column, skipping nulls.""" values = [] for row in results: v = row.get(col) if v is not None: try: values.append(float(v)) except (ValueError, TypeError): continue return values
def _detect_outliers(self, values: list[float]) -> list[float]: """Detect outliers using the IQR method.""" if len(values) < 4: return []
sorted_vals = sorted(values) n = len(sorted_vals) q1 = sorted_vals[int(n * 0.25)] q3 = sorted_vals[int(n * 0.75)] iqr = q3 - q1
lower = q1 - 1.5 * iqr upper = q3 + 1.5 * iqr
return [v for v in values if v < lower or v > upper]1# API Package12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Conversational Fast-Path β Server-side detection for chat queries.
Handles greetings, thanks, identity questions, etc. without invoking thefull LLM pipeline. Provides instant (<1ms) responses for conversational queries."""
import re
# ββ Pattern Registry βββββββββββββββββββββββββββββββββββββ_CHAT_PATTERNS = [ re.compile(r'^(hi|hello|hey|howdy|sup|yo)\b[\s!.?]*$', re.I), re.compile(r'^how are you\??[\s!.]*$', re.I), re.compile(r'^thank(s| you)[\s!.,]*$', re.I), re.compile(r'^(bye|goodbye|see you|cya|later)[\s!.]*$', re.I), re.compile(r'^good (morning|afternoon|evening|night)[\s!.]*$', re.I), re.compile(r'^(ok|okay|alright|great|perfect|cool|nice|awesome)[\s!.]*$', re.I), re.compile(r'^(who are you|what are you|what is plainsql)\??$', re.I), re.compile(r'^(what can you do|help me|help)\??[\s!.]*$', re.I),]
_CHAT_RESPONSES = { '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.", 'thanks': "You're welcome! Let me know if you'd like to explore more insights from your data.", 'farewell': "Goodbye! Your data will be here when you need it.", 'identity': "I'm PlainSQL β an enterprise AI platform that converts natural language into SQL using a hybrid RAG + LLM pipeline.", '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'", 'default': "I'm PlainSQL, your AI data assistant. Ask me questions about your database!",}
def detect_conversational(query: str): """ Returns a fast-path response string if the query is conversational, else None.
This avoids a full LLM round-trip for simple greetings/thanks/identity questions. Average latency: <0.1ms. """ q = query.strip() if re.match(r'^(hi|hello|hey|howdy|sup|yo)\b', q, re.I): return _CHAT_RESPONSES['greeting'] if re.match(r'^how are you', q, re.I): return _CHAT_RESPONSES['greeting'] if re.match(r'^thank(s| you)', q, re.I): return _CHAT_RESPONSES['thanks'] if re.match(r'^(bye|goodbye|see you)', q, re.I): return _CHAT_RESPONSES['farewell'] if re.match(r'^(who are you|what are you|what is plainsql)', q, re.I): return _CHAT_RESPONSES['identity'] if re.match(r'^(what can you do|help)', q, re.I): return _CHAT_RESPONSES['capabilities'] for pat in _CHAT_PATTERNS: if pat.match(q): return _CHAT_RESPONSES['default'] return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""API Middleware β Auth verification, rate limiting, and request logging."""
import timeimport hashlibimport structlogfrom fastapi import Requestfrom typing import Optional
from app.auth.jwt_auth import AuthServicefrom app.observability.metrics import metrics
logger = structlog.get_logger()
# ββ In-Memory Rate Limiter (upgrade to Redis for production) ββ
class InMemoryRateLimiter: """ Simple in-memory rate limiter using sliding window counters. For production, use Redis-backed implementation. """
def __init__(self, requests_per_minute: int = 60): self.rpm = requests_per_minute self._counters: dict[str, list[float]] = {} self._call_count = 0
def check(self, key: str) -> bool: """Returns True if request is allowed, False if rate limited.""" now = time.time() window_start = now - 60
if key not in self._counters: self._counters[key] = []
# Clean old entries for this key self._counters[key] = [t for t in self._counters[key] if t > window_start]
# Periodic cleanup of dead keys to prevent unbounded memory growth self._call_count += 1 if self._call_count % 500 == 0: dead_keys = [k for k, v in self._counters.items() if not v] for k in dead_keys: del self._counters[k]
if len(self._counters[key]) >= self.rpm: return False
self._counters[key].append(now) return True
# ββ In-Memory Query Cache ββββββββββββββββββββββββββββββββ
class QueryCache: """ Simple in-memory query cache. For production, upgrade to Redis. """
def __init__(self, ttl_seconds: int = 300, max_entries: int = 500): self.ttl = ttl_seconds self.max_entries = max_entries self._cache: dict[str, dict] = {}
def _make_key(self, query: str, tenant_id: str = "default") -> str: raw = f"{tenant_id}:{query.strip().lower()}" return hashlib.sha256(raw.encode()).hexdigest()[:16]
def get(self, query: str, tenant_id: str = "default") -> Optional[dict]: key = self._make_key(query, tenant_id) entry = self._cache.get(key) if entry and time.time() - entry["timestamp"] < self.ttl: return entry["data"] elif entry: del self._cache[key] return None
def set(self, query: str, data: dict, tenant_id: str = "default"): key = self._make_key(query, tenant_id) # Evict oldest if at capacity if len(self._cache) >= self.max_entries: oldest_key = min(self._cache, key=lambda k: self._cache[k]["timestamp"]) del self._cache[oldest_key] self._cache[key] = {"data": data, "timestamp": time.time(), "tenant_id": tenant_id}
def invalidate(self, tenant_id: str = "default"): """Clear all cache entries for a specific tenant. Cache keys are SHA-256 hashes of '{tenant_id}:{query}', so we must recheck by storing the tenant_id alongside the cached data. """ keys_to_delete = [ k for k, v in self._cache.items() if v.get("tenant_id", "default") == tenant_id ] for k in keys_to_delete: del self._cache[k]
def invalidate_all(self): """Clear the entire cache (all tenants).""" self._cache.clear()
# ββ Auth Dependency ββββββββββββββββββββββββββββββββββββββ
def create_auth_dependency(auth_service: AuthService): """ Create a FastAPI dependency for JWT authentication. Token is OPTIONAL β unauthenticated requests receive a guest analyst identity. This allows the frontend to work without login for development/demo use. """ # Default guest identity for unauthenticated requests GUEST_USER = { "sub": "guest", "username": "guest", "role": "analyst", "tenant_id": "default", }
def get_current_user(request: Request) -> dict: auth_header = request.headers.get("Authorization", "") api_key = request.headers.get("X-API-Key", "")
# No credentials provided β return guest identity (no 401) if not auth_header.startswith("Bearer ") and not api_key: return GUEST_USER
token = auth_header[7:] if auth_header.startswith("Bearer ") else api_key
try: payload = auth_service.verify_token(token) return payload except Exception as e: metrics.increment("plainsql_auth_failures_total") logger.warning("auth_failed", error=str(e)) # Invalid token β still return guest rather than blocking (dev-friendly) return GUEST_USER
return get_current_user
# ββ Request Logging Middleware βββββοΏ½οΏ½οΏ½βββββββββββββββββββββ
class RequestLoggingMiddleware: """Log all API requests with timing."""
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send): if scope["type"] != "http": await self.app(scope, receive, send) return
start_time = time.time() request = Request(scope, receive)
# Track active requests metrics.set_gauge("plainsql_active_requests", 1)
try: await self.app(scope, receive, send) finally: elapsed = round((time.time() - start_time) * 1000, 2) metrics.set_gauge("plainsql_active_requests", 0)
logger.info( "http_request", method=request.method, path=request.url.path, elapsed_ms=elapsed, )1# Routes Package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Admin Routes β Administrative operations requiring admin role.Includes schema reindexing, cache invalidation, token usage, and system management."""
from fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.responses import JSONResponseimport structlog
logger = structlog.get_logger()
def create_admin_router( rag_retriever, cache, auth_dep, db_pool, llm_router=None, orchestrator=None,): """Factory to create admin routes with injected dependencies."""
router = APIRouter(prefix="/api/v1/admin", tags=["Admin"])
def _require_admin(user=Depends(auth_dep)): """Ensure the authenticated user has admin role.""" if user.get("role") != "admin": raise HTTPException(status_code=403, detail="Admin role required") return user
@router.post("/reindex") def reindex_schema(user=Depends(_require_admin)): """ Re-index the database schema into RAG (ChromaDB + BM25). Call this after schema changes (new tables, columns, etc.). """ try: rag_retriever.refresh_index() doc_count = rag_retriever.collection.count() logger.info("admin_reindex_complete", triggered_by=user.get("username"), docs=doc_count) return { "status": "ok", "message": f"Schema re-indexed successfully. {doc_count} documents indexed.", "document_count": doc_count, } except Exception as e: logger.error("admin_reindex_failed", error=str(e)) return JSONResponse( status_code=500, content={"error": f"Reindex failed: {str(e)}"}, )
@router.post("/cache/invalidate") def invalidate_cache(user=Depends(_require_admin)): """Clear the entire query cache.""" try: if hasattr(cache, "invalidate_all"): cache.invalidate_all() # Also clear semantic cache if available if orchestrator and hasattr(orchestrator, "semantic_cache") and orchestrator.semantic_cache: orchestrator.semantic_cache.invalidate_all() logger.info("admin_cache_invalidated", triggered_by=user.get("username")) return {"status": "ok", "message": "Cache invalidated successfully."} except Exception as e: logger.error("admin_cache_invalidate_failed", error=str(e)) return JSONResponse( status_code=500, content={"error": f"Cache invalidation failed: {str(e)}"}, )
@router.get("/pool-status") def pool_status(user=Depends(_require_admin)): """Get database connection pool statistics.""" try: pool_info = db_pool.get_pool_status() return {"status": "ok", "pool": pool_info} except Exception as e: return JSONResponse( status_code=500, content={"error": f"Pool status unavailable: {str(e)}"}, )
@router.get("/token-usage") def token_usage(user=Depends(_require_admin)): """ Get aggregate LLM token usage and cost statistics.
Returns: Total input/output tokens, estimated cost, request count, and average tokens per request. """ if not llm_router: return JSONResponse( status_code=503, content={"error": "LLM router not available"}, ) try: usage = llm_router.get_token_usage() # Add semantic cache stats if available cache_stats = None if orchestrator and hasattr(orchestrator, "semantic_cache") and orchestrator.semantic_cache: cache_stats = orchestrator.semantic_cache.stats()
return { "status": "ok", "token_usage": usage, "semantic_cache": cache_stats, } except Exception as e: return JSONResponse( status_code=500, content={"error": f"Token usage unavailable: {str(e)}"}, )
return router
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Chat & Query Routes β Core API endpoints for text-to-SQL.Includes SSE streaming for real-time pipeline feedback."""
import jsonfrom fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.responses import StreamingResponsefrom app.api.schemas import ( GenerateSQLRequest, QueryResult, ExecuteQueryRequest, ExplainRequest, ExplainResponse, InsightsRequest, InsightsResponse,)
router = APIRouter(prefix="/api/v1", tags=["Query"])
def create_chat_router(orchestrator, auth_dep, cache, rate_limiter, tracer, explainer, insights_gen, anomaly_detector, safety_validator): """Factory to create chat router with injected dependencies."""
@router.post("/generate-sql", response_model=QueryResult) def generate_sql(request: GenerateSQLRequest, current_user: dict = Depends(auth_dep)): """ Generate SQL from natural language and optionally execute it. The full multi-agent pipeline runs here. """ # Rate limiting user_key = f"rl:{current_user.get('sub', 'anon')}" if not rate_limiter.check(user_key): raise HTTPException(429, "Rate limit exceeded. Please wait a moment.")
# Check cache cached = cache.get(request.question, current_user.get("tenant_id", "default")) if cached: cached["trace_id"] = "cached" return QueryResult(**cached)
# Run multi-agent pipeline result = orchestrator.process_query( user_query=request.question, conversation_history=request.history, tenant_id=current_user.get("tenant_id", "default"), user_role=current_user.get("role", "viewer"), )
# Trace the query tracer.trace_query(result)
# Build response response_data = { "trace_id": result.get("trace_id", ""), "question": request.question, "intent": result.get("intent"), "sql": result.get("sanitized_sql") or result.get("generated_sql"), "sql_explanation": result.get("sql_explanation"), "message": result.get("friendly_message", ""), "data": result.get("query_results", []), "row_count": result.get("row_count", 0), "column_names": result.get("column_names", []), "execution_time_ms": result.get("execution_time_ms", 0), "chart_config": result.get("chart_config"), "chart_type": result.get("chart_type"), "insights": result.get("insights", []), "follow_ups": result.get("follow_up_questions", []), "error": result.get("error"), }
# Cache successful results if not result.get("error") and result.get("query_results"): cache.set(request.question, response_data, current_user.get("tenant_id", "default"))
return QueryResult(**response_data)
@router.post("/chat/stream") async def chat_stream(request: GenerateSQLRequest, current_user: dict = Depends(auth_dep)): """ Stream chat responses via Server-Sent Events (SSE). Each agent stage emits an event as it completes. """ user_key = f"rl:{current_user.get('sub', 'anon')}" if not rate_limiter.check(user_key): raise HTTPException(429, "Rate limit exceeded.")
async def event_generator(): async for event in orchestrator.aprocess_query_streaming( user_query=request.question, conversation_history=request.history, tenant_id=current_user.get("tenant_id", "default"), user_role=current_user.get("role", "viewer"), ): event_type = event.get("type", "message") yield _sse_event(event_type, event)
return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, )
@router.post("/execute-query", response_model=QueryResult) def execute_query(request: ExecuteQueryRequest, current_user: dict = Depends(auth_dep)): """Execute a user-provided SQL query (must pass safety validation).""" from app.agents.sql_validation import sql_validation_node
# Validate the SQL validation_state = {"generated_sql": request.sql, "retry_count": 0, "trace_id": "manual"} validation_result = sql_validation_node(validation_state)
if not validation_result.get("is_valid"): errors = validation_result.get("validation_errors", ["Unknown validation error"]) raise HTTPException(400, f"SQL blocked by safety layer: {', '.join(errors)}")
# Execute from app.agents.execution import execution_node exec_state = {**validation_result, "trace_id": "manual"} exec_result = execution_node(exec_state, orchestrator.db_pool)
if exec_result.get("error"): raise HTTPException(400, exec_result["error"])
return QueryResult( trace_id="manual", question="Manual SQL execution", sql=request.sql, message=f"Query executed successfully. {exec_result.get('row_count', 0)} rows returned.", data=exec_result.get("query_results", []), row_count=exec_result.get("row_count", 0), column_names=exec_result.get("column_names", []), execution_time_ms=exec_result.get("execution_time_ms", 0), )
@router.post("/explain", response_model=ExplainResponse) def explain_sql(request: ExplainRequest, current_user: dict = Depends(auth_dep)): """Explain a SQL query in natural language.""" explanation = explainer.explain(request.sql, request.result_count) return ExplainResponse(sql=request.sql, explanation=explanation)
@router.post("/insights", response_model=InsightsResponse) def get_insights(request: InsightsRequest, current_user: dict = Depends(auth_dep)): """Generate auto-insights and anomaly detection for data.""" insights = insights_gen.generate(request.data, request.query) anomalies = anomaly_detector.detect(request.data) return InsightsResponse(insights=insights, anomalies=anomalies)
return router
def _sse_event(event_type: str, data: dict) -> str: """Format a Server-Sent Event.""" payload = json.dumps({"type": event_type, **data}, default=str) return f"event: {event_type}\ndata: {payload}\n\n"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Conversations API Router β CRUD for server-side chat persistence.
Provides endpoints for managing conversations and messages,enabling cross-device chat history and user-bound data."""
from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Fieldimport structlog
logger = structlog.get_logger()
def create_conversations_router(conversation_manager, auth_dep=None): """Factory function to create the conversations router with injected dependencies.""" router = APIRouter(prefix="/api/v1/conversations", tags=["conversations"])
class CreateConversationRequest(BaseModel): title: str = Field(default="New analysis", max_length=255)
class UpdateTitleRequest(BaseModel): title: str = Field(..., min_length=1, max_length=255)
# ββ List conversations βββββββββββββββββββββββββββββββ @router.get("") async def list_conversations(): """List all conversations for the current user.""" try: conversations = conversation_manager.list_conversations(user_id="anonymous") return {"conversations": conversations} except Exception as e: logger.error("list_conversations_failed", error=str(e)) raise HTTPException(status_code=500, detail="Failed to load conversations")
# ββ Create conversation ββββββββββββββββββββββββββββββ @router.post("") async def create_conversation(request: CreateConversationRequest): """Create a new conversation.""" try: conv = conversation_manager.create_conversation( title=request.title, user_id="anonymous", ) return conv except Exception as e: logger.error("create_conversation_failed", error=str(e)) raise HTTPException(status_code=500, detail="Failed to create conversation")
# ββ Update conversation title ββββββββββββββββββββββββ @router.patch("/{conversation_id}") async def update_conversation(conversation_id: str, request: UpdateTitleRequest): """Update a conversation's title.""" try: conversation_manager.update_title(conversation_id, request.title) return {"status": "ok"} except Exception as e: logger.error("update_conversation_failed", error=str(e)) raise HTTPException(status_code=500, detail="Failed to update conversation")
# ββ Delete conversation ββββββββββββββββββββββββββββββ @router.delete("/{conversation_id}") async def delete_conversation(conversation_id: str): """Delete a conversation and all its messages.""" try: conversation_manager.delete_conversation(conversation_id, user_id="anonymous") return {"status": "ok"} except Exception as e: logger.error("delete_conversation_failed", error=str(e)) raise HTTPException(status_code=500, detail="Failed to delete conversation")
# ββ Get messages βββββββββββββββββββββββββββββββββββββ @router.get("/{conversation_id}/messages") async def get_messages(conversation_id: str): """Get all messages in a conversation.""" try: messages = conversation_manager.get_messages(conversation_id) return {"messages": messages} except Exception as e: logger.error("get_messages_failed", error=str(e)) raise HTTPException(status_code=500, detail="Failed to load messages")
return router12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Monitoring Routes β Prometheus-native metrics and dashboard JSON endpoint.Exposes query volume, latency, success rates, and error breakdowns.
Uses prometheus_client when available for native Prometheus format.Falls back to in-process metrics for local development."""
from fastapi import APIRouter, Responsefrom app.observability.metrics import ( metrics, get_prometheus_metrics, get_prometheus_content_type,)
router = APIRouter(prefix="/api/v1/metrics", tags=["Monitoring"])
class QueryMetricsRecorder: """ Thin wrapper that records query-level metrics into the unified MetricsCollector. This replaces the old duplicate MetricsCollector that was in this file. """
def record_query( self, latency_ms: float, intent: str = "unknown", success: bool = True, error_agent: str = None, ): """Record a single query execution into the unified metrics system.""" status = "success" if success else "error" metrics.increment("plainsql_queries_total", {"intent": intent, "status": status}) metrics.observe("plainsql_query_latency_ms", latency_ms, {"intent": intent})
if not success and error_agent: metrics.increment("plainsql_agent_errors_total", {"agent": error_agent})
# Module-level singleton_recorder = QueryMetricsRecorder()
def get_metrics_collector() -> QueryMetricsRecorder: """Get the global metrics recorder singleton.""" return _recorder
def create_monitoring_router() -> APIRouter: """Factory to create monitoring router."""
@router.get("/prometheus") def prometheus_metrics_endpoint(): """ Expose metrics in Prometheus exposition format for scraping. Uses native prometheus_client output when available. """ content = get_prometheus_metrics() return Response( content=content, media_type=get_prometheus_content_type(), )
@router.get("/dashboard") def dashboard_metrics(): """JSON metrics for the frontend or internal dashboard.""" return metrics.get_all_metrics()
return router123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193"""Auth, Schema, Analytics, and Health Routes."""
from fastapi import APIRouter, Depends, HTTPException, statusfrom app.api.schemas import ( LoginRequest, RegisterRequest, TokenResponse, APIKeyRequest, APIKeyResponse, SchemaResponse, AnalyticsResponse, HealthResponse,)
router = APIRouter(tags=["System"])
def create_system_router(auth_service, auth_dep, db_pool, rag_retriever, llm_router, tracer, user_repo, start_time): """Factory to create system routes with injected dependencies."""
# ββ Auth Routes ββββββββββββββββββββββββββββββββββββββ
auth_router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
@auth_router.post("/login", response_model=TokenResponse) def login(request: LoginRequest): """Authenticate and get JWT token.""" user = user_repo.get_by_username(request.username) if not user or not auth_service.verify_password(request.password, user["password_hash"]): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password", )
token = auth_service.create_access_token( user_id=user["id"], username=user["username"], role=user["role"], tenant_id=user.get("tenant_id", "default"), )
return TokenResponse( access_token=token, role=user["role"], tenant_id=user.get("tenant_id", "default"), )
@auth_router.post("/register", response_model=TokenResponse) def register(request: RegisterRequest): """Register a new user. Self-registration is always 'viewer' role. Only admins can promote users via a separate endpoint.""" if user_repo.get_by_username(request.username): raise HTTPException(400, "Username already exists")
password_hash = auth_service.hash_password(request.password) user_id = f"user_{user_repo.count() + 1}"
# SECURITY: Self-registration is always viewer. # Elevated roles (analyst, admin) must be granted by an existing admin. assigned_role = "viewer"
success = user_repo.create( user_id=user_id, username=request.username, email=request.email, password_hash=password_hash, role=assigned_role, tenant_id=request.tenant_id, ) if not success: raise HTTPException(500, "Failed to register user")
token = auth_service.create_access_token( user_id=user_id, username=request.username, role=assigned_role, tenant_id=request.tenant_id, )
return TokenResponse( access_token=token, role=assigned_role, tenant_id=request.tenant_id, )
@auth_router.post("/api-keys", response_model=APIKeyResponse) def create_api_key(request: APIKeyRequest, current_user: dict = Depends(auth_dep)): """Create a long-lived API key (admin only).""" if current_user.get("role") != "admin": raise HTTPException(403, "Only admins can create API keys")
api_key = auth_service.create_api_key_token( key_name=request.key_name, tenant_id=current_user.get("tenant_id", "default"), role=request.role, )
return APIKeyResponse( key_name=request.key_name, api_key=api_key, role=request.role, )
# ββ Schema Route βββββββββββββββββββββββββββββββββββββ
schema_router = APIRouter(prefix="/api/v1", tags=["Schema"])
@schema_router.get("/schema", response_model=SchemaResponse) def get_schema(current_user: dict = Depends(auth_dep)): """Get database schema for the current tenant.""" tables = db_pool.get_tables() schema_text = db_pool.get_full_schema() return SchemaResponse( tables=tables, schema_text=schema_text, table_count=len(tables), )
@schema_router.post("/schema/refresh") def refresh_schema(current_user: dict = Depends(auth_dep)): """Re-index the schema (admin only).""" if current_user.get("role") != "admin": raise HTTPException(403, "Only admins can refresh schema") rag_retriever.refresh_index() return {"message": "Schema re-indexed successfully"}
# ββ Analytics Route ββββββββββββββββββββββββββββββββββ
analytics_router = APIRouter(prefix="/api/v1", tags=["Analytics"])
@analytics_router.get("/analytics", response_model=AnalyticsResponse) def get_analytics(current_user: dict = Depends(auth_dep)): """Get usage analytics and metrics.""" if current_user.get("role") not in ("admin", "analyst"): raise HTTPException(403, "Insufficient permissions for analytics")
dashboard = tracer.get_dashboard_metrics() return AnalyticsResponse(**dashboard)
# ββ Health Route βββββββββββββββββββββββββββββββββββββ
health_router = APIRouter(tags=["Health"])
@health_router.get("/api/v1/health", response_model=HealthResponse) def health_check(): """System health check β no auth required.""" import time as _time
try: db_status = "connected" db_pool.get_tables() except Exception: db_status = "disconnected"
try: provider_status = llm_router.get_provider_status() except Exception: provider_status = {}
try: rag_count = rag_retriever.collection.count() except Exception: rag_count = 0
return HealthResponse( status="healthy" if db_status == "connected" else "degraded", version="2.0.0", database=db_status, llm_providers=provider_status, rag_indexed_tables=rag_count, uptime_seconds=round(_time.time() - start_time, 2), )
# NOTE: Prometheus metrics endpoint moved to /api/v1/metrics/prometheus # in monitoring.py to avoid duplicate metrics systems.
@health_router.get("/api/v1/pool-status") def pool_status(current_user: dict = Depends(auth_dep)): """Database connection pool statistics (admin only).""" if current_user.get("role") != "admin": raise HTTPException(403, "Only admins can view pool status") try: return db_pool.get_pool_status() except Exception as e: return {"error": str(e)}
@health_router.get("/api/v1/prompt-templates") def list_prompt_templates(current_user: dict = Depends(auth_dep)): """List all registered prompt templates and their versions (admin only).""" if current_user.get("role") != "admin": raise HTTPException(403, "Only admins can view prompt templates") from app.prompts.registry import get_prompt_registry return get_prompt_registry().list_templates()
return auth_router, schema_router, analytics_router, health_router123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Pydantic Request/Response Schemas β Type-safe API contracts."""
from pydantic import BaseModel, Fieldfrom typing import Optional, Any
# ββ Chat / Query Schemas βββββββββββββββββββββββββββββββββ
class GenerateSQLRequest(BaseModel): """Request to generate SQL from natural language.""" question: str = Field(..., min_length=1, max_length=1000, description="Natural language question") history: list[dict] = Field(default=[], description="Conversation history") execute: bool = Field(default=True, description="Execute the generated SQL immediately")
class QueryResult(BaseModel): """Unified query response.""" trace_id: str question: str intent: Optional[str] = None sql: Optional[str] = None sql_explanation: Optional[str] = None message: str data: list[dict] = [] row_count: int = 0 column_names: list[str] = [] execution_time_ms: float = 0 chart_config: Optional[dict] = None chart_type: Optional[str] = None insights: list[str] = [] follow_ups: list[str] = [] error: Optional[str] = None
class ExecuteQueryRequest(BaseModel): """Request to execute a specific SQL query.""" sql: str = Field(..., min_length=1, max_length=5000, description="SQL query to execute")
# ββ Auth Schemas βββββββββββββββββββββββββββββββββββββββββ
class LoginRequest(BaseModel): """Login credentials.""" username: str = Field(..., min_length=2, max_length=50) password: str = Field(..., min_length=6, max_length=128)
class RegisterRequest(BaseModel): """New user registration.""" username: str = Field(..., min_length=2, max_length=50) password: str = Field(..., min_length=6, max_length=128) email: str = Field(..., max_length=100) role: str = Field(default="viewer", description="viewer | analyst | admin") tenant_id: str = Field(default="default")
class TokenResponse(BaseModel): """JWT token response.""" access_token: str token_type: str = "bearer" role: str tenant_id: str expires_in: int = 28800 # 8 hours in seconds
class APIKeyRequest(BaseModel): """Create API key request.""" key_name: str = Field(..., min_length=2, max_length=50) role: str = Field(default="analyst")
class APIKeyResponse(BaseModel): """API key creation response.""" key_name: str api_key: str role: str expires_in_days: int = 90
# ββ Explain / Insights Schemas βββββββββββββββββββββββββββ
class ExplainRequest(BaseModel): """Request to explain SQL in natural language.""" sql: str = Field(..., min_length=1, max_length=5000) result_count: int = Field(default=0, ge=0)
class ExplainResponse(BaseModel): """SQL explanation response.""" sql: str explanation: str
class InsightsRequest(BaseModel): """Request auto-insights for data.""" data: list[dict] = Field(..., min_length=1) query: str = Field(default="")
class InsightsResponse(BaseModel): """Generated insights response.""" insights: list[str] anomalies: list[dict] = []
# ββ Schema / Analytics Schemas βββββββββββββββββββββββββββ
class SchemaResponse(BaseModel): """Database schema response.""" tables: list[str] schema_text: str table_count: int
class AnalyticsResponse(BaseModel): """Usage analytics response.""" total_queries: int successful_queries: int failed_queries: int latency_stats: dict all_metrics: dict
# ββ Health Check βββββββββββββββββββββββββββββββββββββββββ
class HealthResponse(BaseModel): """System health check response.""" status: str version: str database: str llm_providers: dict[str, Any] rag_indexed_tables: int uptime_seconds: float1# Auth Package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""JWT Authentication Service β Token creation, verification, and password hashing.Production-grade auth with bcrypt password hashing and configurable expiry."""
import bcryptimport structlogfrom datetime import datetime, timedelta, timezonefrom typing import Optionalfrom jose import jwt, JWTError
logger = structlog.get_logger()
class AuthService: """ JWT-based authentication service. Handles token creation, verification, and password hashing. """
def __init__(self, secret_key: str, algorithm: str = "HS256", expiry_hours: int = 8): self.secret_key = secret_key self.algorithm = algorithm self.expiry_hours = expiry_hours
# ββ Password Hashing βββββββββββββββββββββββββββββββββ
@staticmethod def hash_password(password: str) -> str: """Hash a plaintext password using bcrypt.""" pwd_bytes = password.encode("utf-8") salt = bcrypt.gensalt() return bcrypt.hashpw(pwd_bytes, salt).decode("utf-8")
@staticmethod def verify_password(plain_password: str, hashed_password: str) -> bool: """Verify a plaintext password against a bcrypt hash.""" return bcrypt.checkpw( plain_password.encode("utf-8"), hashed_password.encode("utf-8"), )
# ββ Token Management βββββββββββββββββββββββββββββββββ
def create_access_token( self, user_id: str, username: str, role: str, tenant_id: str = "default", extra_claims: Optional[dict] = None, ) -> str: """ Create a JWT access token. Payload includes: - sub: user_id - username: display name - role: admin | analyst | viewer - tenant_id: multi-tenant isolation - exp: expiration timestamp - iat: issued-at timestamp """ now = datetime.now(timezone.utc) payload = { "sub": user_id, "username": username, "role": role, "tenant_id": tenant_id, "exp": now + timedelta(hours=self.expiry_hours), "iat": now, "type": "access", }
if extra_claims: payload.update(extra_claims)
token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm) logger.info("token_created", user_id=user_id, role=role, tenant_id=tenant_id) return token
def verify_token(self, token: str) -> dict: """ Verify and decode a JWT token. Raises JWTError if invalid or expired. """ try: payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm]) return payload except JWTError as e: logger.warning("token_verification_failed", error=str(e)) raise
def create_api_key_token(self, key_name: str, tenant_id: str, role: str = "analyst") -> str: """ Create a long-lived API key token (90 days). Used for programmatic access. """ now = datetime.now(timezone.utc) payload = { "sub": f"apikey:{key_name}", "username": key_name, "role": role, "tenant_id": tenant_id, "exp": now + timedelta(days=90), "iat": now, "type": "api_key", } return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Role-Based Access Control (RBAC) β Permission enforcement for API endpoints.Three roles: admin, analyst, viewer with hierarchical permissions."""
from enum import Enumfrom fastapi import HTTPException, statusimport structlog
logger = structlog.get_logger()
class Role(str, Enum): """User roles with increasing privilege levels.""" VIEWER = "viewer" # Can view data only ANALYST = "analyst" # Can execute queries and view analytics ADMIN = "admin" # Full access including user management
class Permission(str, Enum): """Granular permissions mapped to roles.""" READ = "read" # View query results EXECUTE = "execute" # Execute SQL queries VIEW_ANALYTICS = "view_analytics" # View usage analytics MANAGE_SCHEMA = "manage_schema" # Refresh schema index MANAGE_USERS = "manage_users" # Create/delete users MANAGE_API_KEYS = "manage_api_keys" # Create API keys VIEW_LOGS = "view_logs" # View system logs
# Role β Permission mappingROLE_PERMISSIONS: dict[Role, set[Permission]] = { Role.VIEWER: { Permission.READ, }, Role.ANALYST: { Permission.READ, Permission.EXECUTE, Permission.VIEW_ANALYTICS, }, Role.ADMIN: { Permission.READ, Permission.EXECUTE, Permission.VIEW_ANALYTICS, Permission.MANAGE_SCHEMA, Permission.MANAGE_USERS, Permission.MANAGE_API_KEYS, Permission.VIEW_LOGS, },}
def check_permission(user_role: str, required_permission: Permission) -> bool: """Check if a role has a specific permission.""" try: role = Role(user_role) except ValueError: return False return required_permission in ROLE_PERMISSIONS.get(role, set())
def require_role(minimum_role: Role): """ FastAPI dependency that enforces minimum role level. Usage: Depends(require_role(Role.ANALYST)) """ role_hierarchy = {Role.VIEWER: 0, Role.ANALYST: 1, Role.ADMIN: 2}
def checker(current_user: dict): user_role = current_user.get("role", "viewer") try: user_level = role_hierarchy.get(Role(user_role), -1) required_level = role_hierarchy.get(minimum_role, 99) except ValueError: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Invalid role: {user_role}", )
if user_level < required_level: logger.warning( "access_denied", user_role=user_role, required_role=minimum_role.value, user=current_user.get("sub"), ) raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Insufficient permissions. Required: {minimum_role.value}, Current: {user_role}", ) return current_user
return checker1# Cache module123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""Redis Client β Production-grade cache and rate limiting backed by Redis.Falls back to in-memory implementations when Redis is unavailable."""
import jsonimport timeimport hashlibimport structlogfrom typing import Optional
logger = structlog.get_logger()
class RedisCache: """ Redis-backed query cache with TTL and tenant isolation. Replaces InMemoryQueryCache for multi-worker production deployments. """
def __init__(self, redis_url: str, ttl_seconds: int = 300): self.ttl = ttl_seconds self._client = None try: import redis self._client = redis.Redis.from_url( redis_url, decode_responses=True, socket_connect_timeout=5, socket_timeout=3, retry_on_timeout=True, ) # Verify connection self._client.ping() logger.info("redis_cache_connected", url=redis_url.split("@")[-1]) except Exception as e: logger.warning("redis_cache_unavailable", error=str(e)) self._client = None
@property def available(self) -> bool: return self._client is not None
@staticmethod def _make_key(query: str, tenant_id: str = "default") -> str: raw = f"{tenant_id}:{query.strip().lower()}" return f"plainsql:cache:{hashlib.sha256(raw.encode()).hexdigest()[:16]}"
def get(self, query: str, tenant_id: str = "default") -> Optional[dict]: """Retrieve cached query result.""" if not self._client: return None try: key = self._make_key(query, tenant_id) data = self._client.get(key) if data: logger.debug("cache_hit", key=key[:20]) return json.loads(data) except Exception as e: logger.warning("redis_get_failed", error=str(e)) return None
def set(self, query: str, data: dict, tenant_id: str = "default"): """Cache a query result with TTL.""" if not self._client: return try: key = self._make_key(query, tenant_id) self._client.setex(key, self.ttl, json.dumps(data, default=str)) except Exception as e: logger.warning("redis_set_failed", error=str(e))
def invalidate(self, tenant_id: str = "default"): """Clear all cache entries. Note: Since cache keys are SHA-256 hashes of '{tenant_id}:{query}', we cannot filter by tenant from the key alone. This purges all entries. For tenant-isolated purge, store tenant_id in the value and scan. """ if not self._client: return try: pattern = "plainsql:cache:*" cursor = 0 while True: cursor, keys = self._client.scan(cursor, match=pattern, count=100) if keys: self._client.delete(*keys) if cursor == 0: break except Exception as e: logger.warning("redis_invalidate_failed", error=str(e))
def invalidate_all(self): """Clear all cached queries.""" if not self._client: return try: pattern = "plainsql:cache:*" cursor = 0 while True: cursor, keys = self._client.scan(cursor, match=pattern, count=100) if keys: self._client.delete(*keys) if cursor == 0: break except Exception as e: logger.warning("redis_invalidate_all_failed", error=str(e))
class RedisRateLimiter: """ Redis-backed sliding window rate limiter. Shared across all Gunicorn workers for accurate rate limiting. """
def __init__(self, redis_url: str, requests_per_minute: int = 60): self.rpm = requests_per_minute self._client = None self._consecutive_failures = 0 self._max_failures_before_deny = 3 # Fail closed after this many errors try: import redis self._client = redis.Redis.from_url( redis_url, decode_responses=True, socket_connect_timeout=5, socket_timeout=2, ) self._client.ping() logger.info("redis_rate_limiter_connected") except Exception as e: logger.warning("redis_rate_limiter_unavailable", error=str(e)) self._client = None
@property def available(self) -> bool: return self._client is not None
def check(self, key: str) -> bool: """Returns True if request is allowed, False if rate limited.""" if not self._client: return True # Fail open only when Redis was never connected try: redis_key = f"plainsql:ratelimit:{key}" now = time.time() window_start = now - 60
pipe = self._client.pipeline() # Remove old entries outside the window pipe.zremrangebyscore(redis_key, 0, window_start) # Count entries in current window pipe.zcard(redis_key) # Add current request pipe.zadd(redis_key, {str(now): now}) # Set TTL on the key to auto-cleanup pipe.expire(redis_key, 120) results = pipe.execute()
current_count = results[1] self._consecutive_failures = 0 # Reset on success return current_count < self.rpm except Exception as e: self._consecutive_failures += 1 logger.warning( "redis_rate_check_failed", error=str(e), consecutive_failures=self._consecutive_failures, ) # Fail OPEN after repeated Redis failures to maintain service availability during outages if self._consecutive_failures >= self._max_failures_before_deny: logger.warning("rate_limiter_fail_open", reason="redis_unavailable_failing_open") return True return True # Allow during transient errors
def create_cache(redis_url: str = None, ttl_seconds: int = 300): """ Factory: Returns RedisCache if Redis is available, otherwise InMemoryQueryCache. """ if redis_url: cache = RedisCache(redis_url, ttl_seconds) if cache.available: return cache # Fallback to in-memory from app.api.middleware import QueryCache logger.info("using_inmemory_cache_fallback") return QueryCache(ttl_seconds=ttl_seconds)
def create_rate_limiter(redis_url: str = None, rpm: int = 60): """ Factory: Returns RedisRateLimiter if Redis is available, otherwise InMemoryRateLimiter. """ if redis_url: limiter = RedisRateLimiter(redis_url, rpm) if limiter.available: return limiter # Fallback to in-memory from app.api.middleware import InMemoryRateLimiter logger.info("using_inmemory_rate_limiter_fallback") return InMemoryRateLimiter(requests_per_minute=rpm)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""Semantic Cache β Cache query results by embedding similarity.
Instead of requiring exact string matches, this cache finds semanticallysimilar queries that have already been processed. This means: "Show top 5 employees by salary" β cache hit for "List the 5 highest paid employees"
Uses MiniLM-L6-v2 embeddings with cosine similarity threshold.Falls back gracefully when sentence-transformers is unavailable."""
import timeimport osimport threadingimport structlogfrom typing import Optional
logger = structlog.get_logger()
class SemanticCache: """ Embedding-based query cache with TTL and similarity threshold.
Architecture: - Encodes queries using MiniLM-L6-v2 (384-dim embeddings) - Stores (embedding, result, timestamp) tuples - On lookup, computes cosine similarity against all cached embeddings - Returns cached result if similarity >= threshold
Thread-safe for concurrent FastAPI workers. """
def __init__( self, similarity_threshold: float = 0.95, ttl_seconds: int = 300, max_entries: int = 500, ): self._threshold = similarity_threshold self._ttl = ttl_seconds self._max_entries = max_entries self._lock = threading.Lock()
# Cache entries: list of (embedding, result, timestamp, original_query) self._entries: list[tuple] = []
# Lazy-load encoder self._encoder = None self._encoder_loaded = False
def _get_encoder(self): """Lazy-load the sentence encoder on first use.""" if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"): logger.info("semantic_cache_encoder_disabled_by_env") return None
if not self._encoder_loaded: self._encoder_loaded = True try: from sentence_transformers import SentenceTransformer self._encoder = SentenceTransformer("all-MiniLM-L6-v2") logger.info("semantic_cache_encoder_loaded", model="all-MiniLM-L6-v2") except ImportError: logger.info("semantic_cache_disabled", reason="sentence-transformers not installed") except Exception as e: logger.warning("semantic_cache_encoder_failed", error=str(e)) return self._encoder
@property def available(self) -> bool: """Check if semantic caching is available.""" if os.environ.get("DISABLE_ML_INTENT", "false").lower() in ("true", "1", "yes"): return False try: import sentence_transformers import numpy # Reference modules to satisfy unused import checks _ = sentence_transformers _ = numpy return True except ImportError: return False
def get(self, query: str, tenant_id: str = "default") -> Optional[dict]: """ Look up a semantically similar cached result.
Returns the cached result dict if found, None otherwise. """ encoder = self._get_encoder() if not encoder: return None
try: import numpy as np
query_emb = encoder.encode([query])[0] now = time.time()
with self._lock: # Clean expired entries while searching valid_entries = [] best_match = None best_score = 0.0
for entry in self._entries: emb, result, ts, original, tid = entry
# Skip expired if now - ts > self._ttl: continue
# Skip different tenant if tid != tenant_id: valid_entries.append(entry) continue
valid_entries.append(entry)
# Cosine similarity score = float( np.dot(query_emb, emb) / (np.linalg.norm(query_emb) * np.linalg.norm(emb) + 1e-8) )
if score >= self._threshold and score > best_score: best_score = score best_match = result
# Update entries (removes expired) self._entries = valid_entries
if best_match: logger.info( "semantic_cache_hit", query=query[:60], similarity=round(best_score, 3), ) return best_match
except Exception as e: logger.warning("semantic_cache_get_failed", error=str(e))
return None
def set(self, query: str, result: dict, tenant_id: str = "default"): """ Cache a query result with its embedding. """ encoder = self._get_encoder() if not encoder: return
try: embedding = encoder.encode([query])[0]
with self._lock: # Evict oldest if at capacity if len(self._entries) >= self._max_entries: self._entries = self._entries[-(self._max_entries // 2):]
self._entries.append( (embedding, result, time.time(), query, tenant_id) )
logger.debug("semantic_cache_set", query=query[:60])
except Exception as e: logger.warning("semantic_cache_set_failed", error=str(e))
def invalidate(self, tenant_id: str = "default"): """Clear all entries for a tenant.""" with self._lock: self._entries = [ e for e in self._entries if e[4] != tenant_id ]
def invalidate_all(self): """Clear all cache entries.""" with self._lock: self._entries.clear()
def stats(self) -> dict: """Return cache statistics.""" with self._lock: now = time.time() active = sum(1 for e in self._entries if now - e[2] <= self._ttl) return { "total_entries": len(self._entries), "active_entries": active, "max_entries": self._max_entries, "ttl_seconds": self._ttl, "similarity_threshold": self._threshold, "encoder_available": self._encoder is not None, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""PlainSQL Configuration β Pydantic Settings with environment-based config.All secrets loaded from .env, with sensible defaults for local dev."""
from pydantic_settings import BaseSettingsfrom pydantic import Field, model_validatorfrom typing import Optionalfrom functools import lru_cache
_JWT_DEFAULT = "change-me-in-production-use-openssl-rand-hex-32"
class Settings(BaseSettings): """Application settings loaded from environment variables."""
# ββ App ββββββββββββββββββββββββββββββββββββββββββββββ APP_NAME: str = "PlainSQL" APP_VERSION: str = "2.0.0" DEBUG: bool = False ENV: str = Field(default="development", description="development | staging | production")
# ββ Database βββββββββββββββββββββββββββββββββββββββββ DB_URI: str = Field(..., description="MySQL connection URI") DB_POOL_SIZE: int = 10 DB_MAX_OVERFLOW: int = 20 DB_POOL_TIMEOUT: int = 30 DB_QUERY_TIMEOUT: int = 30
# ββ Redis ββββββββββββββββββββββββββββββββββββββββββββ REDIS_URL: str = Field(default="redis://localhost:6379/0") CACHE_TTL_SECONDS: int = 300
# ββ Authentication βββββββββββββββββββββββββββββββββββ JWT_SECRET_KEY: str = Field(default=_JWT_DEFAULT) JWT_ALGORITHM: str = "HS256" JWT_EXPIRY_HOURS: int = 8
# ββ LLM Providers βββββββββββββββββββββββββββββββββββ HUGGINGFACEHUB_API_TOKEN: Optional[str] = None OPENAI_API_KEY: Optional[str] = None ANTHROPIC_API_KEY: Optional[str] = None GROQ_API_KEY: Optional[str] = None GROQ_MODEL_PRIMARY: str = "llama-3.3-70b-versatile" GROQ_MODEL_FAST: str = "llama-3.1-8b-instant" GROQ_BASE_URL: str = "https://api.groq.com/openai/v1" OLLAMA_BASE_URL: str = "http://localhost:11434" DEFAULT_LLM_PROVIDER: str = Field(default="groq", description="groq | huggingface | openai | anthropic | ollama") DEFAULT_MODEL: str = "Qwen/Qwen2.5-Coder-32B-Instruct"
# ββ RAG ββββββββββββββββββββββββββββββββββββββββββββββ CHROMA_PERSIST_DIR: str = "./chroma_db" EMBEDDING_MODEL: str = "all-MiniLM-L6-v2" RAG_TOP_K: int = 5
# ββ Safety βββββββββββββββββββββββββββββββββββββββββββ MAX_QUERY_ROWS: int = 1000 QUERY_TIMEOUT_SECONDS: int = 30
# ββ Rate Limiting ββββββββββββββββββββββββββββββββββββ RATE_LIMIT_RPM: int = 60
# ββ Observability ββββββββββββββββββββββββββββββββββββ LANGSMITH_API_KEY: Optional[str] = None LANGSMITH_PROJECT: str = "plainsql" LOG_LEVEL: str = "INFO"
# ββ CORS βββββββββββββββββββββββββββββββββββββββββββββ CORS_ORIGINS: list[str] = [ "http://localhost:3000", "http://localhost:5173", "http://127.0.0.1:3000", "http://127.0.0.1:5173", "http://localhost:5500", ]
model_config = { "env_file": [".env", "../.env", "../../.env"], "env_file_encoding": "utf-8", "case_sensitive": True, "extra": "ignore", }
@model_validator(mode="after") def _validate_production_secrets(self) -> "Settings": """Prevent deployment with default secrets in production/staging.""" if self.ENV in ("production", "staging"): if self.JWT_SECRET_KEY == _JWT_DEFAULT: raise ValueError( "FATAL: JWT_SECRET_KEY must be changed from the default value " "in production/staging. Generate one with: openssl rand -hex 32" ) if len(self.JWT_SECRET_KEY) < 32: raise ValueError( "FATAL: JWT_SECRET_KEY must be at least 32 characters for production." ) return self
@lru_cache()def get_settings() -> Settings: """Cached settings singleton.""" return Settings()1# DB Package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Database Connection Pool β Production-grade pooled connections via SQLAlchemy engine.Supports multi-tenant databases via tenant_id-based connection routing."""
import timeimport refrom sqlalchemy import create_engine, text, eventfrom sqlalchemy.pool import QueuePoolfrom urllib.parse import urlparse, unquotefrom typing import Optionalfrom contextlib import contextmanagerimport structlog
logger = structlog.get_logger()
# Only allow alphanumeric + underscore in identifiers_SAFE_IDENTIFIER = re.compile(r'^[a-zA-Z0-9_]+$')
def _validate_identifier(name: str, label: str = "identifier"): """Validate that a SQL identifier contains only safe characters.""" if not _SAFE_IDENTIFIER.match(name): raise ValueError(f"Invalid {label}: {name!r}")
class DatabasePool: """ Production database connection pool. Uses SQLAlchemy QueuePool for connection reuse, health checks, and overflow management. Falls back to raw pymysql for schema introspection when needed. """
def __init__( self, db_uri: str, query_timeout: int = 30, pool_size: int = 10, max_overflow: int = 20, pool_timeout: int = 30, ): parsed = urlparse(db_uri) self.host = parsed.hostname self.port = parsed.port or 3306 self.user = parsed.username self.password = unquote(parsed.password) if parsed.password else "" self.db_name = parsed.path[1:] if parsed.path else "chatbot" self.query_timeout = query_timeout
# ββ Build SQLAlchemy engine with connection pool ββ # Construct a clean pymysql URI (no SQLAlchemy dialect prefix issues) safe_password = self.password.replace("@", "%40") engine_uri = f"mysql+pymysql://{self.user}:{safe_password}@{self.host}:{self.port}/{self.db_name}"
connect_kwargs = { "connect_timeout": 10, "read_timeout": query_timeout, "write_timeout": query_timeout, } # TiDB Cloud requires SSL if self.host and "tidbcloud.com" in self.host: import ssl ssl_ctx = ssl.create_default_context() connect_kwargs["ssl"] = ssl_ctx
self._engine = create_engine( engine_uri, poolclass=QueuePool, pool_size=pool_size, max_overflow=max_overflow, pool_timeout=pool_timeout, pool_pre_ping=True, # Verify connections before checkout (stale conn defense) pool_recycle=1800, # Recycle connections every 30 min (MySQL wait_timeout defense) connect_args=connect_kwargs, )
# ββ Set session to READ ONLY for query connections ββ @event.listens_for(self._engine, "checkout") def _set_read_only(dbapi_conn, connection_record, connection_proxy): """Set session to read-only on checkout for defense-in-depth.""" pass # MySQL read-only requires SUPER privilege; rely on SQL validation instead
# ββ In-Memory Schema Cache ββ self._tables = None self._table_schemas = {} self._foreign_keys = {}
self._prepopulate_cache_from_file()
self._validate_connection()
def _prepopulate_cache_from_file(self): """Pre-populate the schema cache from enriched_schema.json if it exists.""" import os import json schema_file = "./chroma_db/enriched_schema.json" if os.path.exists(schema_file): try: with open(schema_file, "r", encoding="utf-8") as f: enriched_tables = json.load(f) tables = [] for item in enriched_tables: table_name = item.get("table_name") if not table_name: continue tables.append(table_name) if "raw_columns" in item: self._table_schemas[table_name] = item["raw_columns"] if "raw_fks" in item: self._foreign_keys[table_name] = item["raw_fks"] if tables: self._tables = tables logger.info("prepopulated_database_schema_cache_from_file", tables=len(tables)) except Exception as e: logger.warning("failed_to_prepopulate_schema_cache", error=str(e))
def _validate_connection(self): """Validate database connectivity on startup.""" try: with self._engine.connect() as conn: conn.execute(text("SELECT 1")) logger.info("database_connected", host=self.host, database=self.db_name, pool_size=self._engine.pool.size()) except Exception as e: logger.error("database_connection_failed", error=str(e)) raise
@contextmanager def get_connection(self): """Context manager for pooled database connections.""" conn = self._engine.connect() try: yield conn finally: conn.close()
def execute_query(self, query: str, params: Optional[dict] = None) -> list[dict]: """Execute a read-only query and return results as list of dicts.""" start_time = time.perf_counter() try: with self._engine.connect() as conn: # Enforce statement-level timeout (milliseconds) to prevent # runaway queries from blocking the thread pool forever. # The socket read_timeout only handles network stalls, not slow SQL. timeout_ms = self.query_timeout * 1000 try: conn.execute(text(f"SET SESSION max_execution_time = {timeout_ms}")) except Exception: pass # Non-critical β older MySQL versions may not support this
if params: result = conn.execute(text(query), params) else: result = conn.execute(text(query)) columns = result.keys() rows = [dict(zip(columns, row)) for row in result.fetchall()] elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) logger.info("db_query_executed", query=query[:200], elapsed_ms=elapsed_ms, row_count=len(rows)) return rows except Exception as e: elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) logger.error("db_query_failed", query=query[:200], elapsed_ms=elapsed_ms, error=str(e)) raise
def _execute_write_internal(self, query: str, params: Optional[tuple] = None): """ Execute a write query. INTERNAL USE ONLY β for schema setup and migrations. User-facing queries MUST go through execute_query after SQL validation. """ start_time = time.perf_counter() try: with self._engine.begin() as conn: if params: # Build named params dict matching :p0, :p1, :p2... placeholders param_dict = {f"p{i}": v for i, v in enumerate(params)} conn.execute(text(query), param_dict) else: conn.execute(text(query)) elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) logger.info("db_write_executed", query=query[:200], elapsed_ms=elapsed_ms) except Exception as e: elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2) logger.error("db_write_failed", query=query[:200], elapsed_ms=elapsed_ms, error=str(e)) raise
def get_tables(self) -> list[str]: """Returns all table names in the current database.""" if self._tables is None: rows = self.execute_query("SHOW TABLES") self._tables = [list(row.values())[0] for row in rows] return self._tables
def get_table_schema(self, table_name: str) -> list[dict]: """Returns column details for a specific table.""" if table_name not in self._table_schemas: _validate_identifier(table_name, "table_name") rows = self.execute_query(f"DESCRIBE `{table_name}`") self._table_schemas[table_name] = [ { "name": row["Field"], "type": row["Type"], "null": row["Null"], "key": row["Key"], "default": row["Default"], } for row in rows ] return self._table_schemas[table_name]
def get_foreign_keys(self, table_name: str) -> list[dict]: """Returns foreign key relationships for a table.""" if table_name not in self._foreign_keys: query = """ SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = :schema_name AND TABLE_NAME = :table_name AND REFERENCED_TABLE_NAME IS NOT NULL """ self._foreign_keys[table_name] = self.execute_query(query, {"schema_name": self.db_name, "table_name": table_name}) return self._foreign_keys[table_name]
def clear_schema_cache(self): """Clears all schema caching to allow schema refreshes.""" self._tables = None self._table_schemas.clear() self._foreign_keys.clear() logger.info("database_schema_cache_cleared")
def get_sample_values(self, table_name: str, column_name: str, limit: int = 5) -> list: """Returns sample distinct values for a column.""" _validate_identifier(table_name, "table_name") _validate_identifier(column_name, "column_name") try: query = f"SELECT DISTINCT `{column_name}` FROM `{table_name}` LIMIT :lim" rows = self.execute_query(query, {"lim": limit}) return [list(r.values())[0] for r in rows] except Exception: return []
def get_row_count(self, table_name: str) -> int: """Returns approximate row count for a table.""" try: rows = self.execute_query(f"SELECT COUNT(*) as cnt FROM `{table_name}`") return rows[0]["cnt"] if rows else 0 except Exception: return 0 def get_full_schema(self) -> str: """Generates a complete text representation of the database schema.""" tables = self.get_tables() schema_text = ""
for table in tables: columns = self.get_table_schema(table) schema_text += f"Table: {table}\nColumns:\n" for col in columns: schema_text += f" - {col['name']} ({col['type']})" if col['key'] == 'PRI': schema_text += " [PRIMARY KEY]" if col['key'] == 'MUL': schema_text += " [FOREIGN KEY]" schema_text += "\n"
# Add foreign key relationships fks = self.get_foreign_keys(table) if fks: schema_text += "Relationships:\n" for fk in fks: schema_text += f" - {fk['COLUMN_NAME']} β {fk['REFERENCED_TABLE_NAME']}.{fk['REFERENCED_COLUMN_NAME']}\n" schema_text += "\n"
return schema_text
def get_pool_status(self) -> dict: """Returns current connection pool statistics.""" pool = self._engine.pool return { "pool_size": pool.size(), "checked_out": pool.checkedout(), "overflow": pool.overflow(), "checked_in": pool.checkedin(), }
class TenantRegistry: """ Multi-tenant database connection registry. Maps tenant_id β DatabasePool for isolated data access.
NOTE: Currently scaffolding β not used in production. The system operates as single-tenant with tenant_id used only for cache isolation. For true multi-tenancy, instantiate this registry in main.py and pass tenant-specific pools to the orchestrator. """
def __init__(self): self._pools: dict[str, DatabasePool] = {}
def register(self, tenant_id: str, db_uri: str, query_timeout: int = 30): """Register a new tenant database.""" self._pools[tenant_id] = DatabasePool(db_uri, query_timeout) logger.info("tenant_registered", tenant_id=tenant_id)
def get_pool(self, tenant_id: str) -> DatabasePool: """Get the database pool for a tenant.""" pool = self._pools.get(tenant_id) if not pool: raise ValueError(f"No database registered for tenant: {tenant_id}") return pool
def list_tenants(self) -> list[str]: """List all registered tenant IDs.""" return list(self._pools.keys())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Conversation Persistence β MySQL-backed chat history management.
Provides CRUD operations for conversations and messages, enablingcross-device chat persistence and server-side state management."""
import uuidfrom typing import Optionalimport structlog
logger = structlog.get_logger()
# ββ Schema Migration βββββββββββββββββββββββββββββββββββββββββ
CONVERSATIONS_DDL = """CREATE TABLE IF NOT EXISTS conversations ( id VARCHAR(36) PRIMARY KEY, user_id VARCHAR(64) NOT NULL DEFAULT 'anonymous', title VARCHAR(255) NOT NULL DEFAULT 'New analysis', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_user (user_id), INDEX idx_updated (updated_at DESC)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"""
MESSAGES_DDL = """CREATE TABLE IF NOT EXISTS messages ( id VARCHAR(36) PRIMARY KEY, conversation_id VARCHAR(36) NOT NULL, role ENUM('user', 'assistant') NOT NULL, content TEXT, generated_sql TEXT, explanation TEXT, friendly_message TEXT, intent VARCHAR(32), execution_time_ms FLOAT DEFAULT 0, row_count INT DEFAULT 0, result_data JSON, feedback ENUM('up', 'down') DEFAULT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_conversation (conversation_id), INDEX idx_created (created_at), FOREIGN KEY (conversation_id) REFERENCES conversations(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"""
def ensure_tables(db_pool) -> bool: """Auto-create conversations and messages tables on startup.""" try: db_pool._execute_write_internal(CONVERSATIONS_DDL) db_pool._execute_write_internal(MESSAGES_DDL) logger.info("persistence_tables_ready") return True except Exception as e: logger.warning("persistence_migration_failed", error=str(e)) return False
# ββ Conversation Manager βββββββββββββββββββββββββββββββββββββ
class ConversationManager: """ Server-side conversation and message persistence. Replaces localStorage-based chat history with MySQL storage. """
def __init__(self, db_pool): self.db_pool = db_pool
# ββ Conversations ββββββββββββββββββββββββββββββββββββ
def list_conversations(self, user_id: str = "anonymous", limit: int = 50) -> list[dict]: """List conversations for a user, most recent first.""" rows = self.db_pool.execute_query( """SELECT c.id, c.title, c.created_at, c.updated_at, COUNT(m.id) as message_count FROM conversations c LEFT JOIN messages m ON m.conversation_id = c.id WHERE c.user_id = :user_id GROUP BY c.id ORDER BY c.updated_at DESC LIMIT :lim""", {"user_id": user_id, "lim": limit}, ) return [ { "id": r["id"], "title": r["title"], "message_count": r["message_count"], "created_at": str(r["created_at"]), "updated_at": str(r["updated_at"]), } for r in rows ]
def create_conversation(self, title: str = "New analysis", user_id: str = "anonymous") -> dict: """Create a new conversation and return its metadata.""" conv_id = str(uuid.uuid4())[:36] self.db_pool._execute_write_internal( "INSERT INTO conversations (id, user_id, title) VALUES (:p0, :p1, :p2)", (conv_id, user_id, title[:255]), ) logger.info("conversation_created", conversation_id=conv_id) return {"id": conv_id, "title": title, "message_count": 0}
def update_title(self, conversation_id: str, title: str): """Update a conversation's title.""" self.db_pool._execute_write_internal( "UPDATE conversations SET title = :p0 WHERE id = :p1", (title[:255], conversation_id), )
def delete_conversation(self, conversation_id: str, user_id: str = "anonymous"): """Delete a conversation and all its messages (cascade).""" self.db_pool._execute_write_internal( "DELETE FROM conversations WHERE id = :p0 AND user_id = :p1", (conversation_id, user_id), ) logger.info("conversation_deleted", conversation_id=conversation_id)
# ββ Messages βββββββββββββββββββββββββββββββββββββββββ
def get_messages(self, conversation_id: str, limit: int = 200) -> list[dict]: """Get all messages in a conversation, oldest first.""" rows = self.db_pool.execute_query( """SELECT id, role, content, generated_sql, explanation, friendly_message, intent, execution_time_ms, row_count, result_data, feedback, created_at FROM messages WHERE conversation_id = :conv_id ORDER BY created_at ASC LIMIT :lim""", {"conv_id": conversation_id, "lim": limit}, ) results = [] for r in rows: msg = { "id": r["id"], "role": r["role"], "content": r["content"] or "", "created_at": str(r["created_at"]), } if r["role"] == "assistant": msg["data"] = { "sql": r["generated_sql"] or "", "explanation": r["explanation"] or "", "message": r["friendly_message"] or "", "intent": r["intent"] or "", "execution_time_ms": r["execution_time_ms"] or 0, "row_count": r["row_count"] or 0, } # Parse stored JSON result data if r["result_data"]: try: import json msg["data"]["answer"] = json.loads(r["result_data"]) if isinstance(r["result_data"], str) else r["result_data"] except (json.JSONDecodeError, TypeError): msg["data"]["answer"] = [] msg["_feedback"] = r["feedback"] results.append(msg) return results
def save_user_message(self, conversation_id: str, content: str) -> str: """Save a user message and return its ID.""" msg_id = str(uuid.uuid4())[:36] self.db_pool._execute_write_internal( """INSERT INTO messages (id, conversation_id, role, content) VALUES (:p0, :p1, :p2, :p3)""", (msg_id, conversation_id, "user", content), ) return msg_id
def save_assistant_message( self, conversation_id: str, content: str, generated_sql: str = "", explanation: str = "", friendly_message: str = "", intent: str = "", execution_time_ms: float = 0, row_count: int = 0, result_data: Optional[list] = None, ) -> str: """Save an assistant response and return its ID.""" import json msg_id = str(uuid.uuid4())[:36] result_json = json.dumps(result_data[:100] if result_data else [], default=str) self.db_pool._execute_write_internal( """INSERT INTO messages (id, conversation_id, role, content, generated_sql, explanation, friendly_message, intent, execution_time_ms, row_count, result_data) VALUES (:p0, :p1, :p2, :p3, :p4, :p5, :p6, :p7, :p8, :p9, :p10)""", ( msg_id, conversation_id, "assistant", content, generated_sql, explanation, friendly_message, intent, execution_time_ms, row_count, result_json, ), ) return msg_id
def update_feedback(self, message_id: str, rating: str): """Update feedback rating on a message.""" self.db_pool._execute_write_internal( "UPDATE messages SET feedback = :p0 WHERE id = :p1", (rating, message_id), )
def get_conversation_context(self, conversation_id: str, limit: int = 6) -> list[dict]: """Get recent user/sql pairs for conversation context (used by SQL generation).""" rows = self.db_pool.execute_query( """SELECT role, content, generated_sql FROM messages WHERE conversation_id = :conv_id ORDER BY created_at DESC LIMIT :lim""", {"conv_id": conversation_id, "lim": limit * 2}, ) context = [] for r in reversed(rows): if r["role"] == "user": context.append({"user": r["content"]}) elif r["role"] == "assistant" and r["generated_sql"] and context: context[-1]["sql"] = r["generated_sql"] return context[-limit:].env.exampleAdded+56
.gitattributes-1
.gitignoreAdded+49
DockerfileAdded+38
backend/alembic.iniAdded+37
backend/alembic/env.pyAdded+73
backend/alembic/script.py.makoAdded+24
backend/alembic/versions/001_initial_plainsql_tables.pyAdded+54
backend/app/__init__.pyAdded+2
backend/app/agents/__init__.pyAdded+1
backend/app/agents/execution.pyAdded+140
backend/app/agents/guardrails.pyAdded+264
backend/app/agents/intent_classifier.pyAdded+314
backend/app/agents/ml_classifier.pyAdded+144
backend/app/agents/models/__init__.pyAdded+1
backend/app/agents/models/intent_model.joblibAdded
backend/app/agents/models/train_classifier.pyAdded+130
backend/app/agents/models/training_data.jsonAdded+173
backend/app/agents/orchestrator.pyAdded+856
backend/app/agents/query_understanding.pyAdded+276
backend/app/agents/result_summary.pyAdded+326
backend/app/agents/schema_retrieval.pyAdded+220
backend/app/agents/sql_generation.pyAdded+159
backend/app/agents/sql_validation.pyAdded+198
backend/app/agents/state.pyAdded+73
backend/app/agents/visualization.pyAdded+222
backend/app/ai_features/__init__.pyAdded+1
backend/app/ai_features/anomaly.pyAdded+105
backend/app/ai_features/explainer.pyAdded+29
backend/app/ai_features/insights.pyAdded+135
backend/app/api/__init__.pyAdded+1
backend/app/api/fast_path.pyAdded+55
backend/app/api/middleware.pyAdded+175
backend/app/api/routes/__init__.pyAdded+1
backend/app/api/routes/admin.pyAdded+116
backend/app/api/routes/chat.pyAdded+156
backend/app/api/routes/conversations.pyAdded+83
backend/app/api/routes/monitoring.pyAdded+70
backend/app/api/routes/system.pyAdded+193
backend/app/api/schemas.pyAdded+135
backend/app/auth/__init__.pyAdded+1
backend/app/auth/jwt_auth.pyAdded+109
backend/app/auth/rbac.pyAdded+93
backend/app/cache/__init__.pyAdded+1
backend/app/cache/redis_client.pyAdded+201
backend/app/cache/semantic_cache.pyAdded+198
backend/app/config.pyAdded+103
backend/app/db/__init__.pyAdded+1
backend/app/db/connection.pyAdded+314
backend/app/db/persistence.pyAdded+228