""" Intent Classification Guardrail. LLM-based classification to determine whether a user query is: - ACPC_RELATED → proceed to retrieval - GREETINGS/SMALL TALK → proceed to retrieval - OFF_TOPIC → block with fallback - INJECTION → block with fallback (includes personal info requests) """ import logging from langchain_core.messages import HumanMessage from app.utils.llm_helpers import get_llm from app.agent.prompts import INTENT_CLASSIFICATION_PROMPT logger = logging.getLogger(__name__) # Valid classification labels — anything else is treated as blocked VALID_LABELS = ("ACPC_RELATED", "GREETINGS / SMALL TALK", "OFF_TOPIC", "INJECTION") async def classify_query(query: str) -> dict: """Classify a user query using LLM-based intent detection. Returns: dict with: - "classification": one of VALID_LABELS or "UNKNOWN" - "route": "retrieve" if ACPC_RELATED, "fallback" otherwise - "blocked_reason": None if allowed, else the classification label """ if not query or not query.strip(): logger.warning("Empty query passed to classify_query") return { "classification": "UNKNOWN", "route": "fallback", "blocked_reason": "empty_query", } llm = get_llm(temperature=0.0) prompt = INTENT_CLASSIFICATION_PROMPT.format(query=query) try: response = await llm.ainvoke([HumanMessage(content=prompt)]) classification = response.content.strip().upper() except Exception as e: logger.error("LLM error in classify_query: %s — defaulting to fallback", e) return { "classification": "UNKNOWN", "route": "fallback", "blocked_reason": "llm_error", } # Default-deny: if LLM returns something unexpected, block it if classification not in VALID_LABELS: logger.warning( "Invalid classification '%s' (expected one of %s) — blocking", classification, VALID_LABELS, ) return { "classification": classification, "route": "fallback", "blocked_reason": "invalid_classification", } logger.info("Intent classification: %s for query: %s", classification, query[:80]) # Only ACPC_RELATED passes through if classification == "ACPC_RELATED" or classification == "GREETINGS / SMALL TALK": return { "classification": classification, "route": "retrieve", "blocked_reason": None, } return { "classification": classification, "route": "fallback", "blocked_reason": classification.lower(), }