Sakhi-AI / intent_engine.py
Prof-chaos-5
Initial commit
c223b53
Raw
History Blame Contribute Delete
1.74 kB
"""
Intent Engine for Sakhi.
Classifies user queries to adapt the AI's teaching strategy.
"""
import json
import logging
from typing import Dict
logger = logging.getLogger(__name__)
class IntentDetector:
def __init__(self, llm_client):
self.llm = llm_client
def detect(self, query: str) -> Dict[str, str]:
"""Returns dict containing 'intent' and 'topic'."""
if not query or len(query.split()) < 2:
return {"intent": "Explain", "topic": query}
# Fast heuristic checks to save LLM calls
q_lower = query.lower()
if any(w in q_lower for w in ["quiz", "test", "question", "sawaal", "mcq"]):
return {"intent": "Quiz", "topic": query}
if any(w in q_lower for w in ["difference", "compare", "vs", "antar"]):
return {"intent": "Compare", "topic": query}
# Fallback to LLM intent detection
from prompt_templates import INTENT_DETECTION_PROMPT
prompt = INTENT_DETECTION_PROMPT.format(query=query)
try:
# We use a low temperature for predictable JSON
response = self.llm._chat_completion(
system_prompt="You are an intent classifier. Output JSON only.",
user_prompt=prompt,
max_tokens=100,
temperature=0.1
)
# Parse JSON
cleaned = response.split("```json")[-1].split("```")[0].strip() if "```" in response else response.strip()
result = json.loads(cleaned)
return result
except Exception as e:
logger.warning(f"Intent detection failed, defaulting to Explain. Error: {e}")
return {"intent": "Explain", "topic": query}