DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(explore-context): keep reasoning on replayed rounds for thinking providers (#1400) (#1404)
ZQR1101f27f34771309
diff --git a/deeptutor/capabilities/explore_context/explorer.py b/deeptutor/capabilities/explore_context/explorer.pyindex 1aab50d6c..df865a55a 100644--- a/deeptutor/capabilities/explore_context/explorer.py+++ b/deeptutor/capabilities/explore_context/explorer.py@@ -38,7 +38,7 @@ from deeptutor.runtime.agentic import (can_use_native_tool_calling,dispatch_tool_calls,)-from deeptutor.runtime.agentic.messages import assistant_message_with_tool_calls+from deeptutor.runtime.agentic.messages import assistant_message, assistant_message_with_tool_callsfrom deeptutor.runtime.agentic.tool_call_stream import ToolCallAccumulatorfrom deeptutor.runtime.registry.tool_registry import get_tool_registryfrom deeptutor.runtime.stream_bus import StreamBus@@ -46,6 +46,7 @@ from deeptutor.services.config.loader import get_capability_paramsfrom deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargsfrom deeptutor.services.llm import stream as llm_streamfrom deeptutor.services.llm.capabilities import threads_session_id+from deeptutor.services.session.provider_response_state import normalize_provider_response_statelogger = logging.getLogger(__name__)@@ -98,6 +99,14 @@ class _CallResult:# 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 = ""+ # The provider's own native output items (Responses wire) and Anthropic's+ # signed thinking blocks, replayed on the next request. On a Responses-wire+ # provider the chat-dialect ``reasoning_content`` field is not understood+ # by the request converter — a tool-round history that lost the native+ # items is rejected by thinking models with "the ``reasoning_content`` in+ # the thinking mode must be passed back to the API".+ response_output_items: list[dict[str, Any]] = field(default_factory=list)+ thinking_blocks: list[dict[str, Any]] = field(default_factory=list)class ContextExplorer:@@ -209,6 +218,8 @@ class ContextExplorer:investigation = ""total_in = 0total_out = 0+ nudged_empty_finish = False+ forced_finish_appended = Falseasync with stream.stage(EXPLORE_STAGE, source=EXPLORE_SOURCE, metadata=stage_meta):await stream.progress(self._status_exploring(),@@ -220,10 +231,11 @@ class ContextExplorer:)for round_idx in range(MAX_LOOP_ROUNDS):is_last = round_idx == MAX_LOOP_ROUNDS - 1- if is_last:+ if is_last and not forced_finish_appended:# Budget exhausted while still calling tools — force a# tool-less finish from what has been gathered.messages.append({"role": "user", "content": self._forced_finish_instruction()})+ forced_finish_appended = Truetotal_in += sum(_content_chars(m) for m in messages)result = await self._call_llm(client,@@ -236,14 +248,41 @@ class ContextExplorer:total_out += result.output_charsif not result.tool_calls:investigation = result.text+ if (+ not investigation.strip()+ and result.reasoning_content+ and not is_last+ and not nudged_empty_finish+ ):+ # The round burned its output budget on internal+ # reasoning and never acted — the shape a thinking+ # model falls into on a tight per-round budget. Nudge+ # it once with the same forced-finish instruction the+ # last round uses; a second reasoning-only round still+ # ends the loop and degrades to the single pass.+ nudged_empty_finish = True+ await stream.progress(+ self._t(+ "status.reasoning_only_nudged",+ default=(+ "The exploration round produced only internal "+ "reasoning; asked the model to write its "+ "investigation now."+ ),+ ),+ source=EXPLORE_SOURCE,+ stage=EXPLORE_STAGE,+ metadata=merge_trace_metadata(stage_meta, {"trace_kind": "warning"}),+ )+ nudged = _assistant_message_with_provider_state(result)+ messages.append(nudged)+ messages.append(+ {"role": "user", "content": self._forced_finish_instruction()}+ )+ forced_finish_appended = True+ continuebreak- messages.append(- assistant_message_with_tool_calls(- result.text,- result.tool_calls,- reasoning_content=result.reasoning_content or None,- )- )+ messages.append(_assistant_message_with_provider_state(result))dispatch = await dispatch_tool_calls(tool_calls=result.tool_calls,context=context,@@ -301,6 +340,8 @@ class ContextExplorer:text_parts: list[str] = []reasoning_parts: list[str] = []+ response_output_items: list[dict[str, Any]] = []+ thinking_blocks: list[dict[str, Any]] = []tool_acc = ToolCallAccumulator()output_chars = 0response_stream = await client.chat.completions.create(**kwargs)@@ -309,7 +350,18 @@ class ContextExplorer:choices = getattr(chunk, "choices", None) or []if not choices:continue- delta = getattr(choices[0], "delta", None)+ choice = choices[0]+ provider_fields = getattr(choice, "provider_specific_fields", None)+ if isinstance(provider_fields, dict):+ native_items = provider_fields.get("native_output_items")+ if isinstance(native_items, list):+ response_output_items.extend(+ item for item in native_items if isinstance(item, dict)+ )+ blocks = provider_fields.get("thinking_blocks")+ if isinstance(blocks, list):+ thinking_blocks.extend(block for block in blocks if isinstance(block, dict))+ delta = getattr(choice, "delta", None)if delta is None:continuereasoning = getattr(delta, "reasoning_content", None) or getattr(@@ -342,6 +394,8 @@ class ContextExplorer:tool_calls=tool_calls,output_chars=output_chars,reasoning_content="".join(reasoning_parts),+ response_output_items=response_output_items,+ thinking_blocks=thinking_blocks,)def _read_source_schemas(self, source_index: dict[str, str]) -> list[dict[str, Any]]:@@ -533,6 +587,42 @@ class ContextExplorer:return self._t("briefing_header", default="[Context Investigation]")+def _assistant_message_with_provider_state(result: _CallResult) -> dict[str, Any]:+ """The round's assistant turn with its reasoning replay state attached.++ The chat-dialect ``reasoning_content`` field covers Chat Completions+ providers. On a Responses-wire provider the request converter only+ replays reasoning from the provider's own native output items — a history+ that lost them is rejected by thinking models with "the+ ``reasoning_content`` in the thinking mode must be passed back to the+ API" (#1400), so the native items ride along as private state.+ """+ if result.tool_calls:+ message = assistant_message_with_tool_calls(+ result.text,+ result.tool_calls,+ reasoning_content=result.reasoning_content or None,+ thinking_blocks=result.thinking_blocks or None,+ )+ else:+ message = assistant_message(+ result.text,+ reasoning_content=result.reasoning_content or None,+ thinking_blocks=result.thinking_blocks or None,+ )+ state: dict[str, Any] = {}+ if result.response_output_items:+ state["responses_output_items"] = result.response_output_items+ if result.reasoning_content:+ state["reasoning_content"] = result.reasoning_content+ if result.thinking_blocks:+ state["thinking_blocks"] = result.thinking_blocks+ normalized = normalize_provider_response_state(state)+ if normalized is not None:+ message["_provider_response_state"] = normalized+ return message++def _content_chars(message: dict[str, Any]) -> int:content = message.get("content")if isinstance(content, str):diff --git a/deeptutor/capabilities/explore_context/prompts/en/explore_context.yaml b/deeptutor/capabilities/explore_context/prompts/en/explore_context.yamlindex 65f910718..06b6d980f 100644--- a/deeptutor/capabilities/explore_context/prompts/en/explore_context.yaml+++ b/deeptutor/capabilities/explore_context/prompts/en/explore_context.yaml@@ -113,3 +113,4 @@ briefing_header: |status:exploring: "Context exploration"+ reasoning_only_nudged: "The exploration round produced only internal reasoning; asked the model to write its investigation now."diff --git a/deeptutor/capabilities/explore_context/prompts/zh/explore_context.yaml b/deeptutor/capabilities/explore_context/prompts/zh/explore_context.yamlindex e6fb85ab7..9c0046bfb 100644--- a/deeptutor/capabilities/explore_context/prompts/zh/explore_context.yaml+++ b/deeptutor/capabilities/explore_context/prompts/zh/explore_context.yaml@@ -87,3 +87,4 @@ briefing_header: |status:exploring: "上下文调查"+ reasoning_only_nudged: "调查轮次只有内部推理,已要求模型直接写出调查结论。"diff --git a/tests/capabilities/test_explore_context_capability.py b/tests/capabilities/test_explore_context_capability.pyindex 8510ff63d..bd5a28dfe 100644--- a/tests/capabilities/test_explore_context_capability.py+++ b/tests/capabilities/test_explore_context_capability.py@@ -178,22 +178,28 @@ class _FakeDelta:self,content: str | None = None,tool_calls: list[_FakeToolCall] | None = None,+ reasoning_content: str | None = None,) -> None:self.content = contentself.tool_calls = tool_calls- self.reasoning_content = None+ self.reasoning_content = reasoning_contentself.reasoning = Noneclass _FakeChoice:- def __init__(self, delta: _FakeDelta) -> None:+ def __init__(self, delta: _FakeDelta, provider_specific_fields: dict | None = None) -> None:self.delta = deltaself.finish_reason = None+ self.provider_specific_fields = provider_specific_fieldsclass _FakeChunk:- def __init__(self, delta: _FakeDelta) -> None:- self.choices = [_FakeChoice(delta)]+ def __init__(+ self,+ delta: _FakeDelta,+ provider_specific_fields: dict | None = None,+ ) -> None:+ self.choices = [_FakeChoice(delta, provider_specific_fields)]self.usage = None@@ -295,6 +301,174 @@ async def test_loop_falls_back_to_single_pass_on_client_error(assert "fallback briefing text" in block.content+# ---------------------------------------------------------------------------+# Reasoning replay state (#1400: DeepSeek thinking mode rejects a tool-round+# history whose reasoning was dropped — Responses-wire converters only replay+# it from ``_provider_response_state``).+# ---------------------------------------------------------------------------+++def _reasoning_tool_round(native_items: list[dict[str, Any]] | None) -> list[_FakeChunk]:+ """One streamed round: reasoning delta, then a read_source tool call."""+ chunks = [+ _FakeChunk(_FakeDelta(reasoning_content="I should read the transcript first.")),+ _FakeChunk(+ _FakeDelta(+ tool_calls=[_FakeToolCall(0, "call_1", "read_source", '{"source_id": "hs-x"}')]+ )+ ),+ ]+ if native_items is not None:+ chunks.append(+ _FakeChunk(+ _FakeDelta(),+ provider_specific_fields={"native_output_items": native_items},+ )+ )+ return chunks+++async def test_loop_replays_provider_reasoning_state_on_tool_rounds(+ monkeypatch: pytest.MonkeyPatch, _force_loop: None+) -> None:+ """The tool-round assistant message carries the provider's native output+ items so a Responses-wire provider still sees the round's reasoning."""+ native_items = [+ {+ "type": "reasoning",+ "id": "rs_1",+ "content": [{"type": "reasoning_text", "text": "I should read the transcript first."}],+ },+ {+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_1",+ "name": "read_source",+ "arguments": '{"source_id": "hs-x"}',+ },+ ]+ fake_client = _FakeClient(+ [+ _reasoning_tool_round(native_items),+ [_FakeChunk(_FakeDelta(content="The transcript shows the nav was rewritten."))],+ ]+ )+ monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)++ cap = ExploreContextCapability()+ ctx = _ctx(+ source_index={"hs-x": "## Claude Code\nI rewrote the nav and shipped it."},+ history_references=["x"],+ )++ block = await cap.pre_loop(ctx, StreamBus(), usage=None)++ assert isinstance(block, PromptBlock)+ assert "nav was rewritten" in block.content+ completions = fake_client.chat.completions+ assert len(completions.calls) == 2+ assistant = next(m for m in completions.calls[1]["messages"] if m.get("role") == "assistant")+ state = assistant.get("_provider_response_state")+ assert state is not None+ assert state.get("responses_output_items") == native_items+ # The chat-dialect echo stays on the message for Chat Completions providers.+ assert assistant.get("reasoning_content") == "I should read the transcript first."+++async def test_loop_plain_provider_keeps_chat_echo_without_native_items(+ monkeypatch: pytest.MonkeyPatch, _force_loop: None+) -> None:+ """A provider that never reported native output items gets the plain+ chat-completions echo — and never a fabricated reasoning item."""+ fake_client = _FakeClient(+ [+ _reasoning_tool_round(None),+ [_FakeChunk(_FakeDelta(content="The transcript shows the nav was rewritten."))],+ ]+ )+ monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)++ cap = ExploreContextCapability()+ ctx = _ctx(+ source_index={"hs-x": "## Claude Code\nI rewrote the nav."}, history_references=["x"]+ )++ await cap.pre_loop(ctx, StreamBus(), usage=None)++ completions = fake_client.chat.completions+ assistant = next(m for m in completions.calls[1]["messages"] if m.get("role") == "assistant")+ assert assistant.get("reasoning_content") == "I should read the transcript first."+ state = assistant.get("_provider_response_state")+ assert not (state or {}).get("responses_output_items")+++async def test_loop_nudges_reasoning_only_round_into_writing(+ monkeypatch: pytest.MonkeyPatch, _force_loop: None+) -> None:+ """A round that produced only reasoning (budget burned, nothing visible)+ is nudged once with the forced-finish instruction instead of silently+ collapsing into the single-pass fallback."""+ monkeypatch.setattr(+ explorer_mod, "llm_stream", _fake_stream(["fallback briefing that must not be used"])+ )+ fake_client = _FakeClient(+ [+ [_FakeChunk(_FakeDelta(reasoning_content="Planning the whole investigation..."))],+ [_FakeChunk(_FakeDelta(content="The transcript shows the nav was rewritten."))],+ ]+ )+ monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)++ cap = ExploreContextCapability()+ ctx = _ctx(+ source_index={"hs-x": "## Claude Code\nI rewrote the nav."}, history_references=["x"]+ )++ block = await cap.pre_loop(ctx, StreamBus(), usage=None)++ completions = fake_client.chat.completions+ assert len(completions.calls) == 2+ second_messages = completions.calls[1]["messages"]+ nudged_assistant = next(m for m in second_messages if m.get("role") == "assistant")+ assert nudged_assistant.get("reasoning_content") == "Planning the whole investigation..."+ assert second_messages[-1]["role"] == "user"+ assert "Investigation budget reached" in str(second_messages[-1]["content"])+ # The loop's own investigation won — not the single-pass fallback.+ assert isinstance(block, PromptBlock)+ assert "nav was rewritten" in block.content+++async def test_reasoning_only_exhaustion_falls_back_to_single_pass(+ monkeypatch: pytest.MonkeyPatch, _force_loop: None+) -> None:+ """The nudge fires once; a second reasoning-only round ends the loop and+ degrades to the single-pass briefing (bounded, never an infinite nudge)."""+ monkeypatch.setattr(explorer_mod, "llm_stream", _fake_stream(["fallback briefing text"]))+ fake_client = _FakeClient(+ [+ [_FakeChunk(_FakeDelta(reasoning_content="Thinking pass one..."))],+ [_FakeChunk(_FakeDelta(reasoning_content="Thinking pass two..."))],+ ]+ )+ monkeypatch.setattr(explorer_mod, "build_openai_client", lambda _cfg: fake_client)++ cap = ExploreContextCapability()+ ctx = _ctx(+ source_index={"hs-x": "## Claude Code\nI rewrote the nav."}, history_references=["x"]+ )++ block = await cap.pre_loop(ctx, StreamBus(), usage=None)++ # Round 0 nudged, round 1 reasoning-only again → loop ends, single pass runs.+ assert len(fake_client.chat.completions.calls) == 2+ assert isinstance(block, PromptBlock)+ assert "fallback briefing text" in block.content++# ---------------------------------------------------------------------------# ContextExplorer source assembly (single-pass helpers)# ---------------------------------------------------------------------------