| """ |
| 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} |
|
|
| |
| 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} |
| |
| |
| from prompt_templates import INTENT_DETECTION_PROMPT |
| prompt = INTENT_DETECTION_PROMPT.format(query=query) |
| |
| try: |
| |
| response = self.llm._chat_completion( |
| system_prompt="You are an intent classifier. Output JSON only.", |
| user_prompt=prompt, |
| max_tokens=100, |
| temperature=0.1 |
| ) |
| |
| 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} |