Skip to content

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

fix(mastery): validate guarded finishes before streaming

Bingxi Zhao (Frank)ce3532b7f8f0
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index 34766b6e9..e1689120a 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -163,6 +163,8 @@ class LLMCallResult:
visible_text: str = ""
tool_calls: list[dict[str, Any]] = field(default_factory=list)
finish_reason: str = ""
+ deferred_chunk_metadata: dict[str, Any] | None = None
+ deferred_completion_metadata: dict[str, Any] | None = None
@dataclass(slots=True)
@@ -311,6 +313,7 @@ class AgentLoop:
trace_role="response" if settling else "explore",
max_tokens=self.pipeline.loop_max_tokens,
tool_schemas=self.tool_schemas,
+ defer_visible_output=self.pipeline._has_capability_finish_guard(self.context),
)
except Exception as exc:
# A mid-loop LLM failure (timeout / transient network) must not
@@ -347,6 +350,7 @@ class AgentLoop:
# and ask for a continuation. The ordinary exploration /
# settlement counters still apply, so repeated truncation
# has the same hard upper bound as repeated tool calls.
+ await self._release_deferred_output(result)
await self.stream.progress(
self.pipeline._t(
"notices.output_truncated",
@@ -412,12 +416,28 @@ class AgentLoop:
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
+ if finish_redirect:
+ await self._discard_deferred_output(result)
+ if 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
+ 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="chat",
+ stage=LOOP_STAGE,
+ metadata={"trace_kind": "warning"},
+ )
+ return LoopOutcome(final_text="", completed=False)
+ await self._release_deferred_output(result)
# Finish: the text streamed live this round IS the answer.
return await self._finalize_finish(
final_text,
@@ -425,6 +445,7 @@ class AgentLoop:
continued_answer_parts=continued_answer_parts,
)
+ await self._release_deferred_output(result)
messages.append(assistant_message_with_tool_calls(result.text, result.tool_calls))
dispatch = await self.pipeline._dispatch_tool_calls(
tool_calls=result.tool_calls,
@@ -597,6 +618,42 @@ class AgentLoop:
await self.pipeline._emit_protocol_fallback_final_response(self.stream, final_text)
return LoopOutcome(final_text=final_text, completed=True)
+ async def _release_deferred_output(self, result: LLMCallResult) -> None:
+ """Publish a buffered capability round only after its protocol accepts it."""
+ if result.deferred_chunk_metadata is not None and result.visible_text:
+ await self.stream.content(
+ result.visible_text,
+ source="chat",
+ stage=LOOP_STAGE,
+ metadata=result.deferred_chunk_metadata,
+ )
+ if result.deferred_completion_metadata is not None:
+ await self.stream.progress(
+ "",
+ source="chat",
+ stage=LOOP_STAGE,
+ metadata=result.deferred_completion_metadata,
+ )
+ result.deferred_chunk_metadata = None
+ result.deferred_completion_metadata = None
+
+ async def _discard_deferred_output(self, result: LLMCallResult) -> None:
+ """Close a rejected round's trace without publishing its buffered prose."""
+ metadata = result.deferred_completion_metadata
+ if metadata is not None:
+ metadata = dict(metadata)
+ metadata["call_role"] = "narration"
+ metadata.pop("answer_visible", None)
+ metadata["finish_rejected"] = True
+ await self.stream.progress(
+ "",
+ source="chat",
+ stage=LOOP_STAGE,
+ metadata=metadata,
+ )
+ result.deferred_chunk_metadata = None
+ result.deferred_completion_metadata = None
+
# ---- LLM call ----------------------------------------------------------
async def _call_llm(
@@ -608,6 +665,7 @@ class AgentLoop:
trace_role: str,
max_tokens: int,
tool_schemas: list[dict[str, Any]] | None = None,
+ defer_visible_output: bool = False,
) -> LLMCallResult:
await self.pipeline._guard_context_window(messages, self.stream)
stage = LOOP_STAGE
@@ -686,9 +744,10 @@ class AgentLoop:
visible_text_parts.append(segment)
if segment.strip():
answer_content_emitted = True
- await self.stream.content(
- segment, source="chat", stage=stage, metadata=chunk_meta
- )
+ if not defer_visible_output:
+ await self.stream.content(
+ segment, source="chat", stage=stage, metadata=chunk_meta
+ )
else:
await self.stream.thinking(
segment, source="chat", stage=stage, metadata=chunk_meta
@@ -850,20 +909,23 @@ class AgentLoop:
# answer content, not an internal tool preamble.
completion_metadata["answer_visible"] = True
- await self.stream.progress(
- "",
- source="chat",
- stage=stage,
- metadata=merge_trace_metadata(
- trace_meta,
- completion_metadata,
- ),
- )
+ completion_event_metadata = merge_trace_metadata(trace_meta, completion_metadata)
+ if not defer_visible_output:
+ await self.stream.progress(
+ "",
+ source="chat",
+ stage=stage,
+ metadata=completion_event_metadata,
+ )
return LLMCallResult(
text=text,
visible_text="".join(visible_text_parts),
tool_calls=tool_calls,
finish_reason=finish_reason,
+ deferred_chunk_metadata=chunk_meta if defer_visible_output else None,
+ deferred_completion_metadata=(
+ completion_event_metadata if defer_visible_output else None
+ ),
)
async def _create_response_stream(
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index d296b2b83..0c8e045b3 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -727,6 +727,13 @@ class AgenticChatPipeline:
return content
return ""
+ def _has_capability_finish_guard(self, context: UnifiedContext) -> bool:
+ """Whether a capability may need to inspect a tool-less finish first."""
+ return any(
+ callable(getattr(cap, "finish_instruction", None))
+ for cap in self._active_loop_capabilities(context)
+ )
+
async def _capability_pre_loop_briefings(
self,
context: UnifiedContext,
diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.py
index 07215fda2..8cea87ea0 100644
--- a/deeptutor/capabilities/mastery/loop.py
+++ b/deeptutor/capabilities/mastery/loop.py
@@ -206,14 +206,10 @@ class MasteryLoopCapability:
"""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 "
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index 4b4b2c414..86896ec01 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -606,7 +606,8 @@ async def test_mastery_tool_round_keeps_teaching_markdown_visible(
assert markers[0]["call_role"] == "narration"
assert markers[0]["answer_visible"] is True
joined_content = "".join(_contents(events))
- assert joined_content.startswith(explanation + "Choose the answer when you are ready.")
+ assert joined_content.startswith(explanation)
+ assert "Choose the answer when you are ready." not in joined_content
assert "Which sum?" in joined_content
assert client.call_count == 3
assert [row["name"] for row in registry.executed] == ["mastery_quiz", "ask_user"]
@@ -697,6 +698,46 @@ async def test_mastery_plain_choice_finish_gets_one_protocol_redirect(
assert "mastery_quiz" in redirect["content"]
assert "ask_user" in redirect["content"]
assert _result(events).metadata["completed"] is False
+ assert plain_quiz not in "".join(_contents(events))
+
+
+async def test_repeated_plain_choice_failure_is_never_published_as_a_finish(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """One retry is bounded, but its second invalid quiz still cannot finish."""
+ plain_quiz = "Which value is correct?\n\nA. one\nB. two\nC. three\nD. four"
+ client = _ScriptedChatClient(
+ [[_llm_chunk(content=plain_quiz)], [_llm_chunk(content=plain_quiz)]]
+ )
+ 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 plain_quiz not in "".join(_contents(events))
+ rejected_calls = [
+ event.metadata
+ for event in events
+ if event.type == StreamEventType.PROGRESS and event.metadata.get("finish_rejected") is True
+ ]
+ assert len(rejected_calls) == 2
+ assert all(metadata["call_state"] == "complete" for metadata in rejected_calls)
+ assert all(metadata["call_role"] == "narration" for metadata in rejected_calls)
+ result = _result(events)
+ assert result.metadata["completed"] is False
+ assert result.metadata["response"] == ""
@pytest.mark.asyncio