"""Human-to-Agent peer instruction — Mazur's Peer Instruction with the agent as the peer. Classic PI (Mazur 1997; Crouch & Mazur 2001): a concept question → students answer individually → they try to convince a neighbor → re-vote → instructor explains. Normalized gains roughly doubled (0.25 → 0.49 FCI) in Mazur's courses, and peer discussion followed by instructor explanation helps all ability levels most (Smith et al. 2011). Here the learner's "neighbor" is the agent: 1. **Commit**: the agent poses a problem; the learner solves it (paper photo or typed), explains their reasoning, and rates confidence 1-5 (committing before discussion is what makes PI work). 2. **Peer response**: correct → marked correct with *why* it's right (which concepts justify each step). Wrong → the agent points to the gaps and the exact faulty inference, like a peer arguing back — without handing over the answer. 3. **Revise** (the re-vote): the learner can fix their reasoning and resubmit once. 4. **Explanation**: after the revision (or on request) the answer key and reference solution are shown — the "instructor explains" phase. Confidence vs. correctness is logged: confident-and-wrong is flagged as a possible illusion of fluency, and the topic gets more review priority via the learner model. """ from __future__ import annotations import random from datetime import datetime, timezone 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.quiz import load_bank MAX_REVISIONS = 1 def pick_topic(learner_id: str) -> str: """Prefer covered topics (peer discussion works best on material already met), weakest first.""" state = LearnerState.load(learner_id) pool = state.covered or [s["topic"] for s in (state.learning_plan or {}).get("steps", [])] pool = [t for t in pool if load_bank().get(t)] or [t for t in TOPIC_BY_ID if load_bank().get(t)] return max(pool, key=lambda t: state.topics[t].error_rate if t in state.topics else 0.5) class PeerInstructionSession: def __init__(self, learner_id: str, topic: str | None = None, seed: int | None = None): self.learner_id = learner_id self.topic = topic or pick_topic(learner_id) rng = random.Random(seed) state = LearnerState.load(learner_id) pool = [p for p in load_bank().get(self.topic, []) if p["answer_format"] != "multiple_choice" and len(p["statement"]) < 900] unseen = [p for p in pool if p["id"] not in state.seen_problems] or pool if not unseen: raise ValueError(f"no problems for topic {self.topic!r}") self.problem = rng.choice(unseen) self.round = 0 self.history: list[dict] = [] self.finished = False def prompt(self) -> dict: return {"topic": self.topic, "topic_title": TOPIC_BY_ID[self.topic].title, "problem": self.problem["statement"], "image_paths": self.problem["image_paths"], "instructions": ("Solve it on paper (or type), explain your reasoning for each step — what concept " "you used and why — and rate how confident you are (1-5). I'll respond like a peer: " "if you're right I'll tell you why; if not, I'll show you where your reasoning breaks.")} def submit(self, work: str, confidence: int) -> dict: if self.finished: raise ValueError("session finished — start a new problem") p = self.problem final_round = self.round >= MAX_REVISIONS ev = evaluate_work(p["statement"], p["answer"], work, mode="explain", reference_solution=p["solution"], answer_format=p["answer_format"], reveal_answer=final_round) ev["confidence"] = confidence ev["calibration"] = ( "⚠️ You were confident but this isn't right yet — a classic illusion of fluency. Worth a closer look." if (confidence >= 4 and not ev["correct"]) else "You were unsure, but your reasoning holds up — trust that process." if (confidence <= 2 and ev["correct"]) else "") self.history.append({"round": self.round, "verdict": ev["verdict"], "confidence": confidence}) if ev["correct"] or final_round: self.finished = True ev["reveal"] = {"answer_key": p["answer"], "solution": p["solution"]} self._record(ev) else: ev["next"] = "Revise your reasoning where I flagged it and resubmit (this is your re-vote)." self.round += 1 return ev def _record(self, ev: dict) -> None: state = LearnerState.load(self.learner_id) first = self.history[0] state.peer_log.append({"t": datetime.now(timezone.utc).isoformat(timespec="seconds"), "topic": self.topic, "problem_id": self.problem["id"], "rounds": self.history, "initial_correct": first["verdict"] == "correct", "final_correct": ev["correct"], "initial_confidence": first["confidence"]}) # Initial (pre-discussion) answer is the honest retrieval signal for the spacing schedule. state.apply_quiz_results([{"problem_id": self.problem["id"], "topic": self.topic, "correct": first["verdict"] == "correct"}]) state.save()