File size: 5,495 Bytes
af25a2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""

Explainer - Explains concepts and topics clearly

"""

from typing import Tuple, Dict
from config import LLM_PROVIDER
from core.llm_engine import LLMEngine
from core.prompt_builder import PromptBuilder
from core.validator import InputValidator, ContentValidator
from core.utils import log_event, truncate_text


class Explainer:
    """Explains concepts and topics in different ways."""
    
    def __init__(self, llm_provider: str = LLM_PROVIDER):
        """

        Initialize explainer.

        

        Args:

            llm_provider: LLM provider to use

        """
        self.engine = LLMEngine(llm_provider)
        self.prompt_builder = PromptBuilder()
        self.validator = InputValidator()
    
    def explain(

        self,

        concept: str,

        context: str = "",

        mode: str = "normal"

    ) -> Tuple[bool, str]:
        """

        Explain a concept.

        

        Args:

            concept: Concept or topic to explain

            context: Optional context/notes

            mode: Explanation mode (normal, detailed, teacher)

        

        Returns:

            Tuple of (success, explanation)

        """
        # Validate inputs
        is_valid, msg = self.validator.validate_input(concept)
        if not is_valid:
            log_event("VALIDATION_ERROR", f"Explainer: {msg}")
            return False, msg
        
        if len(concept) < 5:
            return False, "Concept too short. Please provide more detail."
        
        # Build prompt
        try:
            prompt = self.prompt_builder.build_explanation_prompt(
                concept,
                context=truncate_text(context, 2000) if context else "",
                mode=mode
            )
            log_event("PROMPT_BUILT", "Explanation prompt ready")
        except Exception as e:
            log_event("PROMPT_ERROR", f"Error building explanation: {str(e)}")
            return False, f"Error: {str(e)}"
        
        # Generate explanation
        success, explanation = self.engine.generate(prompt, max_tokens=1500)
        
        if not success:
            log_event("EXPLANATION_ERROR", explanation)
            return False, explanation
        
        # Quality check
        is_meaningful = ContentValidator.is_meaningful_response(explanation, min_words=15)
        if not is_meaningful:
            log_event("QUALITY_CHECK_FAILED", "Explanation too short")
            return False, "Explanation too short. Please try again."
        
        quality_score = ContentValidator.estimate_quality(explanation)
        log_event("QUALITY_SCORE", f"Explanation quality: {quality_score:.2f}")
        
        log_event("EXPLANATION_SUCCESS", f"Explanation generated")
        return True, explanation
    
    def simple_explain(self, concept: str) -> Tuple[bool, str]:
        """

        Explain in simple, basic terms.

        

        Args:

            concept: Concept to explain

        

        Returns:

            Tuple of (success, explanation)

        """
        return self.explain(concept, mode="teacher")
    
    def expert_explain(self, concept: str, context: str = "") -> Tuple[bool, str]:
        """

        Provide expert-level explanation.

        

        Args:

            concept: Concept to explain

            context: Related context

        

        Returns:

            Tuple of (success, explanation)

        """
        return self.explain(concept, context=context, mode="detailed")
    
    def exam_style_explain(self, concept: str) -> Tuple[bool, str]:
        """

        Explain in exam-answer format.

        

        Args:

            concept: Concept to explain

        

        Returns:

            Tuple of (success, explanation)

        """
        return self.explain(concept, mode="exam")
    
    def compare_explanations(

        self,

        concept: str,

        modes: list = None

    ) -> Tuple[bool, Dict]:
        """

        Compare explanations in different modes.

        

        Args:

            concept: Concept to explain

            modes: List of modes to compare

        

        Returns:

            Tuple of (success, dict of explanations)

        """
        if modes is None:
            modes = ["normal", "detailed", "teacher"]
        
        explanations = {}
        
        for mode in modes:
            success, explanation = self.explain(concept, mode=mode)
            explanations[mode] = explanation if success else f"Error: {explanation}"
        
        return True, explanations
    
    def explain_with_examples(self, concept: str) -> Tuple[bool, str]:
        """

        Explain concept with real-world examples.

        

        Args:

            concept: Concept to explain

        

        Returns:

            Tuple of (success, explanation)

        """
        enhanced_prompt = f"""Explain '{concept}' with multiple real-world examples.

        

Include:

1. Simple definition

2. Why it matters

3. At least 3 real-world examples

4. Visual description if applicable

5. Common misconceptions

"""
        
        try:
            success, explanation = self.engine.generate(enhanced_prompt, max_tokens=1500)
            return success, explanation
        except Exception as e:
            return False, f"Error: {str(e)}"


# Type hint for dict import
from typing import Dict