acpc-testing-third / app /guardrails /intent_classifier.py
Stoic-2910's picture
Upload 116 files
f6dea0d verified
Raw History Blame Contribute Delete
2.7 kB
"""
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(),
}