Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix mastery choice persistence and grading

R-Turing943e9fb7e811
diff --git a/deeptutor/capabilities/mastery/prompts/en/system.md b/deeptutor/capabilities/mastery/prompts/en/system.md
index bfa42d5bb..73a25b898 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 wor
Then 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, give each `ask_user` option a short label (A / B / C …) and set the matching label as `mastery_quiz`'s `expected_answer`; for open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`. 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`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`. Keep working the same objective until `mastery_grade` reports `mastered: true`.
- 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.md
index cdba3f145..32423e051 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.。选择题给每个 `ask_user` 选项一个短标签(A / B / C …),并把正确标签设为 `mastery_quiz` 的 `expected_answer`;简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改。在 `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`。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。
- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。
- `review`:有到期的间隔复习项——再考一次以巩固。
- `complete`:祝贺学习者并总结其已掌握的内容。
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 2e55795e7..846597d60 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import json
import logging
+import re
from typing import TYPE_CHECKING, Any
import uuid
@@ -61,6 +62,8 @@ _QUESTION_TYPES = ("choice", "short", "open")
_ALLOWED_KP_TYPES = {t.value for t in KnowledgeType}
logger = logging.getLogger(__name__)
+_OPTION_PREFIX_RE = re.compile(r"^\s*([A-Z])\s*[.::、))-]\s*(.+)$", re.IGNORECASE)
+
def _new_service() -> LearningService:
from deeptutor.learning.service import LearningService
@@ -96,15 +99,104 @@ def _question_bank_options(options: list[str]) -> dict[str, str]:
text = str(raw or "").strip()
if not text:
continue
- if len(text) <= 3 and text.isalnum():
+ match = _OPTION_PREFIX_RE.match(text)
+ if match:
+ key = match.group(1).upper()
+ result[key] = match.group(2).strip()
+ elif len(text) == 1 and text.isalnum():
key = text.upper()
result[key] = text
- continue
- key = chr(ord("A") + idx) if idx < 26 else str(idx + 1)
- result[key] = text
+ else:
+ key = chr(ord("A") + idx) if idx < 26 else str(idx + 1)
+ result[key] = text
return result
+def _has_choice_option_bodies(options: dict[str, str]) -> bool:
+ """Whether a choice map contains real answer text, not only A/B/C labels."""
+ return len(options) >= 2 and all(
+ value.strip() and value.strip().upper() != key.upper() for key, value in options.items()
+ )
+
+
+def _normalized_choice_prompt(value: str) -> str:
+ return "".join(char.casefold() for char in str(value or "") if char.isalnum())
+
+
+def _resolve_choice_answer(expected_answer: str, options: dict[str, str]) -> str:
+ """Resolve a model-supplied choice answer to its stable option label.
+
+ Models occasionally send ``"Step 6"`` or the full option text even though
+ the interactive card returns ``"C"``. Resolve a unique textual match at
+ registration time so deterministic grading compares like with like.
+ """
+ expected = str(expected_answer or "").strip()
+ key = expected.upper()
+ if key in options:
+ return key
+ if not expected:
+ return ""
+
+ prefix_match = _OPTION_PREFIX_RE.match(expected)
+ if prefix_match and prefix_match.group(1).upper() in options:
+ return prefix_match.group(1).upper()
+
+ needle = expected.casefold()
+ exact = [label for label, text in options.items() if text.casefold() == needle]
+ if len(exact) == 1:
+ return exact[0]
+ contained = [label for label, text in options.items() if needle in text.casefold()]
+ return contained[0] if len(contained) == 1 else ""
+
+
+async def _recover_choice_options_from_turn(
+ store: Any,
+ turn_id: str,
+ question: str,
+) -> dict[str, str]:
+ """Recover choice descriptions from the most recent matching ask_user card.
+
+ This is a compatibility fallback for questions registered by older
+ versions, where ``mastery_quiz`` persisted only ``["A", "B", ...]`` even
+ though the full descriptions were present in the turn's ``ask_user``
+ event.
+ """
+ if not turn_id or not hasattr(store, "get_turn_events"):
+ return {}
+ try:
+ events = await store.get_turn_events(turn_id)
+ except Exception:
+ logger.warning("Failed to load turn events for mastery option recovery", exc_info=True)
+ return {}
+
+ target = _normalized_choice_prompt(question)
+ for event in reversed(events):
+ if event.get("type") != "tool_call":
+ continue
+ metadata = event.get("metadata") or {}
+ if metadata.get("tool_name") != "ask_user":
+ continue
+ questions = (metadata.get("args") or {}).get("questions") or []
+ for item in reversed(questions):
+ if not isinstance(item, dict):
+ continue
+ recovered = {
+ str(option.get("label") or "").strip().upper(): str(
+ option.get("description") or ""
+ ).strip()
+ for option in (item.get("options") or [])
+ if isinstance(option, dict)
+ and str(option.get("label") or "").strip()
+ and str(option.get("description") or "").strip()
+ }
+ if not _has_choice_option_bodies(recovered):
+ continue
+ prompt = _normalized_choice_prompt(str(item.get("prompt") or ""))
+ if prompt == target or prompt.startswith(target) or target.startswith(prompt):
+ return recovered
+ return {}
+
+
async def _sync_mastery_attempt_to_question_bank(
*,
session_id: str,
@@ -112,6 +204,8 @@ async def _sync_mastery_attempt_to_question_bank(
pending: PendingQuestion,
user_answer: str,
is_correct: bool,
+ choice_options: dict[str, str] | None = None,
+ correct_answer: str | None = None,
) -> None:
if not session_id:
return
@@ -120,8 +214,8 @@ async def _sync_mastery_attempt_to_question_bank(
"question_id": pending.question_id,
"question": pending.prompt,
"question_type": _question_bank_type(pending.question_type),
- "options": _question_bank_options(list(pending.options or [])),
- "correct_answer": pending.expected_answer,
+ "options": choice_options or _question_bank_options(list(pending.options or [])),
+ "correct_answer": correct_answer or pending.expected_answer,
"explanation": "",
"difficulty": "",
"user_answer": user_answer,
@@ -208,7 +302,8 @@ class MasteryQuizTool(BaseTool):
"and you never re-state the answer later). After calling this, "
"present the question with the ask_user tool so the learner answers "
"on an interactive card (for choices, give ask_user options short "
- "labels like A/B/C and set the correct label as expected_answer); "
+ "labels like A/B/C, pass every full option body here, and set the "
+ "correct label as expected_answer); "
"then call mastery_grade with their answer. For CONCEPT / DESIGN "
"objectives use mastery_assess instead."
),
@@ -242,7 +337,12 @@ class MasteryQuizTool(BaseTool):
ToolParameter(
name="options",
type="array",
- description="Choice labels, when question_type='choice'.",
+ description=(
+ "For question_type='choice', every full option in label order, "
+ "for example ['A: first answer', 'B: second answer']. Never "
+ "pass bare labels such as ['A', 'B', 'C', 'D']. Use the same "
+ "bodies as the ask_user option descriptions."
+ ),
required=False,
items={"type": "string"},
),
@@ -265,6 +365,30 @@ class MasteryQuizTool(BaseTool):
if q_type not in _QUESTION_TYPES:
q_type = "short"
options = [str(o) for o in (kwargs.get("options") or []) if str(o).strip()]
+ if q_type == "choice":
+ choice_options = _question_bank_options(options)
+ if not _has_choice_option_bodies(choice_options):
+ return ToolResult(
+ content=(
+ "Choice questions need full option bodies in mastery_quiz.options "
+ "(for example ['A: first answer', 'B: second answer']), not only "
+ "the labels A/B/C/D. Retry mastery_quiz with the exact option "
+ "descriptions you will show through ask_user."
+ ),
+ success=False,
+ )
+ resolved_expected = _resolve_choice_answer(expected, choice_options)
+ if not resolved_expected:
+ return ToolResult(
+ content=(
+ "Choice expected_answer must be an option label such as A/B/C/D, "
+ "or uniquely match one full option body. Retry mastery_quiz with "
+ "the correct label."
+ ),
+ success=False,
+ )
+ expected = resolved_expected
+ options = [f"{key}: {text}" for key, text in choice_options.items()]
service = _new_service()
progress = service.get_or_create(path_id)
@@ -339,13 +463,32 @@ class MasteryGradeTool(BaseTool):
content="No question is awaiting an answer. Pose one with mastery_quiz first.",
success=False,
)
+ choice_options: dict[str, str] = {}
+ expected_answer = pending.expected_answer
+ if pending.question_type == "choice":
+ choice_options = _question_bank_options(list(pending.options or []))
+ if not _has_choice_option_bodies(choice_options):
+ try:
+ from deeptutor.services.session import get_sqlite_session_store
+
+ choice_options = await _recover_choice_options_from_turn(
+ get_sqlite_session_store(),
+ _resolve_turn_id(kwargs),
+ pending.prompt,
+ )
+ except Exception:
+ logger.warning("Failed to recover legacy mastery choice options", exc_info=True)
+ resolved_expected = _resolve_choice_answer(expected_answer, choice_options)
+ if resolved_expected:
+ expected_answer = resolved_expected
+
is_correct = service.grade_and_record(
progress,
question_id=pending.question_id,
knowledge_point_id=pending.knowledge_point_id,
module_id=pending.module_id,
user_answer=answer,
- expected_answer=pending.expected_answer,
+ expected_answer=expected_answer,
question_type=pending.question_type,
scheduler=scheduler,
)
@@ -355,6 +498,8 @@ class MasteryGradeTool(BaseTool):
pending=pending,
user_answer=answer,
is_correct=is_correct,
+ choice_options=choice_options,
+ correct_answer=expected_answer,
)
service.clear_pending_question(progress)
kp, _, _ = find_knowledge_point(progress, pending.knowledge_point_id)
diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.py
index ca921762f..ec3aea75e 100644
--- a/deeptutor/learning/tests/test_mastery_tools.py
+++ b/deeptutor/learning/tests/test_mastery_tools.py
@@ -225,6 +225,72 @@ async def test_grade_syncs_mastery_attempt_to_question_bank(path_id, session_sto
assert entry["is_correct"] is False
+async def test_choice_quiz_rejects_bare_option_labels(path_id):
+ await _build_basic(path_id)
+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = status["next"]["knowledge_point_id"]
+
+ result = await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="Which order is correct?",
+ expected_answer="A",
+ question_type="choice",
+ options=["A", "B", "C", "D"],
+ )
+
+ assert result.success is False
+ assert "full option bodies" in result.content
+
+
+async def test_choice_quiz_preserves_bodies_and_normalizes_answer(path_id, session_store):
+ session = await session_store.create_session(title="Choice Mastery")
+ await _build_basic(path_id)
+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
+ kp_id = status["next"]["knowledge_point_id"]
+
+ quiz = await MasteryQuizTool().execute(
+ _mastery_path_id=path_id,
+ knowledge_point_id=kp_id,
+ question="Where is the stop condition added?",
+ expected_answer="Step 6",
+ question_type="choice",
+ options=[
+ "A: Step 2 — write the first tool",
+ "B: Step 4 — test one call",
+ "C: Step 6 — add the stop condition",
+ "D: Step 7 — add another tool",
+ ],
+ )
+ assert quiz.success is True
+
+ grade = json.loads(
+ (
+ await MasteryGradeTool().execute(
+ _mastery_path_id=path_id,
+ _session_id=session["id"],
+ _turn_id="turn_choice_1",
+ answer="C",
+ )
+ ).content
+ )
+ assert grade["is_correct"] is True
+
+ entries = await session_store.list_notebook_entries()
+ entry = entries["items"][0]
+ assert entry["options"] == {
+ "A": "Step 2 — write the first tool",
+ "B": "Step 4 — test one call",
+ "C": "Step 6 — add the stop condition",
+ "D": "Step 7 — add another tool",
+ }
+ assert entry["correct_answer"] == "C"
+ assert entry["user_answer"] == "C"
+ assert entry["is_correct"] is True
+
+
# ── assess: the qualitative gate ─────────────────────────────────────────────