""" 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