The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): recover inline reasoning stripped by the think scrubber
SayHell0W0rlde0c3006f72eb
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 2fbe12be028..af286133073 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3269,6 +3269,13 @@ class _StreamingCall(StreamingWaitMonitor):args or stamping "stop"."""full_content = "".join(content_parts) or Nonefull_reasoning = "".join(reasoning_parts) or None+ if not full_reasoning:+ # Providers that inline reasoning (MiniMax-M3 streams <think>…</think> in content) never+ # send a reasoning delta — recover what the think scrubber stripped so the structured+ # reasoning_content field stays populated (#89647).+ think_scrubber = getattr(self.agent, "_stream_think_scrubber", None)+ if think_scrubber is not None:+ full_reasoning = think_scrubber.reasoning() or Nonemock_tool_calls, has_truncated_tool_args = self._assemble_tool_calls(tool_calls_acc, finish_reason)# Zero-chunk guard: nothing usable = upstream error / malformed SSE.if finish_reason is None and not content_parts and not reasoning_parts and not refusal_parts and not tool_calls_acc:diff --git a/agent/think_scrubber.py b/agent/think_scrubber.pyindex 3ee45f0ca84..32b217de88c 100644--- a/agent/think_scrubber.py+++ b/agent/think_scrubber.py@@ -23,6 +23,13 @@ THINK_TAG_NAMES: Tuple[str, ...] = ("think", "thinking", "reasoning", "thought",THINK_OPEN_TAGS: Tuple[str, ...] = tuple(f"<{name.lower()}>" for name in THINK_TAG_NAMES)THINK_CLOSE_TAGS: Tuple[str, ...] = tuple(f"</{name.lower()}>" for name in THINK_TAG_NAMES)+# Tag markup stripped by reasoning(); matches every variant the scrubber+# recognizes (open, close, case-insensitive).+_THINK_TAG_RE = re.compile(+ r"<\s*/?\s*(?:" + "|".join(THINK_TAG_NAMES) + r")\s*>",+ re.IGNORECASE,+)+class StreamingThinkScrubber:"""Stateful scrubber for streaming reasoning/thinking blocks.@@ -50,6 +57,7 @@ class StreamingThinkScrubber:self._in_block: bool = Falseself._buf: str = ""self._last_emitted_ended_newline: bool = True+ self._reasoning_parts: list[str] = []def _emit(self, out: list[str], text: str) -> None:"""Append visible prose to *out* (orphan close tags stripped) and track the newline flag."""@@ -70,9 +78,15 @@ class StreamingThinkScrubber:if self._in_block:close_idx, close_len = self._find_first_tag(buf, self._CLOSE_TAGS)if close_idx == -1:- # No close yet: hold back a possible partial close-tag prefix, drop the rest.- self._hold_partial(buf, self._CLOSE_TAGS)+ # No close yet: hold back a possible partial close-tag prefix; collect+ # the rest as reasoning (#89647).+ discard = self._hold_partial(buf, self._CLOSE_TAGS)+ if discard:+ self._reasoning_parts.append(discard)break+ # Found close: collect block content as reasoning (#89647).+ if buf[:close_idx]:+ self._reasoning_parts.append(buf[:close_idx])buf = buf[close_idx + close_len:]self._in_block = Falsecontinue@@ -84,6 +98,8 @@ class StreamingThinkScrubber:open_idx, open_len = self._find_open_at_boundary(buf, out)if pair is not None and (open_idx == -1 or pair[0] <= open_idx):self._emit(out, buf[:pair[0]])+ # Collect the stripped pair (tags removed by reasoning()) (#89647).+ self._reasoning_parts.append(buf[pair[0]:pair[1]])buf = buf[pair[1]:]continueif open_idx != -1:@@ -110,12 +126,25 @@ class StreamingThinkScrubber:partial reasoning is worse than a truncated answer), otherwise the tail is emitted verbatim.Always resets the boundary flag — intra-turn retries flush then stream again without ``reset()``,and a stale False flag made the new stream's opening ``<think>`` look mid-line."""+ if self._in_block and self._buf:+ self._reasoning_parts.append(self._buf)tail = "" if self._in_block else self._bufself._buf = ""self._in_block = Falseself._last_emitted_ended_newline = Truereturn self._strip_orphan_close_tags(tail) if tail else ""+ def reasoning(self) -> str:+ """Reasoning text stripped from streamed content so far, tag markup removed ("" when none).++ Lets callers populate a structured ``reasoning_content`` field for providers (e.g. MiniMax-M3)+ that inline reasoning instead of returning a reasoning delta (#89647).+ """+ if not self._reasoning_parts:+ return ""+ cleaned = [t for t in (_THINK_TAG_RE.sub("", part).strip() for part in self._reasoning_parts) if t]+ return "\n".join(cleaned)+# ── internal helpers ───────────────────────────────────────────────@staticmethoddiff --git a/tests/agent/test_think_scrubber.py b/tests/agent/test_think_scrubber.pyindex 8c1a2d69d97..72d719d2398 100644--- a/tests/agent/test_think_scrubber.py+++ b/tests/agent/test_think_scrubber.py@@ -182,3 +182,36 @@ class TestRealisticStreaming:s = StreamingThinkScrubber()deltas = ["Hello ", "world ", "how ", "are ", "you?"]assert _drive(s, deltas) == "Hello world how are you?"+++class TestReasoningCollection:+ """The scrubber collects stripped reasoning for structured fields (#89647)."""++ def test_collects_split_block_across_deltas(self) -> None:+ s = StreamingThinkScrubber()+ visible = _drive(s, ["<think>", "Let me check", " their config", "</think>", "Done."])+ assert visible == "Done."+ assert s.reasoning() == "Let me check\ntheir config"++ def test_collects_closed_pair_in_single_delta(self) -> None:+ s = StreamingThinkScrubber()+ visible = _drive(s, ["<think>inline reasoning</think>Hello"])+ assert visible == "Hello"+ assert s.reasoning() == "inline reasoning"++ def test_empty_when_no_reasoning(self) -> None:+ s = StreamingThinkScrubber()+ _drive(s, ["Just visible text"])+ assert s.reasoning() == ""++ def test_strips_tag_markup_from_collected_text(self) -> None:+ s = StreamingThinkScrubber()+ _drive(s, ["<thinking>plan</thinking>ok"])+ assert s.reasoning() == "plan"++ def test_reset_clears_collected_reasoning(self) -> None:+ s = StreamingThinkScrubber()+ _drive(s, ["<think>a</think>x"])+ assert s.reasoning() == "a"+ s.reset()+ assert s.reasoning() == ""