DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: require selected mastery quizzes to complete delivery
Wubian111ead57a7b2e7e
diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex d7f72c052..6c9656a01 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -614,19 +614,7 @@ class AgentLoop:messages.append(_assistant_round_message(result))self._append_loop_instruction(messages, finish_redirect)continue- await self.stream.progress(- self.pipeline._t(- "notices.capability_finish_rejected",- default=(- "The model did not complete the required interactive step. "- "Please retry the turn."- ),- ),- source=self.source,- stage=self.stage,- metadata={"trace_kind": "warning"},- )- return LoopOutcome(final_text="", completed=False)+ return await self._reject_capability_finish()final_override = self.pipeline._capability_final_text_override(self.context, final_text)@@ -785,6 +773,22 @@ class AgentLoop:messages[:] = prefixreturn len(messages)+ async def _reject_capability_finish(self) -> LoopOutcome:+ """Fail a turn whose required interaction could not be completed."""+ await self.stream.progress(+ self.pipeline._t(+ "notices.capability_finish_rejected",+ default=(+ "The model did not complete the required interactive step. "+ "Please retry the turn."+ ),+ ),+ source=self.source,+ stage=self.stage,+ metadata={"trace_kind": "warning"},+ )+ return LoopOutcome(final_text="", completed=False)+async def _forced_finish(self,messages: list[dict[str, Any]],@@ -794,6 +798,11 @@ class AgentLoop:error: str = "",continued_answer_parts: list[str] | None = None,) -> LoopOutcome:+ # A tool-free salvage reply cannot satisfy an outstanding interaction.+ # Empty text asks capabilities about state, without inventing prose to+ # validate or giving the model another chance to claim completion.+ if self.pipeline._capability_finish_instruction(self.context, ""):+ return await self._reject_capability_finish()if reason == "error":# The caller has the exception and logs it; without it here the# reader is told a step failed and never which one or why — thediff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex 4fbd54281..b57df2586 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -249,6 +249,7 @@ class MasteryLoopCapability:if tool_name in MASTERY_TOOL_NAMES:updated = dict(kwargs)if tool_name == "mastery_quiz":+ state["quiz_requested"] = Truestate["quiz_awaiting_grade"] = Trueupdated["_end_turn_on_card"] = _card_end_marker(context)elif tool_name == "mastery_grade":@@ -289,11 +290,13 @@ class MasteryLoopCapability:def finish_instruction(self, context: UnifiedContext, final_text: str) -> str | None:"""Catch a finish that leaves the learner with nothing to answer.- Only the *shape of the reply* can trigger this. Two states that read- like unfinished protocol are not:+ A quiz selected in this turn must reach its success callback before+ the turn can finish, regardless of reply wording or later grading.+ Text heuristics are only a fallback for replies that never selected+ the tool. Two other states are not an outstanding delivery:- ``mastery_quiz`` called without a grade no longer means the question- went unasked — that call now poses it on its own card — so a learner+ A pending question from an earlier turn does not mean it went+ unasked — it was already posed on its own card — so a learnerwho types a question instead of answering leaves the interaction openon purpose, and the tutor answering them is the right reply, not askipped step.@@ -314,6 +317,14 @@ class MasteryLoopCapability:if not self.is_active(context):return Nonestate = context.extension("mastery")+ if state.get("quiz_requested") and not state.get("card_posted"):+ return (+ "This turn selected mastery_quiz, but no question card was successfully "+ "posted. Inspect the tool error and retry mastery_quiz with corrected "+ "arguments. A prose reply or a grading call cannot complete the selected "+ "question delivery. If delivery remains unsuccessful, this turn must "+ "fail rather than report successful completion."+ )if not state.get("card_posted") and (_announces_an_unposed_question(final_text) or _claims_card_delivery(final_text)):diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex 2662c81e2..dda3903c5 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -1324,7 +1324,18 @@ async def test_repeated_plain_choice_failure_is_never_published_as_a_finish(@pytest.mark.asyncio[email protected]("repair", ["new", "existing", "tool_failure", "repeat"])+ "repair",+ [+ "new",+ "existing",+ "tool_failure",+ "repeat",+ "selected_retry",+ "selected_failure",+ "selected_budget",+ ],+)async def test_mastery_card_promise_repair_uses_real_question_tool(repair: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -1398,9 +1409,49 @@ async def test_mastery_card_promise_repair_uses_real_question_tool()if repair == "tool_failure":script.append([_llm_chunk(content=promise, finish_reason="stop")])+ selected_quiz = repair.startswith("selected_")+ if selected_quiz:+ # No delivery keywords: a failed native tool call alone establishes+ # the obligation, and unrelated final prose must not erase it.+ promise = "Done."+ script = [+ [+ _llm_chunk(+ tool_calls=[{"id": "bad-quiz", "name": "mastery_quiz", "arguments": "{}"}],+ finish_reason="tool_calls",+ )+ ],+ [_llm_chunk(content=promise, finish_reason="stop")],+ [+ _llm_chunk(+ tool_calls=[+ {+ "id": "retry-quiz",+ "name": "mastery_quiz",+ "arguments": json.dumps(quiz_args),+ }+ ],+ finish_reason="tool_calls",+ )+ ]+ if repair == "selected_retry"+ else [_llm_chunk(content=promise, finish_reason="stop")],+ ]+ if repair == "selected_budget":+ script = [+ [+ _llm_chunk(+ tool_calls=[{"id": f"bad-{index}", "name": "mastery_quiz", "arguments": "{}"}],+ finish_reason="tool_calls",+ )+ ]+ for index in range(4)+ ] + [[_llm_chunk(content="Done.", finish_reason="stop")]]client = _ScriptedChatClient(script)registry = RealQuizRegistry()pipeline = MasteryLoopPipeline(language="zh")+ if repair == "selected_budget":+ pipeline._max_rounds = 1pipeline.registry = registrymonkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["mastery_quiz"])monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)@@ -1423,10 +1474,17 @@ async def test_mastery_card_promise_repair_uses_real_question_tool(and "mastery_question" in e.metadata.get("tool_metadata", {})]assert promise not in _answer_text(events)- assert "mastery_quiz" in client.calls[1]["messages"][-1]["content"]- assert any(s["function"]["name"] == "mastery_quiz" for s in client.calls[1]["tools"])- assert client.call_count == (3 if repair == "tool_failure" else 2)- succeeded = repair in {"new", "existing"}+ if repair == "selected_budget":+ # One exploration round plus three settlement rounds; no tool-less+ # salvage call can discharge an unfulfilled quiz obligation.+ assert client.call_count == 4+ assert all("tools" in call for call in client.calls)+ else:+ correction = client.calls[2 if selected_quiz else 1]+ assert "mastery_quiz" in correction["messages"][-1]["content"]+ assert any(s["function"]["name"] == "mastery_quiz" for s in correction["tools"])+ assert client.call_count == (3 if repair == "tool_failure" or selected_quiz else 2)+ succeeded = repair in {"new", "existing", "selected_retry"}assert _result(events).metadata["completed"] is succeededif succeeded:assert len(cards) == 1diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.pyindex c666d31ad..819811352 100644--- a/tests/capabilities/test_mastery_capability.py+++ b/tests/capabilities/test_mastery_capability.py@@ -82,7 +82,7 @@ def test_graded_review_may_finish_in_prose():capability = MasteryLoopCapability()context = _context()- capability.augment_kwargs("mastery_quiz", {}, context)+ context.extension("mastery")["quiz_awaiting_grade"] = Truecapability.augment_kwargs("mastery_grade", {}, context)assert capability.finish_instruction(context, _GRADED_REVIEW) is None@@ -98,7 +98,7 @@ def test_open_question_still_allows_answering_the_learner():capability = MasteryLoopCapability()context = _context()- capability.augment_kwargs("mastery_quiz", {}, context)+ context.extension("mastery")["quiz_awaiting_grade"] = Trueassert capability.finish_instruction(context, "会的,路由失败时它会重写查询再试。") is None@@ -108,7 +108,7 @@ def test_open_question_may_not_be_restated_in_prose():capability = MasteryLoopCapability()context = _context()- capability.augment_kwargs("mastery_quiz", {}, context)+ context.extension("mastery")["quiz_awaiting_grade"] = Trueinstruction = capability.finish_instruction(context, _GRADED_REVIEW)assert instruction is not None@@ -208,6 +208,35 @@ def test_card_delivery_claim_does_not_guard_plain_chat() -> None:assert MasteryLoopCapability().finish_instruction(UnifiedContext(), "卡片就在下面。") is None+ "reply", ["Done.", "请继续。", "", "出题失败,请稍后重试。", _GRADED_REVIEW]+)[email protected]("graded", [False, True])+def test_selected_quiz_requires_success_regardless_of_final_text(reply: str, graded: bool) -> None:+ """A selected quiz is an obligation even if a later grade clears awaiting state."""+ context = _context()+ capability = MasteryLoopCapability()+ kwargs = capability.augment_kwargs("mastery_quiz", {}, context)+ if graded:+ capability.augment_kwargs("mastery_grade", {}, context)+ context.metadata["mastery_card_grade"] = {"is_correct": True}+ instruction = capability.finish_instruction(context, reply)+ assert instruction is not None+ assert "no question card was successfully posted" in instruction+ kwargs["_end_turn_on_card"]()+ assert capability.finish_instruction(context, "Done.") is None+++def test_quiz_obligation_does_not_leak_into_another_turn() -> None:+ """A failed quiz in one context does not require a quiz in another."""+ capability = MasteryLoopCapability()+ capability.augment_kwargs("mastery_quiz", {}, _context())+ other_turn = _context()+ other_turn.metadata["turn_id"] = "turn-3"+ capability.augment_kwargs("mastery_status", {}, other_turn)+ assert capability.finish_instruction(other_turn, "先解释一下冒泡排序。") is None++def test_runtime_grading_also_frees_the_review_to_finish():"""A ruling the runtime made counts as this turn having graded.@@ -227,7 +256,7 @@ def test_reviewing_a_graded_attempt_is_not_an_announcement():capability = MasteryLoopCapability()context = _context()- capability.augment_kwargs("mastery_quiz", {}, context)+ context.extension("mastery")["quiz_awaiting_grade"] = Truecapability.augment_kwargs("mastery_grade", {}, context)assert capability.finish_instruction(context, "这道题的关键在于闭环反馈,你抓住了。") is None