Skip to content

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

fix(mastery): redirect plain-text quizzes to cards

XZHb4bbe20e87c8
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index bda1a3766..34766b6e9 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -286,6 +286,7 @@ class AgentLoop:
exploration_budget = max(1, self.pipeline.effective_max_rounds(self.context))
settlement_started = False
nudged_empty_finish = False
+ finish_redirect_used = False
continued_answer_parts: list[str] = []
while True:
settling = state.exploration_rounds >= exploration_budget
@@ -408,6 +409,15 @@ class AgentLoop:
),
)
continue
+ finish_redirect = self.pipeline._capability_finish_instruction(
+ self.context, final_text
+ )
+ if finish_redirect and not finish_redirect_used:
+ finish_redirect_used = True
+ if result.text:
+ messages.append({"role": "assistant", "content": result.text})
+ self._append_loop_instruction(messages, finish_redirect)
+ continue
# Finish: the text streamed live this round IS the answer.
return await self._finalize_finish(
final_text,
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 3a5763642..d296b2b83 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -702,6 +702,31 @@ class AgenticChatPipeline:
]
return "\n\n".join(seed for seed in seeds if seed)
+ def _capability_finish_instruction(self, context: UnifiedContext, final_text: str) -> str:
+ """Let an active capability reject a narrow tool-less finish once.
+
+ This is a protocol guard, not a content generator: capabilities return
+ a short instruction only when their own state proves that required tool
+ work remains. A guard failure must not sink the learner's answer.
+ """
+ for cap in self._active_loop_capabilities(context):
+ hook = getattr(cap, "finish_instruction", None)
+ if not callable(hook):
+ continue
+ try:
+ instruction = hook(context, final_text)
+ except Exception:
+ logger.warning(
+ "finish guard failed for capability %s",
+ getattr(cap, "name", "?"),
+ exc_info=True,
+ )
+ continue
+ content = str(instruction or "").strip()
+ if content:
+ return content
+ return ""
+
async def _capability_pre_loop_briefings(
self,
context: UnifiedContext,
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py
index 41c243e48..07215fda2 100644
--- a/deeptutor/capabilities/mastery/loop.py
+++ b/deeptutor/capabilities/mastery/loop.py
@@ -40,6 +40,14 @@ _RECOMMENDATION_SUFFIX = re.compile(
r"[\s ]*[((]\s*(?:推荐|建议|recommended|recommend)\s*[))][\s ]*$",
re.IGNORECASE,
)
+_PLAIN_CHOICE_OPTION_RE = re.compile(
+ r"^(?:[-*+]\s*)?(?:\*\*)?([A-D])(?:\*\*)?\s*[.、)::-]\s*(\S.*)$",
+ re.IGNORECASE,
+)
+_PLAIN_QUIZ_PROMPT_RE = re.compile(
+ r"\b(?:which|choose|select|answer)\b|选择|选哪个|请选择|请回答|答案",
+ re.IGNORECASE,
+)
def _without_recommendation(text: Any) -> Any:
@@ -80,6 +88,26 @@ def _strip_answer_hints(kwargs: dict[str, Any]) -> dict[str, Any]:
return {**kwargs, "questions": cleaned_questions}
+def _looks_like_plain_choice_quiz(text: str) -> bool:
+ """Recognise a rendered A-D option list with high precision.
+
+ The model may discuss labelled options while teaching. Requiring both an
+ assessment prompt and at least three distinct labelled answer bodies keeps
+ ordinary prose, headings, and option-like vocabulary examples out of this
+ protocol guard.
+ """
+ labels: set[str] = set()
+ prompt_lines: list[str] = []
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ match = _PLAIN_CHOICE_OPTION_RE.match(line)
+ if match:
+ labels.add(match.group(1).upper())
+ else:
+ prompt_lines.append(line)
+ return len(labels) >= 3 and any(_PLAIN_QUIZ_PROMPT_RE.search(line) for line in prompt_lines)
+
+
def _bind_pending_ask_user_args(kwargs: dict[str, Any], path_id: str) -> dict[str, Any]:
"""Replace model-authored quiz display data with persisted public state.
@@ -152,11 +180,16 @@ class MasteryLoopCapability:
return kwargs
path_id = str(context.metadata.get("mastery_path_id") or "").strip()
if tool_name == "ask_user":
+ context.metadata["_mastery_quiz_needs_card"] = False
# Strip hints last, so a card rebound from persisted state is
# cleaned too — the persisted options were model-authored as well.
return _strip_answer_hints(_bind_pending_ask_user_args(kwargs, path_id))
if tool_name in MASTERY_TOOL_NAMES:
updated = dict(kwargs)
+ if tool_name == "mastery_quiz":
+ context.metadata["_mastery_quiz_needs_card"] = True
+ elif tool_name == "mastery_grade":
+ context.metadata["_mastery_quiz_needs_card"] = False
updated["_mastery_path_id"] = path_id
updated["_session_id"] = str(context.session_id or "").strip()
updated["_turn_id"] = str(context.metadata.get("turn_id") or "").strip()
@@ -169,6 +202,26 @@ class MasteryLoopCapability:
return updated
return kwargs
+ def finish_instruction(self, context: UnifiedContext, final_text: str) -> str | None:
+ """Redirect a quantitative assessment away from a plain-text finish."""
+ if not self.is_active(context):
+ return None
+ if context.metadata.get("_mastery_plain_quiz_guard_used"):
+ return None
+
+ needs_card = bool(context.metadata.get("_mastery_quiz_needs_card"))
+ if not needs_card and not _looks_like_plain_choice_quiz(final_text):
+ return None
+
+ context.metadata["_mastery_plain_quiz_guard_used"] = True
+ return (
+ "The previous reply tried to finish a mastery assessment as plain text. "
+ "Do not repeat the question in prose. First ensure the question and its "
+ "answer are registered with mastery_quiz (retry it if the previous call "
+ "failed), then present the persisted question with ask_user and stop for "
+ "the learner's answer."
+ )
+
def pre_loop_seed(self, context: UnifiedContext) -> str:
_ = context
return ""
diff --git a/deeptutor/capabilities/protocol.py b/deeptutor/capabilities/protocol.py
index 02944537b..d10cf0c53 100644
--- a/deeptutor/capabilities/protocol.py
+++ b/deeptutor/capabilities/protocol.py
@@ -84,6 +84,12 @@ class LoopCapability(Protocol):
a ``getattr`` default, like ``pre_loop``). The dispatcher runs them before
the round's other calls and re-binds those calls afterwards, so a switch
and a write issued in the same round cannot land on different targets.
+
+ A capability MAY also define ``finish_instruction(context, final_text)``.
+ It is called after a tool-less LLM round and may return a short protocol
+ instruction when that round must not finalize the turn. The answer loop
+ gives the model one additional round with tools still mounted; capability
+ implementations are responsible for keeping the check narrow and bounded.
"""
name: str
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index ec4b460d3..4b4b2c414 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -529,6 +529,16 @@ async def test_mastery_tool_round_keeps_teaching_markdown_visible(
)
return schemas
+ async def execute(self, name: str, **kwargs):
+ if name == "ask_user":
+ self.executed.append({"name": name, "kwargs": kwargs})
+ return ToolResult(
+ content="Asked the learner.",
+ success=True,
+ pause_for_user={"questions": kwargs["questions"]},
+ )
+ return await super().execute(name, **kwargs)
+
explanation = (
"### Binary addition\n\n"
"| Carry | Sum |\n"
@@ -552,6 +562,19 @@ async def test_mastery_tool_round_keeps_teaching_markdown_visible(
),
],
[_llm_chunk(content="Choose the answer when you are ready.")],
+ [
+ _llm_chunk(
+ tool_calls=[
+ {
+ "id": "ask-1",
+ "name": "ask_user",
+ "arguments": json.dumps(
+ {"questions": [{"id": "q1", "prompt": "Which sum?"}]}
+ ),
+ }
+ ]
+ )
+ ],
]
)
pipeline = AgenticChatPipeline(language="en")
@@ -559,7 +582,7 @@ async def test_mastery_tool_round_keeps_teaching_markdown_visible(
monkeypatch.setattr(
pipeline,
"_compose_enabled_tools",
- lambda _context: ["mastery_quiz"],
+ lambda _context: ["mastery_quiz", "ask_user"],
)
monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
@@ -569,7 +592,7 @@ async def test_mastery_tool_round_keeps_teaching_markdown_visible(
session_id="s1",
user_message="Teach me binary addition",
enabled_tools=["mastery_quiz"],
- metadata={"mastery_mode": True, "mastery_path_id": "path-1"},
+ metadata={"mastery_mode": True, "mastery_path_id": ""},
),
)
@@ -582,7 +605,130 @@ async def test_mastery_tool_round_keeps_teaching_markdown_visible(
]
assert markers[0]["call_role"] == "narration"
assert markers[0]["answer_visible"] is True
- assert "".join(_contents(events)) == explanation + "Choose the answer when you are ready."
+ joined_content = "".join(_contents(events))
+ assert joined_content.startswith(explanation + "Choose the answer when you are ready.")
+ assert "Which sum?" in joined_content
+ assert client.call_count == 3
+ assert [row["name"] for row in registry.executed] == ["mastery_quiz", "ask_user"]
+ redirect = client.calls[2]["messages"][-1]
+ assert redirect["role"] == "user"
+ assert "mastery_quiz" in redirect["content"]
+ assert "ask_user" in redirect["content"]
+ result = _result(events)
+ assert result.metadata["completed"] is False
+
+
+ "plain_quiz",
+ [
+ (
+ "Which expression builds a dictionary?\n\n"
+ "- A. `{w: words.count(w) for w in words}`\n"
+ "- B. `[w: words.count(w) for w in words]`\n"
+ "- C. `{w for w in words}`\n"
+ "- D. `(w: words.count(w) for w in words)`"
+ ),
+ (
+ "请选择正确的字典推导式:\n\n"
+ "- A. `{w: words.count(w) for w in words}`\n"
+ "- B. `[w: words.count(w) for w in words]`\n"
+ "- C. `{w for w in words}`\n"
+ "- D. `(w: words.count(w) for w in words)`"
+ ),
+ ],
+)
+async def test_mastery_plain_choice_finish_gets_one_protocol_redirect(
+ plain_quiz: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A prose A-D quiz cannot bypass the registered-card assessment flow."""
+
+ class _MasteryCardRegistry(_Registry):
+ async def execute(self, name: str, **kwargs):
+ if name == "ask_user":
+ self.executed.append({"name": name, "kwargs": kwargs})
+ return ToolResult(
+ content="Asked the learner.",
+ success=True,
+ pause_for_user={"questions": kwargs["questions"]},
+ )
+ return await super().execute(name, **kwargs)
+
+ registry = _MasteryCardRegistry()
+ client = _ScriptedChatClient(
+ [
+ [_llm_chunk(content=plain_quiz)],
+ [
+ _llm_chunk(
+ tool_calls=[
+ {
+ "id": "ask-1",
+ "name": "ask_user",
+ "arguments": json.dumps(
+ {"questions": [{"id": "q1", "prompt": "Which expression?"}]}
+ ),
+ }
+ ]
+ )
+ ],
+ ]
+ )
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = registry
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["ask_user"])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ events = await _run(
+ pipeline,
+ UnifiedContext(
+ session_id="s1",
+ user_message="Continue",
+ enabled_tools=["ask_user"],
+ metadata={"mastery_mode": True, "mastery_path_id": ""},
+ ),
+ )
+
+ assert client.call_count == 2
+ assert [row["name"] for row in registry.executed] == ["ask_user"]
+ redirect = client.calls[1]["messages"][-1]
+ assert redirect["role"] == "user"
+ assert "plain text" in redirect["content"]
+ assert "mastery_quiz" in redirect["content"]
+ assert "ask_user" in redirect["content"]
+ assert _result(events).metadata["completed"] is False
+
+
+async def test_mastery_labelled_teaching_examples_stay_direct(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A labelled teaching list is not itself an assessment prompt."""
+ registry = _Registry()
+ teaching = (
+ "Here are container spellings to remember:\n\n"
+ "- A. lists use brackets.\n"
+ "- B. dictionaries answer key lookups with braces and a colon.\n"
+ "- C. sets use braces without a colon."
+ )
+ client = _ScriptedChatClient([[_llm_chunk(content=teaching)]])
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = registry
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ events = await _run(
+ pipeline,
+ UnifiedContext(
+ session_id="s1",
+ user_message="Teach me Python containers",
+ metadata={"mastery_mode": True, "mastery_path_id": ""},
+ ),
+ )
+
+ assert client.call_count == 1
+ assert "".join(_contents(events)) == teaching
+ assert _result(events).metadata["completed"] is True
@pytest.mark.asyncio