DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: keep mastery teaching content visible (#855)
Bingxi Zhao4d5effeaa458
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.pyindex 7809fc50d..cd83bfba5 100644--- a/deeptutor/agents/chat/agent_loop.py+++ b/deeptutor/agents/chat/agent_loop.py@@ -5,8 +5,9 @@ One chat turn = ONE agent loop over a single growing conversation:* each round is one LLM call; its text streams to the user as a ``content``block, and its tool calls are dispatched with their ``role=tool`` resultsappended back into the conversation;-* a round that DOES call tools is "narration" — its text is a preamble to- the tool work — and the loop continues;+* a round that DOES call tools is "narration" by default — its text is a+ preamble to the tool work — and the loop continues; modes that intentionally+ combine learner-facing prose with a tool call mark that prose answer-visible;* a round that calls NO tools is the ``finish``: its text IS the finaluser-facing answer and the loop ends (the model deciding it is done; afirst round without tool calls is the "no exploration needed" fast path);@@ -766,12 +767,15 @@ class AgentLoop:# output remains visible but is not terminal: the loop continues."call_role": "narration" if tool_calls or truncated_round else "finish",}- if (dsml_calls or truncated_round) and answer_content_emitted:+ mastery_tool_round = bool(tool_calls) and bool(self.context.metadata.get("mastery_mode"))+ if (dsml_calls or truncated_round or mastery_tool_round) and answer_content_emitted:# DSML providers may intentionally combine tutor feedback and an# ask_user/tool call in the same round. Preserve only that cleaned# surrounding prose in the answer surfaces. Truncated rounds also# keep their partial answer visible while retaining a truthful- # non-terminal ``narration`` role.+ # non-terminal ``narration`` role. Mastery rounds likewise combine+ # learner-facing teaching with state/quiz tools; that teaching is+ # answer content, not an internal tool preamble.completion_metadata["answer_visible"] = Trueawait self.stream.progress(diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex 9474b37e4..494b4e616 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -79,8 +79,9 @@ def _narration_marker_call_id(event: StreamEvent) -> str | None:preamble streamed alongside a tool call). Its text belongs to the trace,not the persisted answer, so it is excluded when assembling content.- DSML rounds may explicitly keep the cleaned prose surrounding a call; that- narrow exception remains part of the persisted answer.+ A round may explicitly keep learner-facing prose surrounding a call via+ ``answer_visible`` (for example DSML or mastery tutoring); that narrow+ exception remains part of the persisted answer."""metadata = event.metadata or {}if (diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex b1f008960..dced255af 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -501,6 +501,87 @@ async def test_tool_round_then_finish(monkeypatch: pytest.MonkeyPatch) -> None:assert result.metadata["response"] == "Found what was needed."+async def test_mastery_tool_round_keeps_teaching_markdown_visible(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Mastery teaching may share a native tool round with quiz setup.++ The prose must stay in the answer surface after the round resolves instead+ of being demoted into the compact reasoning trace (issue #855).+ """++ class _MasteryRegistry(_Registry):+ def build_openai_schemas(self, enabled):+ schemas = super().build_openai_schemas(enabled)+ schemas.append(+ {+ "type": "function",+ "function": {+ "name": "mastery_quiz",+ "description": "Register a mastery quiz",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ )+ return schemas++ explanation = (+ "### Binary addition\n\n"+ "| Carry | Sum |\n"+ "| --- | --- |\n"+ "| 1 | 0 |\n\n"+ "Use the carry column to work through the next question."+ )+ registry = _MasteryRegistry()+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(content=explanation),+ _llm_chunk(+ tool_calls=[+ {+ "id": "quiz-1",+ "name": "mastery_quiz",+ "arguments": "{}",+ }+ ]+ ),+ ],+ [_llm_chunk(content="Choose the answer when you are ready.")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ monkeypatch.setattr(+ pipeline,+ "_compose_enabled_tools",+ lambda _context: ["mastery_quiz"],+ )+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(+ pipeline,+ UnifiedContext(+ session_id="s1",+ user_message="Teach me binary addition",+ enabled_tools=["mastery_quiz"],+ metadata={"mastery_mode": True, "mastery_path_id": "path-1"},+ ),+ )++ markers = [+ event.metadata+ for event in events+ if event.type == StreamEventType.PROGRESS+ and event.metadata.get("call_state") == "complete"+ and "call_role" in event.metadata+ ]+ 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."++@pytest.mark.asyncioasync def test_dsml_round_keeps_clean_prose_visible_and_decodes_container_args(monkeypatch: pytest.MonkeyPatch,diff --git a/web/lib/stream.ts b/web/lib/stream.tsindex 47283dc9d..50545949e 100644--- a/web/lib/stream.ts+++ b/web/lib/stream.ts@@ -19,8 +19,8 @@ export function shouldAppendEventContent(event: StreamEvent): boolean {if (!meta.call_id) return true;// The chat agent loop streams every round's text as `content`. The// tool-less finish round (and the forced-finish round) are the- // user-facing answer; narration rounds are filtered back out via their- // call_role marker (see collectNarrationCallIds).+ // user-facing answer; trace-only narration rounds are filtered back out via+ // their call_role marker (see collectNarrationCallIds).return (meta.call_kind === "llm_final_response" ||meta.call_kind === "agent_loop_round"@@ -31,7 +31,8 @@ export function shouldAppendEventContent(event: StreamEvent): boolean {* call_ids whose round resolved as "narration" — a short preamble the chat* loop streamed alongside a tool call. That text belongs to the trace, not* the answer, so it is excluded once the round's call_status marker arrives.- * DSML rounds can explicitly preserve cleaned prose that surrounded a call.+ * Interactive rounds can explicitly preserve learner-facing prose that+ * surrounded a call with `answer_visible`.*/export function collectNarrationCallIds(events: StreamEvent[]): Set<string> {const ids = new Set<string>();