File size: 1,738 Bytes
c223b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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}