"""Worked-example tutoring — the Research Agent's teaching role. Flow per topic (see ARCHITECTURE.md §Worked examples for the evidence): explain ──"I understand"──▶ faded ──correct──▶ full ──correct──▶ transfer ──pass──▶ mastered ▲ │ wrong: targeted │ wrong: feedback; │ fail: illusion of │ │ feedback, retry; │ 2nd miss → back to a │ fluency → new └──── new example ◀────────┘ 3 misses → reveal │ new faded example │ worked example rest, new example └───────────────────────────┘ 1. explain — concept explanation grounded in OpenStax passages + a complete worked example (problem + step-by-step solution, each step annotated with the idea it uses). 2. faded — the same example cut in half (backward fading, Renkl et al. 2002): the learner sees the first half and must complete the rest AND explain their reasoning (self-explanation). 3. full — a new problem on the same topic, solved entirely by the learner, explaining the concept behind every step. 4. transfer — when every concept is right, the Research Agent asks the Retrieval Agent for a 2-3 question quiz on the same topic in different contexts/surfaces, so fluency with the example's surface isn't mistaken for understanding (illusion of fluency). Where the session starts comes from the placement assessment (expertise reversal: partial → start at faded; gap → full worked example). Answer keys and worked solutions come from the datasets. If a topic has no dataset solution, the tutor model may write the steps, but they're used only if their final answer matches the dataset key (verified via the judge/oracle), and they're labelled as such. """ from __future__ import annotations import json import math import random import re from datetime import datetime, timezone from src.config import WORKED_EXAMPLE_MAX_FADED_ATTEMPTS from src.edtech_core.curriculum import TOPIC_BY_ID from src.edtech_core.judge import evaluate_work from src.edtech_core.learner_model import LearnerState from src.edtech_core.llm import chat_json from src.edtech_core.quiz import load_bank, record_quiz_results # ------------------------------------------------------------------------ solution steps def split_steps(solution: str) -> list[str]: """Deterministically split a dataset solution into steps without altering any math.""" text = re.sub(r"^\s*\[figure\]\s*$", "", solution or "", flags=re.MULTILINE) lines = [ln.strip(" -•\t") for ln in text.split("\n")] lines = [ln for ln in lines if len(ln) > 2] if len(lines) < 3: # one long paragraph → split on sentence ends outside $...$ parts, buf, in_math = [], "", False for i, ch in enumerate(" ".join(lines)): buf += ch if ch == "$": in_math = not in_math nxt = " ".join(lines)[i + 1: i + 3] if not in_math and ch in ".;" and nxt[:1] == " " and nxt[1:2].isupper(): parts.append(buf.strip()) buf = "" if buf.strip(): parts.append(buf.strip()) lines = parts merged: list[str] = [] for ln in lines: # glue tiny fragments to the previous step if merged and len(ln) < 30: merged[-1] += " " + ln else: merged.append(ln) return merged def _candidate_problems(topic: str, exclude: set[str]) -> list[dict]: return [p for p in load_bank().get(topic, []) if p["id"] not in exclude and p["answer_format"] == "short_answer" and len(p["statement"]) < 900] def _pick_example(topic: str, exclude: set[str], rng: random.Random) -> dict | None: """Problem + verified steps. Prefers dataset solutions; falls back to tutor-written steps whose final answer is verified against the dataset key.""" pool = _candidate_problems(topic, exclude) with_sol = [p for p in pool if p["solution"] and 150 < len(p["solution"]) < 1800] rng.shuffle(with_sol) for p in with_sol[:20]: steps = split_steps(p["solution"]) if 3 <= len(steps) <= 8: return {"problem": p, "steps": steps, "steps_source": "dataset"} rng.shuffle(pool) for p in pool[:3]: # e.g. U-MATH topics: golden answers only out = chat_json("You write clear step-by-step precalculus solutions.", f"Solve step by step (3-6 steps, LaTeX in $...$).\nPROBLEM:\n{p['statement']}\n" 'Return {"steps": [str], "final_answer": str}.') steps = [s for s in out.get("steps", []) if isinstance(s, str)] if len(steps) < 2: continue check = evaluate_work(p["statement"], p["answer"], "\n".join(steps), mode="answer_only") if check.get("answer_correct"): return {"problem": p, "steps": steps, "steps_source": "tutor-written, verified against dataset key"} return None def _textbook_context(topic: str) -> str: try: from src.edtech_core.retrieval import retrieve_textbook_context hits = retrieve_textbook_context(TOPIC_BY_ID[topic].title, topic=topic, k=3) except Exception: # noqa: BLE001 — tutoring still works without RAG context return "" return "\n\n".join(f"[§{h['section']} {h['section_title']}, p.{h['page']}] {h['text'][:700]}" for h in hits) EXPLAIN_SYSTEM = """\ You are a precalculus tutor using worked examples. Given textbook passages (ground truth) and a worked example whose steps are FIXED (do not change, re-solve, or add math to them), write: - "concept_overview": 3-5 sentences explaining the concept in plain language, grounded in the passages; - "key_ideas": 2-4 short bullets (the ideas the example relies on); - "step_notes": one short note PER STEP (same count as steps) saying which concept/idea that step uses and why it's the right move; - "sections": textbook section numbers you drew on (only ones present in the passages). Return JSON with exactly those keys.""" class WorkedExampleTutor: """One tutoring session on one topic; plain attributes so Gradio State can hold it.""" def __init__(self, learner_id: str, topic: str | None = None, seed: int | None = None): self.learner_id = learner_id state = LearnerState.load(learner_id) if not state.assessed: from src.edtech_core.quiz import AssessmentRequired raise AssessmentRequired("complete the placement assessment first — it decides where tutoring starts") plan_steps = (state.learning_plan or {}).get("steps", []) if topic is None: pending = [s for s in plan_steps if state.concept_progress.get(s["topic"], {}).get("status") != "mastered"] if not pending: raise ValueError("learning plan complete — pick a topic explicitly") topic = pending[0]["topic"] self.topic = topic start = next((s["start_stage"] for s in plan_steps if s["topic"] == topic), "worked_example") self.rng = random.Random(seed) self.used: set[str] = set() self.log: list[dict] = [] self.faded_attempts = 0 self.full_attempts = 0 self.example: dict | None = None self.explanation: dict | None = None self.full_problem: dict | None = None self.transfer: dict | None = None self.transfer_idx = 0 self.transfer_results: list[dict] = [] self._new_example() # Expertise reversal: learners who are already partly there skip the full worked example. self.stage = {"faded": "faded", "full_problem": "full"}.get(start, "explain") if self.stage == "full": self._new_full_problem() self._event("start", {"start_stage": self.stage}) # ---------------------------------------------------------------- helpers def _event(self, kind: str, data: dict) -> None: self.log.append({"t": datetime.now(timezone.utc).isoformat(timespec="seconds"), "kind": kind, **data}) def _new_example(self) -> None: ex = _pick_example(self.topic, self.used, self.rng) if ex is None: raise ValueError(f"no worked-example material for topic {self.topic!r} in the problem bank") self.used.add(ex["problem"]["id"]) self.example = ex self.explanation = None self.faded_attempts = 0 def _new_full_problem(self) -> None: pool = _candidate_problems(self.topic, self.used) same_type = [p for p in pool if p["source_label"] == self.example["problem"]["source_label"]] self.full_problem = self.rng.choice(same_type or pool) self.used.add(self.full_problem["id"]) self.full_attempts = 0 @property def half(self) -> int: return max(1, math.floor(len(self.example["steps"]) / 2)) def _save_progress(self, status: str, **extra) -> None: state = LearnerState.load(self.learner_id) state.concept_progress[self.topic] = {"status": status, "stage": self.stage, "updated": datetime.now(timezone.utc).isoformat(timespec="seconds"), **extra} state.save() d = state.quiz_dir().parent / "tutoring" d.mkdir(parents=True, exist_ok=True) (d / f"{self.topic}.jsonl").open("a").write(json.dumps(self.log[-1], ensure_ascii=False) + "\n") # ---------------------------------------------------------------- stage 1: explain def explain(self) -> dict: if self.explanation is None: steps = "\n".join(f"{i}. {s}" for i, s in enumerate(self.example["steps"], 1)) out = chat_json(EXPLAIN_SYSTEM, f"TOPIC: {TOPIC_BY_ID[self.topic].title}\n\nTEXTBOOK PASSAGES:\n" f"{_textbook_context(self.topic) or '(unavailable)'}\n\nPROBLEM:\n" f"{self.example['problem']['statement']}\n\nFIXED STEPS:\n{steps}") notes = out.get("step_notes") or [] out["step_notes"] = (notes + [""] * len(self.example["steps"]))[: len(self.example["steps"])] self.explanation = out return {"stage": "explain", "topic": self.topic, "topic_title": TOPIC_BY_ID[self.topic].title, "problem": self.example["problem"]["statement"], "image_paths": self.example["problem"]["image_paths"], "steps": self.example["steps"], "answer": self.example["problem"]["answer"], "steps_source": self.example["steps_source"], **self.explanation} def understood(self) -> dict: """Learner says they get it → cut the example in half.""" self.stage = "faded" self._event("understood", {}) return self.current() # ---------------------------------------------------------------- views def current(self) -> dict: if self.stage == "explain": return self.explain() if self.stage == "faded": return {"stage": "faded", "topic_title": TOPIC_BY_ID[self.topic].title, "problem": self.example["problem"]["statement"], "image_paths": self.example["problem"]["image_paths"], "shown_steps": self.example["steps"][: self.half], "remaining": len(self.example["steps"]) - self.half, "prompt": ("Here's the first half of the solution. Complete the remaining steps on paper and, " "for each step, explain the concept or idea you're using and why it's the right move.")} if self.stage == "full": return {"stage": "full", "topic_title": TOPIC_BY_ID[self.topic].title, "problem": self.full_problem["statement"], "image_paths": self.full_problem["image_paths"], "prompt": ("Now solve this one entirely on your own. Number your steps and, for each, explain " "the concept/idea behind it.")} if self.stage == "transfer": it = self.transfer["items"][self.transfer_idx] return {"stage": "transfer", "topic_title": TOPIC_BY_ID[self.topic].title, "problem": it["statement"], "image_paths": it["image_paths"], "progress": f"{self.transfer_idx + 1}/{len(self.transfer['items'])}", "prompt": ("Transfer check — same concept, different setting. Solve it and explain your " "reasoning. (Questions requested from the Retrieval Agent.)")} return {"stage": self.stage, "topic_title": TOPIC_BY_ID[self.topic].title} # ---------------------------------------------------------------- stage 2: faded def submit_faded(self, work: str) -> dict: shown = "\n".join(self.example["steps"][: self.half]) remaining = "\n".join(self.example["steps"][self.half:]) ev = evaluate_work(self.example["problem"]["statement"], self.example["problem"]["answer"], work, mode="complete_faded", reference_solution=remaining, shown_steps=shown) self.faded_attempts += 1 self._event("faded_submit", {"verdict": ev["verdict"], "attempt": self.faded_attempts}) if ev["correct"]: self.stage = "full" self._new_full_problem() ev["next"] = "Every step and explanation checks out — now a full problem on your own." elif self.faded_attempts >= WORKED_EXAMPLE_MAX_FADED_ATTEMPTS: ev["reveal_steps"] = self.example["steps"][self.half:] self._new_example() self.stage = "faded" ev["next"] = ("Here's how the example finishes — study it. Then try a fresh example, cut in half the " "same way.") else: ev["next"] = "Fix the step(s) flagged above and submit your continuation again." self._save_progress("in_progress") return ev # ---------------------------------------------------------------- stage 3: full problem def submit_full(self, work: str) -> dict: p = self.full_problem ev = evaluate_work(p["statement"], p["answer"], work, mode="explain", reference_solution=p["solution"], answer_format=p["answer_format"]) self.full_attempts += 1 self._event("full_submit", {"verdict": ev["verdict"], "attempt": self.full_attempts}) if ev["correct"]: self.request_transfer_quiz() self.stage = "transfer" ev["next"] = ("All concepts right. I've asked the Retrieval Agent for a short quiz on the same idea in " "different contexts — that's how we check it's understanding, not familiarity.") elif self.full_attempts >= 2: ev["reveal_answer"] = p["answer"] self._new_example() self.stage = "faded" ev["next"] = "Let's step back to another half-worked example before the next full problem." else: ev["next"] = "Revise the flagged step(s) and resubmit your full solution." self._save_progress("in_progress") return ev # ---------------------------------------------------------------- handoff → Retrieval Agent def request_transfer_quiz(self) -> dict: from src.edtech_core.retrieval import request_transfer_quiz self.transfer = request_transfer_quiz(self.learner_id, self.topic, exclude_ids=sorted(self.used), requested_by="research_agent.worked_examples") self.transfer_idx = 0 self.transfer_results = [] self._event("handoff_transfer_quiz", {"quiz_id": self.transfer["quiz_id"]}) return self.transfer # ---------------------------------------------------------------- stage 4: transfer def submit_transfer(self, work: str) -> dict: it = self.transfer["items"][self.transfer_idx] ev = evaluate_work(it["statement"], it["answer_key"], work, mode="explain", reference_solution=it["solution"], answer_format=it["answer_format"], reveal_answer=True) passed = bool(ev.get("answer_correct")) and ev.get("reasoning_quality") in ("sound", "partial") self.transfer_results.append({"n": it["n"], "correct": passed}) self.transfer_idx += 1 if self.transfer_idx < len(self.transfer["items"]): ev["next"] = "Next transfer question." return ev record_quiz_results(self.learner_id, self.transfer["quiz_id"], self.transfer_results) n_ok = sum(r["correct"] for r in self.transfer_results) if n_ok >= math.ceil(2 * len(self.transfer_results) / 3): self.stage = "mastered" state = LearnerState.load(self.learner_id) state.cover(self.topic) state.save() ev["next"] = (f"🎉 Transfer passed ({n_ok}/{len(self.transfer_results)}). {TOPIC_BY_ID[self.topic].title} is " "now part of your retrieval-practice rotation.") self._event("mastered", {"transfer": f"{n_ok}/{len(self.transfer_results)}"}) self._save_progress("mastered", transfer=f"{n_ok}/{len(self.transfer_results)}") else: self._new_example() self.stage = "explain" ev["next"] = (f"Transfer {n_ok}/{len(self.transfer_results)}: the worked examples felt familiar, but the " "idea didn't carry over to new settings yet (illusion of fluency). Let's do another " "worked example with a different setup.") self._event("transfer_failed", {"transfer": f"{n_ok}/{len(self.transfer_results)}"}) self._save_progress("needs_more", transfer=f"{n_ok}/{len(self.transfer_results)}") return ev def submit(self, work: str) -> dict: handler = {"faded": self.submit_faded, "full": self.submit_full, "transfer": self.submit_transfer}.get(self.stage) if handler is None: raise ValueError(f"nothing to submit in stage {self.stage!r}") return handler(work)