File size: 9,866 Bytes
6086e71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
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_intent
from 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?\""
    )