From a79fc13ea779800f5b18b595f242bec7e3f33176 Mon Sep 17 00:00:00 2001 From: SamAI CI Date: Sat, 27 Jun 2026 11:43:56 +0800 Subject: [PATCH] fix(think_scrubber): recover final answer from unclosed block MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem Some OpenAI-compatible LLM gateways (e.g. relays fronting MiniMax-M1 / Step-3.7-Flash / Intern-S2-Preview) inline the model's reasoning AND the final answer inside `delta.content` wrapped in a single `` open tag with NO matching `` close. The model intends: reasoning = "The user is asking for 2+2. The answer is 4." final_answer = "4" …and streams it as: delta1: "The user is asking for 2+2. The answer is 4.\n4" (stream ends — no ) StreamingThinkScrubber sees the unclosed `` as a truncated reasoning block and, at flush() time, discards EVERYTHING held back in the buffer — including the final answer "4" that came after the newline. The agent then sees an empty content string and reports "Empty response from model — retrying (1/3)". This was observed in production with the aicq-hermes plugin (v1.2.4) connecting to http://aicq.online:3000/v1 with model "mymodel". The workaround shipped in aicq-hermes v1.2.4 was a monkey-patch on StreamingThinkScrubber.flush; this PR upstreams the fix properly. ## Root cause Two issues in `agent/think_scrubber.py`: 1. `feed()` (line ~125, the `_in_block=True` branch with no close tag found): when inside an open block and the current delta has no close tag, the code only held back a partial close-tag prefix (`_max_partial_suffix`) and DISCARDED everything else. This meant reasoning + final answer prose was dropped in real time — by the time flush() ran, `_buf` only contained a few chars of partial close-tag prefix (usually empty). 2. `flush()` (line ~204, the `_in_block=True` branch): unconditionally returned `""` when still inside an unterminated block, with no attempt to recover visible content. The docstring explicitly justified this as "leaking partial reasoning is worse than a truncated answer" — a reasonable default for truly truncated streams, but wrong for the "inline reasoning + answer, no close tag" pattern. ## Fix **feed() change**: when `_in_block=True` and no close tag is found in the current delta, accumulate the ENTIRE delta into `_buf` (instead of discarding everything except a partial close-tag prefix). The next feed() call prepends `_buf` to the new text and re-scans for close tags across the boundary, so partial close-tags split across deltas are still detected. This change is safe because: - When a close tag IS found later, `buf = buf[close_idx + close_len:]` discards everything before it (the reasoning), so accumulated content is correctly dropped on close. - When no close tag ever arrives (the bug scenario), the accumulated content is available for flush() to recover the final answer. **flush() change**: when `_in_block=True` at end-of-stream, look for the last newline in `_buf` and emit whatever came after it as the visible response. Reasoning models that follow the reasoning-then-newline-then-answer pattern are recovered. If there is NO newline (e.g. pure truncated reasoning with no answer), the original discard-everything behaviour is preserved — this protects the existing test contract: _drive(s, ["reasoning text with no close"]) == "" _drive(s, ["", "The user wants", " to know something"]) == "" An opt-out knob `recover_unclosed_final_answer=False` is added on the scrubber instance for plugins/users who want the strict discard behaviour (e.g. when running against a gateway that emits properly closed tags and the recovery is undesirable). ## Test coverage 4 new tests in `TestFlushBehaviour`: - `test_flush_recovers_final_answer_after_newline_in_unclosed_block`: the core bug repro — single delta with reasoning + newline + answer. - `test_flush_recovers_final_answer_split_across_deltas`: same, but reasoning and answer arrive in separate deltas. - `test_flush_recovers_final_answer_multiline_reasoning`: multi-line reasoning; recovery picks the LAST newline so only the final answer is emitted. - `test_flush_opt_out_recovers_unclosed_final_answer`: setting `recover_unclosed_final_answer=False` restores the strict discard behaviour. All 31 existing tests in `test_think_scrubber.py` still pass unchanged — the fix is backward-compatible because every existing unterminated-block test case has no newline in the held-back buffer, so the new "find last newline" logic falls through to the original `return ""` path. All 8 tests in `tests/cli/test_stream_delta_think_tag.py` also still pass. ## Verification End-to-end tested on a mos3 container with hermes-agent 0.17.0 and the aicq-hermes plugin v1.2.4 (with the monkey-patch removed to isolate the upstream fix): # Before fix (vanilla 0.17.0): hermes -z "What is 2+2? Reply briefly." # -> "Empty response from model — retrying (1/3)" x3, then "❌ Model # returned no content after all retries." # After fix (this PR applied): hermes -z "What is 2+2? Reply briefly." # -> "4" # 11-prompt regression suite via the aicq.me chat network: # 11/11 PASS (math, capitals, translations, instruction-following) The aicq-hermes plugin's monkey-patch shim (added in v1.2.4) is no longer needed once this PR lands — the plugin will remove its shim in a follow-up release. --- agent/think_scrubber.py | 71 ++++++++++++++++++++++++++---- tests/agent/test_think_scrubber.py | 55 +++++++++++++++++++++++ 2 files changed, 118 insertions(+), 8 deletions(-) diff --git a/agent/think_scrubber.py b/agent/think_scrubber.py index 44ddcacff7042..fc8297d476e98 100644 --- a/agent/think_scrubber.py +++ b/agent/think_scrubber.py @@ -123,10 +123,15 @@ def feed(self, text: str) -> str: buf, self._CLOSE_TAGS, ) if close_idx == -1: - # No close yet — hold back a potential partial - # close-tag prefix; discard everything else. - held = self._max_partial_suffix(buf, self._CLOSE_TAGS) - self._buf = buf[-held:] if held else "" + # No close yet — accumulate everything into _buf + # so flush() can recover the final answer if the + # model inlined reasoning + answer inside an + # unclosed (see flush() docstring). + # _max_partial_suffix is no longer needed here + # because we keep the full buffer; the next feed() + # will prepend _buf to the new text and re-scan + # for close tags across the boundary. + self._buf = (self._buf or "") + buf return "".join(out) # Found close: discard block content + tag, continue. buf = buf[close_idx + close_len:] @@ -204,14 +209,64 @@ def feed(self, text: str) -> str: def flush(self) -> str: """End-of-stream flush. - If still inside an unterminated block, held-back content is - discarded — leaking partial reasoning is worse than a - truncated answer. Otherwise the held-back partial-tag tail is - emitted verbatim (it turned out not to be a real tag prefix). + If still inside an unterminated block, the default behaviour is + to discard held-back content — leaking partial reasoning is + worse than a truncated answer. + + However, some OpenAI-compatible LLM gateways (e.g. relays + fronting MiniMax-M1 / Step-3.7-Flash / Intern-S2-Preview) + inline the model's reasoning AND the final answer inside + ``delta.content`` wrapped in a single ```` open tag with + NO matching ```` close. In that pattern the model + intends: + + reasoning = "The user is asking for 2+2. The answer is 4." + final_answer = "4" + + …and streams it as a single content sequence with the answer + on the line after the reasoning prose. Discarding everything + at flush() time throws away the final answer too, leaving the + agent with an empty ``content`` and forcing an "Empty response + from model — retrying" loop. + + To recover the answer in this case without leaking reasoning + on truncated streams, we look for the last newline in the + held-back buffer and emit whatever came after it as the + visible response. Reasoning models that follow the + reasoning-then-newline-then-answer pattern are recovered; if + there is no newline (e.g. pure truncated reasoning with no + answer) the original discard-everything behaviour is + preserved. + + Set ``recover_unclosed_final_answer=False`` on the scrubber + instance (or via the ``AICQ_HERMES_RECOVER_UNCLOSED_FINAL_ANSWER`` + env var, see aicq-hermes plugin) to opt out and restore the + strict discard behaviour. """ if self._in_block: + held = self._buf self._buf = "" self._in_block = False + if not held: + return "" + # Opt-out knob for plugins/users who want the strict + # discard behaviour (e.g. when running against a gateway + # that emits properly closed tags). + if not getattr(self, "recover_unclosed_final_answer", True): + return "" + # Find the last newline; emit whatever came after it as + # the visible response. Reasoning models that follow the + # reasoning-then-newline-then-answer pattern are recovered. + last_nl = held.rfind("\n") + if last_nl != -1 and last_nl + 1 < len(held): + tail = held[last_nl + 1:] + tail = self._strip_orphan_close_tags(tail) + if tail: + self._last_emitted_ended_newline = tail.endswith("\n") + return tail + # No newline — fall through to the original discard + # behaviour. This preserves the existing test contract: + # _drive(s, ["reasoning text with no close"]) == "" return "" tail = self._buf self._buf = "" diff --git a/tests/agent/test_think_scrubber.py b/tests/agent/test_think_scrubber.py index 0f9937d11d70d..665fe68c59ba0 100644 --- a/tests/agent/test_think_scrubber.py +++ b/tests/agent/test_think_scrubber.py @@ -192,6 +192,61 @@ def test_flush_on_empty_scrubber(self) -> None: s = StreamingThinkScrubber() assert s.flush() == "" + def test_flush_recovers_final_answer_after_newline_in_unclosed_block(self) -> None: + """Unclosed with reasoning + newline + final answer. + + Some OpenAI-compatible LLM gateways (e.g. relays fronting + MiniMax-M1 / Step-3.7-Flash / Intern-S2-Preview) inline the + model's reasoning AND the final answer inside ``delta.content`` + wrapped in a single ```` open tag with NO matching + ```` close. The model intends: + + reasoning = "The user is asking for 2+2. The answer is 4." + final_answer = "4" + + …and streams it as a single content sequence with the answer + on the line after the reasoning prose. flush() should recover + the final answer rather than discarding it. + """ + s = StreamingThinkScrubber() + deltas = ["The user is asking for 2+2. The answer is 4.\n4"] + assert _drive(s, deltas) == "4" + + def test_flush_recovers_final_answer_split_across_deltas(self) -> None: + """Same recovery, but reasoning and answer arrive in separate deltas.""" + s = StreamingThinkScrubber() + deltas = [ + "The user is asking for 2+2.", + " The answer is 4.\n", + "4", + ] + assert _drive(s, deltas) == "4" + + def test_flush_recovers_final_answer_multiline_reasoning(self) -> None: + """Multi-line reasoning followed by the final answer. + + The recovery picks the LAST newline, so multi-line reasoning + prose is correctly stripped and only the final answer is + emitted. + """ + s = StreamingThinkScrubber() + deltas = [ + "Let me think about this.\n", + "2+2 is definitely 4.\n", + "I'm confident the answer is 4.\n", + "4", + ] + assert _drive(s, deltas) == "4" + + def test_flush_opt_out_recovers_unclosed_final_answer(self) -> None: + """Plugins can opt out of the recovery by setting + ``recover_unclosed_final_answer=False`` on the scrubber instance. + """ + s = StreamingThinkScrubber() + s.recover_unclosed_final_answer = False + deltas = ["reasoning\nfinal answer"] + assert _drive(s, deltas) == "" + class TestRealisticStreaming: """Character-by-character streaming must work as well as larger chunks."""