Update conversation_logic.py
Browse files1234147 unmodified lines1521531541551561572 unmodified lines16016116216316416513 unmodified lines17918018118218318432 unmodified lines21721821922022122211 unmodified lines23423523623723823924024124224324443 unmodified lines28828929029129229334 unmodified lines328329330331332333334335336337338339340341342343344345346475 unmodified lines82282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886955 unmodified lines9259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709715 unmodified lines977978979980981982983984985986123 unmodified lines11101111111211131114111511161117111811191120112111221123# conversation_logic.pyfrom __future__ import annotationsimport re147 unmodified linesreturn cleaneddef _compose_reply(result: SolverResult,intent: str,2 unmodified lines) -> str:steps = _safe_steps(result.steps or [])topic = (result.topic or "").lower().strip()def topic_hint_fallback() -> str:if topic == "algebra":13 unmodified linesreturn "Focus on the main relationship first."def topic_method_fallback() -> str:if topic == "algebra":return "\n".join(["- Treat it as an equation.",32 unmodified linesreturn "I can explain the method, but I do not have enough structured steps yet."if intent == "hint":if steps:first = steps[0].lower()11 unmodified linesreturn topic_hint_fallback()if intent == "instruction":if steps:return f"First step: {steps[0]}"return "First, identify the key relationship or comparison in the question."if intent == "definition":if steps:return f"Here is the idea in context:\n- {steps[0]}"return "This is asking for the meaning of the term or idea in the question."43 unmodified linesreturn "\n".join(f"- {s}" for s in shown_steps)if normalize_category(category) == "Verbal":return "I can help analyse the wording or logic, but I need the full question text to guide you properly."34 unmodified linesreturn any(p in t for p in explainer_signals)def _normalize_text(text: str) -> str:return re.sub(r"\s+", " ", (text or "").strip().lower())def _extract_keywords(text: str) -> Set[str]:raw = re.findall(r"[a-zA-Z][a-zA-Z0-9_+-]*", (text or "").lower())stop = {"the", "a", "an", "is", "are", "to", "of", "for", "and", "or", "in", "on", "at", "by", "this", "that","it", "be", "do", "i", "me", "my", "you", "how", "what", "why", "give", "show", "please", "can",}return {w for w in raw if len(w) > 2 and w not in stop}def _infer_structure_terms(question_text: str, topic: Optional[str], question_type: Optional[str]) -> List[str]:terms: List[str] = []475 unmodified linesreturn best_linedef _safe_meta_list(items: Any) -> List[str]:if not items:return []if isinstance(items, list):return [str(x).strip() for x in items if str(x).strip()]if isinstance(items, tuple):return [str(x).strip() for x in items if str(x).strip()]if isinstance(items, str):text = items.strip()return [text] if text else []return []def _safe_meta_text(value: Any) -> Optional[str]:if value is None:return Nonetext = str(value).strip()return text or Nonedef _extract_explainer_scaffold(explainer_result: Any) -> Dict[str, Any]:scaffold = getattr(explainer_result, "scaffold", None)if scaffold is None:return {}return {"concept": _safe_meta_text(getattr(scaffold, "concept", None)),"ask": _safe_meta_text(getattr(scaffold, "ask", None)),"givens": _safe_meta_list(getattr(scaffold, "givens", [])),"target": _safe_meta_text(getattr(scaffold, "target", None)),"setup_actions": _safe_meta_list(getattr(scaffold, "setup_actions", [])),"intermediate_steps": _safe_meta_list(getattr(scaffold, "intermediate_steps", [])),"first_move": _safe_meta_text(getattr(scaffold, "first_move", None)),"next_hint": _safe_meta_text(getattr(scaffold, "next_hint", None)),"common_traps": _safe_meta_list(getattr(scaffold, "common_traps", [])),"variables_to_define": _safe_meta_list(getattr(scaffold, "variables_to_define", [])),"equations_to_form": _safe_meta_list(getattr(scaffold, "equations_to_form", [])),"answer_hidden": bool(getattr(scaffold, "answer_hidden", True)),}class ConversationEngine:def __init__(self,55 unmodified linesmeta={},)# 1. explainer path firstif is_explainer_request(user_text or solver_input):explainer_result = route_explainer(solver_input)if explainer_result is not None and getattr(explainer_result, "understood", False):reply = format_explainer_response(result=explainer_result,tone=tone,verbosity=verbosity,transparency=transparency,)scaffold_meta = _extract_explainer_scaffold(explainer_result)result.domain = "quant" if is_quant else "general"result.solved = Falseresult.help_mode = "explain"result.topic = getattr(explainer_result, "topic", None) or question_topicresult.answer_letter = Noneresult.answer_value = Noneresult.internal_answer = Noneresult.used_retrieval = Falseresult.used_generator = Falseresult.reply = replyresult.meta = {"intent": "explain_question","question_text": question_text or "","options_count": len(options_text or []),"category": inferred_category,"question_type": question_type,"classified_topic": question_topic,"explainer_used": True,"bridge_ready": bool(getattr(explainer_result, "meta", {}).get("bridge_ready", False)),"hint_style": getattr(explainer_result, "meta", {}).get("hint_style"),"explainer_summary": getattr(explainer_result, "summary", None),"explainer_teaching_points": _safe_meta_list(getattr(explainer_result, "teaching_points", [])),"scaffold": scaffold_meta,}return result# 2. normal solver pathif is_quant:5 unmodified linesresult.help_mode = resolved_help_modeif not result.topic or result.topic in {"general_quant", "general", "unknown"}:result.topic = question_topicresult.domain = "quant"# 3. compose base replyreply = _compose_reply(result=result,123 unmodified linesresult.internal_answer = Noneresult.reply = replyresult.help_mode = resolved_help_moderesult.meta = {"intent": resolved_intent,"question_text": question_text or "","options_count": len(options_text or []),"category": inferred_category,"question_type": question_type,"classified_topic": question_topic,"explainer_used": False,}return result123147 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523532 unmodified lines35635735835936036136236336436536636736836937037137213 unmodified lines38638738838939039139239339432 unmodified lines42742842943043143243343443511 unmodified lines44744844945045145245345445545645745845946046143 unmodified lines50550650750850951051151251334 unmodified lines548549550551552553475 unmodified lines10291030103110321033103455 unmodified lines10901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711385 unmodified lines1144114511461147114811491150115111521153115411551156115711581159116011611162116311641165123 unmodified lines1289129012911292129312941295129612971298129913001301130213031304from __future__ import annotationsimport re147 unmodified linesreturn cleaneddef _normalize_text(text: str) -> str:return re.sub(r"\s+", " ", (text or "").strip().lower())def _extract_keywords(text: str) -> Set[str]:raw = re.findall(r"[a-zA-Z][a-zA-Z0-9_+-]*", (text or "").lower())stop = {"the", "a", "an", "is", "are", "to", "of", "for", "and", "or", "in", "on", "at", "by", "this", "that","it", "be", "do", "i", "me", "my", "you", "how", "what", "why", "give", "show", "please", "can",}return {w for w in raw if len(w) > 2 and w not in stop}def _safe_meta_list(items: Any) -> List[str]:if not items:return []if isinstance(items, list):return [str(x).strip() for x in items if str(x).strip()]if isinstance(items, tuple):return [str(x).strip() for x in items if str(x).strip()]if isinstance(items, str):text = items.strip()return [text] if text else []return []def _safe_meta_text(value: Any) -> Optional[str]:if value is None:return Nonetext = str(value).strip()return text or Nonedef _extract_explainer_scaffold(explainer_result: Any) -> Dict[str, Any]:scaffold = getattr(explainer_result, "scaffold", None)if scaffold is None:return {}return {"concept": _safe_meta_text(getattr(scaffold, "concept", None)),"ask": _safe_meta_text(getattr(scaffold, "ask", None)),"givens": _safe_meta_list(getattr(scaffold, "givens", [])),"target": _safe_meta_text(getattr(scaffold, "target", None)),"setup_actions": _safe_meta_list(getattr(scaffold, "setup_actions", [])),"intermediate_steps": _safe_meta_list(getattr(scaffold, "intermediate_steps", [])),"first_move": _safe_meta_text(getattr(scaffold, "first_move", None)),"next_hint": _safe_meta_text(getattr(scaffold, "next_hint", None)),"common_traps": _safe_meta_list(getattr(scaffold, "common_traps", [])),"variables_to_define": _safe_meta_list(getattr(scaffold, "variables_to_define", [])),"equations_to_form": _safe_meta_list(getattr(scaffold, "equations_to_form", [])),"answer_hidden": bool(getattr(scaffold, "answer_hidden", True)),}def _build_scaffold_reply(intent: str,help_mode: str,scaffold: Dict[str, Any],summary: Optional[str],teaching_points: List[str],verbosity: float,transparency: float,) -> Optional[str]:if not scaffold and not summary and not teaching_points:return Noneask = _safe_meta_text(scaffold.get("ask")) if scaffold else Nonefirst_move = _safe_meta_text(scaffold.get("first_move")) if scaffold else Nonenext_hint = _safe_meta_text(scaffold.get("next_hint")) if scaffold else Nonesetup_actions = _safe_meta_list(scaffold.get("setup_actions", [])) if scaffold else []intermediate_steps = _safe_meta_list(scaffold.get("intermediate_steps", [])) if scaffold else []variables_to_define = _safe_meta_list(scaffold.get("variables_to_define", [])) if scaffold else []equations_to_form = _safe_meta_list(scaffold.get("equations_to_form", [])) if scaffold else []common_traps = _safe_meta_list(scaffold.get("common_traps", [])) if scaffold else []target_mode = help_mode or intentif target_mode == "hint" or intent == "hint":if first_move:return first_moveif next_hint:return next_hintif setup_actions:return setup_actions[0]if ask:return askif teaching_points:return teaching_points[0]return Noneif target_mode == "instruction" or intent == "instruction":if first_move:return f"First step: {first_move}"if setup_actions:return f"First step: {setup_actions[0]}"if ask:return f"First, identify this: {ask}"return Noneif target_mode == "definition" or intent == "definition":if summary:return summaryif teaching_points:return f"Here is the idea in context:\n- {teaching_points[0]}"if ask:return askreturn Noneif target_mode in {"walkthrough", "step_by_step"} or intent in {"walkthrough", "step_by_step"}:lines: List[str] = []sequence: List[str] = []if ask:sequence.append(f"Identify this first: {ask}")sequence.extend(setup_actions)sequence.extend(intermediate_steps)if first_move and first_move not in sequence:sequence.insert(0, first_move)if next_hint and next_hint not in sequence:sequence.append(next_hint)if not sequence and summary:sequence.append(summary)if not sequence and teaching_points:sequence.extend(teaching_points[:3])if not sequence:return Noneif verbosity < 0.25:shown = sequence[:1]elif verbosity < 0.6:shown = sequence[:2]elif verbosity < 0.85:shown = sequence[:4]else:shown = sequence[:6]return "\n".join(f"- {s}" for s in shown)if target_mode in {"method", "concept", "explain"} or intent in {"method", "concept", "explain"}:lines: List[str] = []if summary:lines.append(summary)if ask:lines.append(f"Start by identifying: {ask}")core_steps: List[str] = []if first_move:core_steps.append(first_move)core_steps.extend(setup_actions[:3])if transparency >= 0.45:core_steps.extend(intermediate_steps[:2])if core_steps:lines.extend(core_steps[:1] if verbosity < 0.35 else core_steps[:3] if verbosity < 0.75 else core_steps[:5])if transparency >= 0.55 and variables_to_define:lines.append(f"Useful variable setup: {variables_to_define[0]}")if transparency >= 0.6 and equations_to_form:lines.append(f"Key equation: {equations_to_form[0]}")if transparency >= 0.65 and next_hint:lines.append(f"Next idea: {next_hint}")if (transparency >= 0.75 or verbosity >= 0.75) and common_traps:lines.append(f"Watch out for: {common_traps[0]}")if not lines and teaching_points:lines.extend(teaching_points[:2])if not lines:return Nonereturn "\n".join(f"- {s}" if not s.startswith("- ") and len(lines) > 1 else s for s in lines)# generic fallbackif first_move:return first_moveif setup_actions:return setup_actions[0]if summary:return summaryif teaching_points:return teaching_points[0]return Nonedef _compose_reply(result: SolverResult,intent: str,2 unmodified lines) -> str:steps = _safe_steps(result.steps or [])topic = (result.topic or "").lower().strip()meta = result.meta or {}scaffold_reply = _build_scaffold_reply(intent=intent,help_mode=result.help_mode,scaffold=meta.get("scaffold", {}) if isinstance(meta, dict) else {},summary=_safe_meta_text(meta.get("explainer_summary")) if isinstance(meta, dict) else None,teaching_points=_safe_meta_list(meta.get("explainer_teaching_points", [])) if isinstance(meta, dict) else [],verbosity=verbosity,transparency=0.5,)def topic_hint_fallback() -> str:if topic == "algebra":13 unmodified linesreturn "Focus on the main relationship first."def topic_method_fallback() -> str:if scaffold_reply:return scaffold_replyif topic == "algebra":return "\n".join(["- Treat it as an equation.",32 unmodified linesreturn "I can explain the method, but I do not have enough structured steps yet."if intent == "hint":if scaffold_reply:return scaffold_replyif steps:first = steps[0].lower()11 unmodified linesreturn topic_hint_fallback()if intent == "instruction":if scaffold_reply:return scaffold_replyif steps:return f"First step: {steps[0]}"return "First, identify the key relationship or comparison in the question."if intent == "definition":if scaffold_reply:return scaffold_replyif steps:return f"Here is the idea in context:\n- {steps[0]}"return "This is asking for the meaning of the term or idea in the question."43 unmodified linesreturn "\n".join(f"- {s}" for s in shown_steps)if scaffold_reply:return scaffold_replyif normalize_category(category) == "Verbal":return "I can help analyse the wording or logic, but I need the full question text to guide you properly."34 unmodified linesreturn any(p in t for p in explainer_signals)def _infer_structure_terms(question_text: str, topic: Optional[str], question_type: Optional[str]) -> List[str]:terms: List[str] = []475 unmodified linesreturn best_lineclass ConversationEngine:def __init__(self,55 unmodified linesmeta={},)# 1. Try explainer early so scaffold is available even when solver is weakexplainer_result = route_explainer(solver_input)explainer_understood = bool(explainer_result is not None and getattr(explainer_result, "understood", False))explainer_scaffold = _extract_explainer_scaffold(explainer_result) if explainer_understood else {}explainer_summary = getattr(explainer_result, "summary", None) if explainer_understood else Noneexplainer_teaching_points = _safe_meta_list(getattr(explainer_result, "teaching_points", [])) if explainer_understood else []# 1a. Explicit explainer request returns scaffold-rich explainer responseif is_explainer_request(user_text or solver_input) and explainer_understood:reply = format_explainer_response(result=explainer_result,tone=tone,verbosity=verbosity,transparency=transparency,)result.domain = "quant" if is_quant else "general"result.solved = Falseresult.help_mode = "explain"result.topic = getattr(explainer_result, "topic", None) or question_topicresult.answer_letter = Noneresult.answer_value = Noneresult.internal_answer = Noneresult.used_retrieval = Falseresult.used_generator = Falseresult.reply = replyresult.meta = {"intent": "explain_question","question_text": question_text or "","options_count": len(options_text or []),"category": inferred_category,"question_type": question_type,"classified_topic": question_topic,"explainer_used": True,"bridge_ready": bool(getattr(explainer_result, "meta", {}).get("bridge_ready", False)),"hint_style": getattr(explainer_result, "meta", {}).get("hint_style"),"explainer_summary": explainer_summary,"explainer_teaching_points": explainer_teaching_points,"scaffold": explainer_scaffold,}return result# 2. normal solver pathif is_quant:5 unmodified linesresult.help_mode = resolved_help_modeif not result.topic or result.topic in {"general_quant", "general", "unknown"}:result.topic = getattr(explainer_result, "topic", None) if explainer_understood else question_topicresult.domain = "quant"# 2a. Attach explainer scaffold into result meta so generic paths can use itif result.meta is None:result.meta = {}if explainer_understood:result.meta["explainer_used"] = Trueresult.meta["bridge_ready"] = bool(getattr(explainer_result, "meta", {}).get("bridge_ready", False))result.meta["hint_style"] = getattr(explainer_result, "meta", {}).get("hint_style")result.meta["explainer_summary"] = explainer_summaryresult.meta["explainer_teaching_points"] = explainer_teaching_pointsresult.meta["scaffold"] = explainer_scaffold# 3. compose base replyreply = _compose_reply(result=result,123 unmodified linesresult.internal_answer = Noneresult.reply = replyresult.help_mode = resolved_help_modefinal_meta = dict(result.meta or {})final_meta.update({"intent": resolved_intent,"question_text": question_text or "","options_count": len(options_text or []),"category": inferred_category,"question_type": question_type,"classified_topic": question_topic,})result.meta = final_metareturn result
conversation_logic.py+281-100