The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): dedupe repeated stream continuation tails
fangliquanflq3814aab269be
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 442f1d8b8a5..bc0cc85b22c 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -257,10 +257,43 @@ def _moa_client_consumes_prepared_request(client: Any) -> bool:return callable(getattr(completions, "prepare", None))+_MIN_CONTINUATION_OVERLAP = 32+++def _continuation_overlap_length(previous: str, continuation: str) -> int:+ """Return the longest continuation prefix that repeats the previous suffix."""+ if len(previous) < _MIN_CONTINUATION_OVERLAP or len(continuation) < _MIN_CONTINUATION_OVERLAP:+ return 0++ prefix_lengths = [0] * len(continuation)+ matched = 0+ for index in range(1, len(continuation)):+ while matched and continuation[index] != continuation[matched]:+ matched = prefix_lengths[matched - 1]+ if continuation[index] == continuation[matched]:+ matched += 1+ prefix_lengths[index] = matched++ matched = 0+ last_index = len(previous) - 1+ for index, char in enumerate(previous):+ while matched and char != continuation[matched]:+ matched = prefix_lengths[matched - 1]+ if char == continuation[matched]:+ matched += 1+ if matched == len(continuation):+ if index == last_index:+ return matched+ matched = prefix_lengths[matched - 1]+ return matched if matched >= _MIN_CONTINUATION_OVERLAP else 0++def _join_truncated_parts(parts: List[str]) -> str:- """Join continuation fragments, adding a newline where two would glue together (#78577)."""+ """Join continuation fragments without repeating a recovered tail."""joined = ""for part in parts:+ if joined and part:+ part = part[_continuation_overlap_length(joined, part):]if joined and not joined[-1].isspace() and part and not part[0].isspace():joined += "\n"joined += partdiff --git a/tests/agent/test_partial_stream_finish_reason.py b/tests/agent/test_partial_stream_finish_reason.pyindex 05f9cc16676..e66255b24da 100644--- a/tests/agent/test_partial_stream_finish_reason.py+++ b/tests/agent/test_partial_stream_finish_reason.py@@ -21,6 +21,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom hermes_constants import PARTIAL_STREAM_STUB_ID, FINISH_REASON_LENGTH+from agent.conversation_loop import _join_truncated_parts# ── Helpers (mirrors test_streaming.py) ────────────────────────────────────@@ -357,6 +358,40 @@ class TestMixedToolCallsOneDroppedOneComplete:# ── Length-continuation prompt branching ──────────────────────────────────+class TestLengthContinuationAssembly:+ def test_repeated_complete_tail_is_not_joined_twice(self):+ conclusion = (+ "**Conclusion**: the project remains on standby until the stable "+ "release. Nothing changes."+ )++ joined = _join_truncated_parts([+ f"Investigation details.\n\n{conclusion}",+ conclusion,+ ])++ assert joined.count(conclusion) == 1++ def test_distinct_continuation_is_preserved(self):+ assert _join_truncated_parts([+ "The first half ends here",+ "and the second half adds new information.",+ ]) == (+ "The first half ends here\n"+ "and the second half adds new information."+ )++ def test_repeated_tail_is_trimmed_without_losing_new_text(self):+ repeated = "A sufficiently long repeated transition sentence ends here."++ assert _join_truncated_parts([+ f"Existing answer. {repeated}",+ f"{repeated} New inbound details remain visible.",+ ]) == (+ f"Existing answer. {repeated} New inbound details remain visible."+ )++# ── Integration: live conversation loop ───────────────────────────────────@@ -398,19 +433,26 @@ class TestConversationLoopPartialStreamContinuation:from tests.agent.test_run_agent import _mock_response, _mock_assistant_msg# First API call: the partial-stream stub (length on partial-stream-stub id).+ repeated_tail = (+ "**Conclusion**: the project remains on standby until the stable "+ "release. Nothing changes."+ )partial_stub = SimpleNamespace(id=PARTIAL_STREAM_STUB_ID,model="test/model",choices=[SimpleNamespace(index=0,- message=_mock_assistant_msg(content="The first half of "),+ message=_mock_assistant_msg(+ content=f"The first half of the answer is forty-two.\n\n{repeated_tail}"+ ),finish_reason=FINISH_REASON_LENGTH,)],usage=None,)- # Second API call: model continues with the rest, clean stop.+ # Second API call: the model restarts from the complete-looking tail+ # even though the nudge said not to repeat it, then stops cleanly.continuation = _mock_response(- content="the answer is forty-two.", finish_reason="stop",+ content=repeated_tail, finish_reason="stop",)loop_agent.client.chat.completions.create.side_effect = [@@ -447,6 +489,7 @@ class TestConversationLoopPartialStreamContinuation:# And the final response stitches both halves together.assert "first half of" in result["final_response"]assert "forty-two" in result["final_response"]+ assert result["final_response"].count(repeated_tail) == 1class TestContentFilterStallActivatesFallback: