Skip to content

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

fix(llm): carry a round's reasoning through the shared agentic loop

Bingxi Zhao (Frank)5f7e165161e0
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index becf44a78..61719c2ef 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -69,6 +69,7 @@ from deeptutor.runtime.agentic import (
run_labeled_step,
)
from deeptutor.runtime.agentic.labels import find_inline_labels
+from deeptutor.runtime.agentic.messages import assistant_message
from deeptutor.runtime.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
from deeptutor.runtime.agentic.usage import record_streamed_usage
from deeptutor.runtime.registry.tool_registry import get_tool_registry
@@ -1484,7 +1485,13 @@ class QuestionPipeline:
step.text, allowed_labels=_PROTOCOL_EXPLORE.allowed
):
return step.text, True, calls
- messages.append({"role": "assistant", "content": step.text[:500]})
+ messages.append(
+ assistant_message(
+ step.text[:500],
+ reasoning_content=step.reasoning_content or None,
+ thinking_blocks=list(step.thinking_blocks) or None,
+ )
+ )
messages.append({"role": "user", "content": self._t("protocol.force_finish_repair")})
return self._t("protocol.fallback_final"), False, calls
diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.py
index 833884352..91acc30a3 100644
--- a/deeptutor/agents/research/pipeline.py
+++ b/deeptutor/agents/research/pipeline.py
@@ -80,6 +80,7 @@ from deeptutor.runtime.agentic import (
run_agentic_loop,
run_labeled_step,
)
+from deeptutor.runtime.agentic.messages import assistant_message
from deeptutor.runtime.agentic.tool_dispatch import (
MAX_PARALLEL_TOOL_CALLS,
)
@@ -1004,7 +1005,13 @@ class ResearchPipeline:
calls += 1
if result.label == LABEL_FINISH and result.text.strip():
return result.text, True, calls
- messages.append({"role": "assistant", "content": result.text[:500]})
+ messages.append(
+ assistant_message(
+ result.text[:500],
+ reasoning_content=result.reasoning_content or None,
+ thinking_blocks=list(result.thinking_blocks) or None,
+ )
+ )
messages.append({"role": "user", "content": self._t("protocol.force_finish_repair")})
return self._t("protocol.fallback_final"), False, calls
diff --git a/deeptutor/book/blocks/base.py b/deeptutor/book/blocks/base.py
index 2dee46db3..9f66d9863 100644
--- a/deeptutor/book/blocks/base.py
+++ b/deeptutor/book/blocks/base.py
@@ -36,7 +36,19 @@ class GenerationFailure(Exception):
def _classify_failure(message: str) -> str:
+ """Bucket a generator failure so the UI can say whether a retry is worth it.
+
+ Substring matching on an error string is crude, and the ordering is what
+ keeps it honest: a provider's own rejection must be recognised as one
+ before the heuristics that look for the *model's* misbehaviour get a turn.
+ """
lower = (message or "").lower()
+ # First, because a provider's rejection quotes the field it objected to.
+ # DeepSeek's "the reasoning_content in the thinking mode must be passed
+ # back to the API" was landing in `prompt_leak` — permanently un-retryable,
+ # and blaming the model for what was a bug in how we replayed its history.
+ if "invalid_request_error" in lower or "must be passed back" in lower:
+ return "provider_error"
if "json" in lower or "object found" in lower or "parse" in lower:
return "json_parse"
if "empty" in lower or "did not return" in lower or "returned no" in lower:
@@ -45,7 +57,9 @@ def _classify_failure(message: str) -> str:
return "timeout"
if "rate limit" in lower or "429" in lower:
return "rate_limit"
- if "<think" in lower or "reasoning_content" in lower or "prompt" in lower:
+ # `"prompt" in lower` deliberately dropped: it also matches "prompt_tokens",
+ # which appears in ordinary usage payloads.
+ if "<think" in lower or "reasoning_content" in lower or "system prompt" in lower:
return "prompt_leak"
if "api" in lower or "llm" in lower or "provider" in lower:
return "provider_error"
diff --git a/deeptutor/capabilities/explore_context/explorer.py b/deeptutor/capabilities/explore_context/explorer.py
index 375d61811..036766a57 100644
--- a/deeptutor/capabilities/explore_context/explorer.py
+++ b/deeptutor/capabilities/explore_context/explorer.py
@@ -85,6 +85,9 @@ class _CallResult:
text: str = ""
tool_calls: list[dict[str, Any]] = field(default_factory=list)
output_chars: int = 0
+ # Streamed to the trace and also kept: a thinking model's provider needs
+ # it echoed on the assistant turn that issued the tool calls.
+ reasoning_content: str = ""
class ContextExplorer:
@@ -224,7 +227,13 @@ class ContextExplorer:
if not result.tool_calls:
investigation = result.text
break
- messages.append(assistant_message_with_tool_calls(result.text, result.tool_calls))
+ messages.append(
+ assistant_message_with_tool_calls(
+ result.text,
+ result.tool_calls,
+ reasoning_content=result.reasoning_content or None,
+ )
+ )
dispatch = await dispatch_tool_calls(
tool_calls=result.tool_calls,
context=context,
@@ -281,6 +290,7 @@ class ContextExplorer:
kwargs["tool_choice"] = "auto"
text_parts: list[str] = []
+ reasoning_parts: list[str] = []
tool_acc = ToolCallAccumulator()
output_chars = 0
response_stream = await client.chat.completions.create(**kwargs)
@@ -296,6 +306,7 @@ class ContextExplorer:
delta, "reasoning", None
)
if reasoning:
+ reasoning_parts.append(str(reasoning))
output_chars += len(reasoning)
await stream.thinking(
reasoning, source=EXPLORE_SOURCE, stage=EXPLORE_STAGE, metadata=chunk_meta
@@ -317,7 +328,10 @@ class ContextExplorer:
tool_calls = tool_acc.collected()
return _CallResult(
- text="".join(text_parts), tool_calls=tool_calls, output_chars=output_chars
+ text="".join(text_parts),
+ tool_calls=tool_calls,
+ output_chars=output_chars,
+ reasoning_content="".join(reasoning_parts),
)
def _read_source_schemas(self, source_index: dict[str, str]) -> list[dict[str, Any]]:
diff --git a/deeptutor/runtime/agentic/labeled_step.py b/deeptutor/runtime/agentic/labeled_step.py
index 6f55cc03e..af83c9c45 100644
--- a/deeptutor/runtime/agentic/labeled_step.py
+++ b/deeptutor/runtime/agentic/labeled_step.py
@@ -110,6 +110,17 @@ class LabeledStepResult:
# escape hatch, but exposes that fact so strict callers can retry rather
# than treating the partial text as complete.
stream_idle_timeout: bool = False
+ # The round's own reasoning, kept so the caller can echo it back on the
+ # assistant turn it rebuilds. It used to be streamed to the trace UI and
+ # then dropped, which is fine for a single call and fatal for a loop:
+ # DeepSeek's thinking models reject a continuation whose history is missing
+ # the previous assistant turn's reasoning ("the reasoning_content in the
+ # thinking mode must be passed back to the API"), and quiz, research and
+ # explore_context are all multi-round.
+ reasoning_content: str = ""
+ # Anthropic's signed thinking blocks, which must be replayed verbatim and
+ # cannot be reconstructed from text.
+ thinking_blocks: tuple[dict[str, Any], ...] = ()
async def run_labeled_step(
@@ -187,6 +198,9 @@ async def run_labeled_step(
# prelude state machine below; this splitter covers the post-label body.
post_label_think = InlineThinkFilter()
tc_acc = ToolCallAccumulator()
+ # Kept for replay on the next round's assistant message, not for display.
+ reasoning_acc: list[str] = []
+ thinking_blocks: list[dict[str, Any]] = []
usage_seen: Any = None
output_chars_seen = 0
finish_reason_seen: str | None = None
@@ -498,6 +512,16 @@ async def run_labeled_step(
choice = choices[0]
if getattr(choice, "finish_reason", None):
finish_reason_seen = str(choice.finish_reason)
+ # Anthropic's signed thinking blocks arrive here rather than on the
+ # delta, and they cannot be rebuilt from text — the signature is
+ # what makes them replayable.
+ provider_fields = getattr(choice, "provider_specific_fields", None)
+ if isinstance(provider_fields, dict):
+ signed_blocks = provider_fields.get("thinking_blocks")
+ if isinstance(signed_blocks, list) and signed_blocks:
+ thinking_blocks = [
+ dict(block) for block in signed_blocks if isinstance(block, dict)
+ ]
delta = choice.delta
if delta is None:
continue
@@ -516,6 +540,11 @@ async def run_labeled_step(
reasoning_text = getattr(delta, "reasoning_content", None) or getattr(
delta, "reasoning", None
)
+ # Accumulated for every label, not only the pre-label prelude: the
+ # provider wants the whole round's reasoning back, and whether the
+ # trace UI showed it is a display question.
+ if reasoning_text:
+ reasoning_acc.append(str(reasoning_text))
if reasoning_text and label is None:
output_chars_seen += len(reasoning_text)
saw_pre_label_think = True
@@ -604,4 +633,6 @@ async def run_labeled_step(
tool_calls=ordered_tool_calls,
finish_reason=finish_reason_seen,
stream_idle_timeout=stream_idle_timeout,
+ reasoning_content="".join(reasoning_acc),
+ thinking_blocks=tuple(thinking_blocks),
)
diff --git a/deeptutor/runtime/agentic/loop.py b/deeptutor/runtime/agentic/loop.py
index 5a996b2b0..b3337bfc1 100644
--- a/deeptutor/runtime/agentic/loop.py
+++ b/deeptutor/runtime/agentic/loop.py
@@ -30,7 +30,10 @@ from typing import Any, Protocol
from deeptutor.runtime.agentic.labeled_step import LabeledStepResult, run_labeled_step
from deeptutor.runtime.agentic.labels import LABEL_UNKNOWN, find_inline_labels
-from deeptutor.runtime.agentic.messages import assistant_message_with_tool_calls
+from deeptutor.runtime.agentic.messages import (
+ assistant_message,
+ assistant_message_with_tool_calls,
+)
from deeptutor.runtime.agentic.tool_dispatch import DispatchOutcome
from deeptutor.runtime.agentic.usage import UsageTracker
from deeptutor.runtime.stream_bus import StreamBus
@@ -259,7 +262,7 @@ async def run_agentic_loop(
)
_append_repair_messages(
messages=messages,
- iteration_text=step.text,
+ step=step,
violation=violation,
host=host,
)
@@ -279,7 +282,7 @@ async def run_agentic_loop(
)
_append_repair_messages(
messages=messages,
- iteration_text=step.text,
+ step=step,
violation=violation,
host=host,
)
@@ -295,7 +298,18 @@ async def run_agentic_loop(
break
if protocol.tool_label is not None and step.label == protocol.tool_label:
- messages.append(assistant_message_with_tool_calls(step.text, step.tool_calls))
+ # The reasoning rides along. A thinking model's provider requires
+ # the round's own reasoning on the assistant turn that issued the
+ # tool calls, and this loop used to drop it — so the second round
+ # of any DeepSeek thinking turn was rejected outright.
+ messages.append(
+ assistant_message_with_tool_calls(
+ step.text,
+ step.tool_calls,
+ reasoning_content=step.reasoning_content or None,
+ thinking_blocks=list(step.thinking_blocks) or None,
+ )
+ )
outcome = await host.dispatch_tools(
iteration=iteration,
tool_calls=step.tool_calls,
@@ -324,7 +338,13 @@ async def run_agentic_loop(
if step.label in protocol.final and step.text and not stream_body_live:
await host.emit_final(step.text, final_meta)
if step.text:
- messages.append({"role": "assistant", "content": step.text})
+ messages.append(
+ assistant_message(
+ step.text,
+ reasoning_content=step.reasoning_content or None,
+ thinking_blocks=list(step.thinking_blocks) or None,
+ )
+ )
# Optional hook for capabilities that attach side-effects to
# intermediate labels (e.g. research's ``APPEND`` mutates the
# topic queue). When the hook returns a non-empty string we
@@ -348,7 +368,7 @@ async def run_agentic_loop(
)
_append_repair_messages(
messages=messages,
- iteration_text=step.text,
+ step=step,
violation="unknown_action",
host=host,
)
@@ -419,17 +439,28 @@ _REPAIR_PREVIEW_CHARS = 500
def _append_repair_messages(
*,
messages: list[dict[str, Any]],
- iteration_text: str,
+ step: LabeledStepResult,
violation: str,
host: LoopHost,
) -> None:
"""Preserve the model's unlabeled draft as assistant context, then add
- a correction prompt that tells the next iteration what to do."""
- clipped = str(iteration_text or "").strip()
+ a correction prompt that tells the next iteration what to do.
+
+ Takes the whole step rather than its text so the round's reasoning travels
+ with the draft: a repair round is still a round, and a thinking model's
+ provider rejects a history that lost it.
+ """
+ clipped = str(step.text or "").strip()
if clipped:
if len(clipped) > _REPAIR_PREVIEW_CHARS:
clipped = clipped[:_REPAIR_PREVIEW_CHARS].rstrip() + "\n...[truncated]"
- messages.append({"role": "assistant", "content": clipped})
+ messages.append(
+ assistant_message(
+ clipped,
+ reasoning_content=step.reasoning_content or None,
+ thinking_blocks=list(step.thinking_blocks) or None,
+ )
+ )
messages.append({"role": "user", "content": host.protocol_repair_message(violation)})
diff --git a/deeptutor/runtime/agentic/messages.py b/deeptutor/runtime/agentic/messages.py
index 0ea57152f..010d5357f 100644
--- a/deeptutor/runtime/agentic/messages.py
+++ b/deeptutor/runtime/agentic/messages.py
@@ -55,4 +55,25 @@ def assistant_message_with_tool_calls(
return message
-__all__ = ["assistant_message_with_tool_calls"]
+def assistant_message(
+ content: str,
+ *,
+ reasoning_content: str | None = None,
+ thinking_blocks: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ """Build a plain assistant turn, carrying its reasoning when there was any.
+
+ The tool-call builder above and this one exist for the same reason: a
+ thinking model's history has to keep the reasoning that produced each
+ assistant turn, or the provider refuses the continuation. Which of the two
+ a round needs depends only on whether it called tools.
+ """
+ message: dict[str, Any] = {"role": "assistant", "content": content}
+ if reasoning_content:
+ message["reasoning_content"] = reasoning_content
+ if thinking_blocks:
+ message["thinking_blocks"] = thinking_blocks
+ return message
+
+
+__all__ = ["assistant_message", "assistant_message_with_tool_calls"]
diff --git a/tests/core/agentic/test_loop_reasoning_replay.py b/tests/core/agentic/test_loop_reasoning_replay.py
new file mode 100644
index 000000000..b544633f4
--- /dev/null
+++ b/tests/core/agentic/test_loop_reasoning_replay.py
@@ -0,0 +1,268 @@
+"""The shared agentic loop must echo a round's reasoning on the next request.
+
+DeepSeek's thinking models reject a continuation whose history has lost the
+previous assistant turn's reasoning:
+
+ The `reasoning_content` in the thinking mode must be passed back to the API.
+
+Chat's own loop has always replayed it. The shared ``runtime/agentic`` loop —
+the one quiz, research, PageIndex and explore_context all run on — read
+``reasoning_content`` off the stream, pushed it to the trace UI for display,
+and then dropped it. Round one could not fail (system + user only); round two
+always did.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from deeptutor.runtime.agentic.loop import LabelProtocol, run_agentic_loop
+from deeptutor.runtime.agentic.tool_dispatch import DispatchOutcome
+from deeptutor.runtime.stream_bus import StreamBus
+
+
+def _content_chunk(content: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ choices=[SimpleNamespace(delta=SimpleNamespace(content=content, tool_calls=None))]
+ )
+
+
+def _reasoning_chunk(reasoning: str) -> SimpleNamespace:
+ """A thinking model's reasoning phase emits no ``delta.content`` at all."""
+ return SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ delta=SimpleNamespace(content=None, tool_calls=None, reasoning_content=reasoning)
+ )
+ ]
+ )
+
+
+def _signed_thinking_chunk(blocks: list[dict[str, Any]]) -> SimpleNamespace:
+ """Anthropic's signed blocks ride on the choice, not the delta."""
+ return SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ delta=SimpleNamespace(content=None, tool_calls=None),
+ provider_specific_fields={"thinking_blocks": blocks},
+ )
+ ]
+ )
+
+
+def _tool_call_chunk(call_id: str, name: str, arguments: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ delta=SimpleNamespace(
+ content=None,
+ tool_calls=[
+ SimpleNamespace(
+ index=0,
+ id=call_id,
+ function=SimpleNamespace(name=name, arguments=arguments),
+ )
+ ],
+ )
+ )
+ ]
+ )
+
+
+async def _async_stream(chunks: list[SimpleNamespace]):
+ for chunk in chunks:
+ yield chunk
+
+
+class _ScriptedClient:
+ def __init__(self, scripts: list[list[SimpleNamespace]]) -> None:
+ self._scripts = list(scripts)
+ self.calls: list[list[dict[str, Any]]] = []
+
+ class _Completions:
+ def __init__(self, parent: _ScriptedClient) -> None:
+ self.parent = parent
+
+ async def create(self, **kwargs: Any):
+ self.parent.calls.append(list(kwargs.get("messages") or []))
+ if not self.parent._scripts:
+ raise RuntimeError("scripted client exhausted")
+ return _async_stream(self.parent._scripts.pop(0))
+
+ class _Chat:
+ def __init__(self, parent: _ScriptedClient) -> None:
+ self.completions = _Completions(parent)
+
+ self.chat = _Chat(self)
+
+
+class _Host:
+ def __init__(self) -> None:
+ self.final_text: str | None = None
+
+ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:
+ return None
+
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
+ return ({"iter": iteration}, {"iter": iteration, "final": True})
+
+ async def dispatch_tools(self, *, iteration, tool_calls):
+ return DispatchOutcome(
+ sources=[],
+ tool_messages=[
+ {"role": "tool", "tool_call_id": call["id"], "content": "{}"} for call in tool_calls
+ ],
+ )
+
+ async def resolve_pause(self, dispatch): # pragma: no cover
+ return False
+
+ async def emit_terminator(self, payload): # pragma: no cover
+ return None
+
+ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:
+ self.final_text = text
+
+ def protocol_retry_notice(self) -> str:
+ return "retry"
+
+ def protocol_repair_message(self, violation: str) -> str:
+ return f"repair:{violation}"
+
+ async def force_finalize(self, *, messages, start_iteration):
+ return ("", False, 0)
+
+
+_PROTOCOL = LabelProtocol(
+ allowed=("THINK", "TOOL", "FINISH"),
+ terminal=frozenset({"FINISH"}),
+ intermediate=frozenset({"THINK"}),
+ final=frozenset({"FINISH"}),
+ tool_label="TOOL",
+)
+
+
+async def _run(scripts: list[list[SimpleNamespace]]) -> _ScriptedClient:
+ client = _ScriptedClient(scripts)
+ bus = StreamBus()
+
+ async def _consume() -> None:
+ async for _ in bus.subscribe():
+ pass
+
+ consumer = asyncio.create_task(_consume())
+ await asyncio.sleep(0)
+ try:
+ await run_agentic_loop(
+ initial_messages=[{"role": "user", "content": "hi"}],
+ protocol=_PROTOCOL,
+ client=client,
+ model="deepseek-v4-flash",
+ completion_kwargs={},
+ binding="deepseek",
+ tool_schemas=None,
+ stream=bus,
+ source="test",
+ stage="test",
+ max_iterations=4,
+ host=_Host(),
+ )
+ finally:
+ await bus.close()
+ await consumer
+ return client
+
+
+def _assistant_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [m for m in messages if m.get("role") == "assistant"]
+
+
+async def test_a_tool_round_replays_its_reasoning() -> None:
+ """The strict case: DeepSeek requires it on the turn that called tools."""
+ client = await _run(
+ [
+ [
+ _reasoning_chunk("I should look this up."),
+ _content_chunk("``TOOL``\n"),
+ _tool_call_chunk("c1", "read_source", "{}"),
+ ],
+ [_content_chunk("``FINISH``\ndone")],
+ ]
+ )
+
+ second_request = _assistant_messages(client.calls[1])
+ assert len(second_request) == 1
+ assert second_request[0]["reasoning_content"] == "I should look this up."
+ assert second_request[0]["tool_calls"]
+
+
+async def test_an_intermediate_round_replays_its_reasoning() -> None:
+ client = await _run(
+ [
+ [
+ _reasoning_chunk("Weighing two framings."),
+ _content_chunk("``THINK``\nstill working"),
+ ],
+ [_content_chunk("``FINISH``\ndone")],
+ ]
+ )
+
+ second_request = _assistant_messages(client.calls[1])
+ assert second_request[0]["reasoning_content"] == "Weighing two framings."
+
+
+async def test_a_repair_round_replays_its_reasoning() -> None:
+ """A protocol violation still produced a round, and it still had reasoning."""
+ client = await _run(
+ [
+ [
+ _reasoning_chunk("Forgot the label."),
+ _content_chunk("no label at all"),
+ ],
+ [_content_chunk("``FINISH``\ndone")],
+ ]
+ )
+
+ second_request = _assistant_messages(client.calls[1])
+ assert second_request[0]["reasoning_content"] == "Forgot the label."
+
+
+async def test_signed_thinking_blocks_survive_the_round() -> None:
+ """Anthropic's blocks are signed, so they cannot be rebuilt from text."""
+ blocks = [{"type": "thinking", "thinking": "…", "signature": "sig-1"}]
+ client = await _run(
+ [
+ [
+ _signed_thinking_chunk(blocks),
+ _content_chunk("``TOOL``\n"),
+ _tool_call_chunk("c1", "read_source", "{}"),
+ ],
+ [_content_chunk("``FINISH``\ndone")],
+ ]
+ )
+
+ second_request = _assistant_messages(client.calls[1])
+ assert second_request[0]["thinking_blocks"] == blocks
+
+
+async def test_a_round_without_reasoning_adds_no_field() -> None:
+ """An ordinary model's history must be byte-identical to before."""
+ client = await _run(
+ [
+ [_content_chunk("``THINK``\nplain"), _content_chunk("")],
+ [_content_chunk("``FINISH``\ndone")],
+ ]
+ )
+
+ second_request = _assistant_messages(client.calls[1])
+ assert "reasoning_content" not in second_request[0]
+ assert "thinking_blocks" not in second_request[0]