DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(mastery): carry explanation and difficulty into the question bank
Bingxi Zhao (Frank)b71aef2b5b48
diff --git a/deeptutor/capabilities/mastery/prompts/en/system.md b/deeptutor/capabilities/mastery/prompts/en/system.mdindex b3ec15c20..6b706cdbc 100644--- a/deeptutor/capabilities/mastery/prompts/en/system.md+++ b/deeptutor/capabilities/mastery/prompts/en/system.md@@ -6,7 +6,7 @@ FIRST on every turn, call `mastery_status`. It returns the next objective to worThen act on the objective:- No objectives yet? Design a path from the learner's materials (use `rag` / `read_source` when materials are attached) and call `mastery_build`. Tag each knowledge point: memory (facts), procedure (step-by-step skills), concept (ideas to understand), design (open-ended judgement).- `probe` (untouched): briefly check whether the learner already knows it before teaching. A test-out is not a silent skip — record its result through the gate (`mastery_assess` for concept / design, `mastery_quiz` + `mastery_grade` for memory / procedure) before advancing. Never move past an objective the engine hasn't marked mastered.-- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. If `pending_interaction.status` is `answered`, immediately call `mastery_grade` with its persisted `learner_answer` and `question_id` instead of asking the learner twice. Otherwise present the pending question with `ask_user`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`.+- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. If `pending_interaction.status` is `answered`, immediately call `mastery_grade` with its persisted `learner_answer` and `question_id` instead of asking the learner twice. Otherwise present the pending question with `ask_user`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`. Always pass `explanation` to `mastery_quiz` (why the expected answer is right): it never appears on the card the learner is answering, but it travels with the attempt into their question bank, where it is the only explanation they will have when reviewing the mistake.- concept / design objectives: ask the learner to explain the idea in their own words, judge it, and record the result with `mastery_assess` (`passed: true` only when the explanation truly shows understanding).- `review`: a spaced-repetition item is due — quiz it again to refresh it.- `complete`: congratulate the learner and summarise what they have mastered.diff --git a/deeptutor/capabilities/mastery/prompts/zh/system.md b/deeptutor/capabilities/mastery/prompts/zh/system.mdindex 452e5146b..801c9fcdf 100644--- a/deeptutor/capabilities/mastery/prompts/zh/system.md+++ b/deeptutor/capabilities/mastery/prompts/zh/system.md@@ -6,7 +6,7 @@然后针对该知识点行动:- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。- `probe`(未触碰):先简短探查学习者是否已经会了再教。"测试通过"不等于直接跳过——仍要用门工具记录结果(concept / design 用 `mastery_assess`,memory / procedure 用 `mastery_quiz` + `mastery_grade`)再推进;绝不要越过引擎尚未标记为"已掌握"的知识点。-- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。如果 `pending_interaction.status` 是 `answered`,应立即用其中持久化的 `learner_answer` 和 `question_id` 调用 `mastery_grade`,不要让学习者重复作答;否则再用 `ask_user` 展示待答题目。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。+- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。如果 `pending_interaction.status` 是 `answered`,应立即用其中持久化的 `learner_answer` 和 `question_id` 调用 `mastery_grade`,不要让学习者重复作答;否则再用 `ask_user` 展示待答题目。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。每次调用 `mastery_quiz` 都要带上 `explanation`(这个答案为什么对):它不会出现在作答卡片上,但会随作答记录进入学习者的题库,是他们日后复习错题时唯一能看到的解析。- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。- `review`:有到期的间隔复习项——再考一次以巩固。- `complete`:祝贺学习者并总结其已掌握的内容。diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex a95f77bb9..94344ece8 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -96,6 +96,19 @@ def _resolve_turn_id(kwargs: dict[str, Any]) -> str:return str(kwargs.get("_turn_id") or "").strip()+_DIFFICULTIES = ("easy", "medium", "hard")+++def _normalize_difficulty(raw: Any) -> str:+ """Map the model's difficulty onto the bank's badge values, or drop it.++ An unrecognised value is discarded rather than rejected: a mislabelled+ difficulty must never cost the learner a question.+ """+ value = str(raw or "").strip().lower()+ return value if value in _DIFFICULTIES else ""++def _question_bank_type(question_type: str) -> str:qtype = str(question_type or "").strip().lower()if qtype == "choice":@@ -208,8 +221,10 @@ async def _sync_mastery_attempt_to_question_bank("question_type": _question_bank_type(pending.question_type),"options": choice_options or parse_options(list(pending.options or [])),"correct_answer": correct_answer or pending.expected_answer,- "explanation": "",- "difficulty": "",+ # Carried from mastery_quiz. Without these the bank held a bare+ # right/wrong for every mastery attempt — reviewable only as a score.+ "explanation": pending.explanation,+ "difficulty": pending.difficulty,"user_answer": user_answer,"is_correct": is_correct,}@@ -406,6 +421,28 @@ class MasteryQuizTool(BaseTool):required=False,items={"type": "string"},),+ ToolParameter(+ name="explanation",+ type="string",+ description=(+ "Why the expected answer is right, in one or two sentences. "+ "Held server-side like expected_answer — never shown on the "+ "card the learner is answering — and saved with the attempt "+ "so a wrong answer is reviewable later in their question "+ "bank instead of being just a score."+ ),+ required=False,+ ),+ ToolParameter(+ name="difficulty",+ type="string",+ description=(+ "How hard this question is for this learner right now. "+ "Shown as a badge when they review the attempt later."+ ),+ required=False,+ enum=list(_DIFFICULTIES),+ ),],)@@ -446,6 +483,8 @@ class MasteryQuizTool(BaseTool):question_type=q_type,expected_answer=expected,options=options,+ explanation=str(kwargs.get("explanation") or "").strip()[:2000],+ difficulty=_normalize_difficulty(kwargs.get("difficulty")),)from deeptutor.learning.service import MasteryInteractionErrordiff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.pyindex d7bc60417..ee839a911 100644--- a/deeptutor/learning/models.py+++ b/deeptutor/learning/models.py@@ -179,6 +179,14 @@ class PendingQuestion(BaseModel):question_type: str = "short"expected_answer: str = ""options: list[str] = Field(default_factory=list)+ # Reference explanation and difficulty, captured when the question is+ # posed. Server-side like ``expected_answer`` — ``public_pending_question``+ # never projects them, so an explanation cannot leak the answer into the+ # card the learner is about to answer. They travel with the attempt into+ # the question bank, which is what makes a mastery mistake reviewable+ # later instead of a bare right/wrong.+ explanation: str = ""+ difficulty: str = ""created_at: float = Field(default_factory=time.time)diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.pyindex addbe78e9..8d024a9ee 100644--- a/deeptutor/learning/tests/test_mastery_tools.py+++ b/deeptutor/learning/tests/test_mastery_tools.py@@ -922,3 +922,98 @@ async def test_leave_makes_the_conversation_own_its_scratch_path(path_id, sessioassert removed == ["session-1"]assert store.exists("session-1") is Falseassert store.exists("calculus") is True+++async def test_quiz_explanation_reaches_the_question_bank(path_id, session_store):+ """A mastery mistake must be reviewable, not just scored.++ The sync used to hard-code ``explanation`` and ``difficulty`` to empty, so+ every question the mastery path contributed to the bank showed a bare+ right/wrong with nothing saying why.+ """+ await _build_basic(path_id)+ session = await session_store.create_session(title="Mastery Session")+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ quiz = json.loads(+ (+ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="What does NAND return for (1, 1)?",+ expected_answer="0",+ question_type="short",+ explanation="NAND is NOT AND, so two true inputs give false.",+ difficulty="medium",+ )+ ).content+ )++ # The reference explanation is answer-adjacent: it must never ride along+ # on the card the learner is about to answer.+ rendered = json.dumps(quiz["ask_user"], ensure_ascii=False)+ assert "NOT AND" not in rendered+ assert "NOT AND" not in json.dumps(quiz["pending_question"], ensure_ascii=False)++ await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ _session_id=session["id"],+ _turn_id="turn_mastery_1",+ question_id=quiz["question_id"],+ answer="1",+ )++ entry = (await session_store.list_notebook_entries())["items"][0]+ assert entry["is_correct"] is False+ assert entry["explanation"] == "NAND is NOT AND, so two true inputs give false."+ assert entry["difficulty"] == "medium"+++async def test_unusable_difficulty_is_dropped_not_rejected(path_id, session_store):+ """A mislabelled difficulty must never cost the learner the question."""+ await _build_basic(path_id)+ session = await session_store.create_session(title="Mastery Session")+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ quiz = json.loads(+ (+ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="2+2?",+ expected_answer="4",+ question_type="short",+ difficulty="extremely tricky",+ )+ ).content+ )+ assert quiz["status"] == "registered"++ await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ _session_id=session["id"],+ _turn_id="turn_mastery_1",+ question_id=quiz["question_id"],+ answer="5",+ )+ entry = (await session_store.list_notebook_entries())["items"][0]+ assert entry["difficulty"] == ""+++async def test_pending_question_without_explanation_still_deserializes(path_id):+ """Paths persisted before the field existed must load unchanged."""+ legacy = PendingQuestion.model_validate(+ {+ "question_id": "q1",+ "knowledge_point_id": "kp1",+ "prompt": "old question",+ "expected_answer": "yes",+ }+ )+ assert legacy.explanation == ""+ assert legacy.difficulty == ""