The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): check a streaming loop every tail window once the reply is long
kshitijk4poor48e3894d0e9a
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.pyindex 7bec6b7f1f4..7f544acb391 100644--- a/agent/repetition_guard.py+++ b/agent/repetition_guard.py@@ -166,7 +166,9 @@ class RunawayStreamWatch:A stream that keeps producing never reaches a completion check, and endpoints without anoutput cap (#127234) keep a looping model going for as long as the turn lives. The firstcheck runs at ``STOP_PATH_MIN_CHARS`` (asked-for repeats stay below it, as on the stop path)- and the next one each time the text doubles, so the total work stays linear in the output.+ and the gap doubles until it reaches one tail window, then stays there. A fixed stride keeps a+ loop that starts late in a long reply from streaming as long as the reply already was before+ a check sees it; each check reads only the tail, so the total work stays linear in the output."""__slots__ = ("_parts", "_held", "_chars", "_next_check")@@ -184,13 +186,12 @@ class RunawayStreamWatch:self._parts.append(text)self._held += len(text)self._chars += len(text)- # The gap between two checks doubles, so text held until the next check would grow- # with the reply. Trimming every tail's worth of new text keeps the cost linear.+ # Text held between checks is bounded by trimming every tail's worth of new text.if self._held >= 2 * _STREAM_TAIL_CHARS:self._trim()if self._chars < self._next_check:return False- self._next_check = 2 * self._chars+ self._next_check = self._chars + min(self._chars, _STREAM_TAIL_CHARS)return is_runaway_repetition(self._trim())def _trim(self) -> str:diff --git a/tests/agent/test_stream_runaway_repetition.py b/tests/agent/test_stream_runaway_repetition.pyindex 6702b8a35e4..01ea8692f0a 100644--- a/tests/agent/test_stream_runaway_repetition.py+++ b/tests/agent/test_stream_runaway_repetition.py@@ -12,6 +12,7 @@ The loops are the ones reported: a Telegram gateway cycle (#125650), the fullwidfrom __future__ import annotations+import hashlibimport jsonimport threadingimport time@@ -38,13 +39,17 @@ _DISTINCT_ROWS = "".join(f"| {i:05d} | status: pending review by the on-call engineer before the next release window |\n"for i in range(500))+assert len(_ASKED_FOR_REPEAT) < STOP_PATH_MIN_CHARS <= len(_DISTINCT_ROWS)+# ~100K of distinct legitimate text before a loop starts: the cut must not wait for the reply to double.+_LONG_PREFIX = "".join(hashlib.sha256(str(i).encode()).hexdigest() + "\n" for i in range(1540))+_LOOP_BUDGET = 100_000class _FakeEndpoint:"""Local endpoint streaming one reply per request, on the chat or the Anthropic wire."""- def __init__(self, channel: str, text: str, *, endless: bool) -> None:- self.channel, self.text, self.endless = channel, text, endless+ def __init__(self, channel: str, text: str, *, endless: bool, prefix: str = "") -> None:+ self.channel, self.text, self.endless, self.prefix = channel, text, endless, prefixself.requests = 0self._stop = threading.Event()endpoint = self@@ -88,8 +93,14 @@ class _FakeEndpoint:if not self.endless:yield from (self.text[i:i + 200] for i in range(0, len(self.text), 200))return+ yield from (self.prefix[i:i + 2000] for i in range(0, len(self.prefix), 2000))+ looped = 0while not self._stop.is_set():+ if self.prefix and looped >= _LOOP_BUDGET:+ self._stop.wait() # stall: a watch that has not cut by now hangs the turn+ returnyield self.text+ looped += len(self.text)time.sleep(0.001)def _chat_frames(self):@@ -142,8 +153,8 @@ def endpoint(monkeypatch):monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")started = []- def start(channel: str, text: str, *, endless: bool) -> _FakeEndpoint:- started.append(_FakeEndpoint(channel, text, endless=endless))+ def start(channel: str, text: str, *, endless: bool, prefix: str = "") -> _FakeEndpoint:+ started.append(_FakeEndpoint(channel, text, endless=endless, prefix=prefix))return started[-1]yield start@@ -179,17 +190,19 @@ def _run_turn(server: _FakeEndpoint, api_mode: str) -> dict:@pytest.mark.parametrize(- ("api_mode", "channel", "loop"),+ ("api_mode", "channel", "loop", "prefix"),[- ("chat_completions", "content", _CYCLE_125650),- ("chat_completions", _LOOP_BEHIND_DETAILS, _CYCLE_125650),- ("anthropic_messages", "content", _STATUS_LINE_78551),- ("anthropic_messages", "reasoning", _CYCLE_125650),+ ("chat_completions", "content", _CYCLE_125650, ""),+ ("chat_completions", _LOOP_BEHIND_DETAILS, _CYCLE_125650, ""),+ ("anthropic_messages", "content", _STATUS_LINE_78551, ""),+ ("anthropic_messages", "reasoning", _CYCLE_125650, ""),+ ("chat_completions", "content", _CYCLE_125650, _LONG_PREFIX),],- ids=["chat-content", "chat-reasoning-behind-details", "anthropic-text", "anthropic-thinking"],+ ids=["chat-content", "chat-reasoning-behind-details", "anthropic-text", "anthropic-thinking",+ "chat-loop-after-long-prefix"],)-def test_looping_stream_is_cut_without_a_stream_callback(endpoint, api_mode, channel, loop):- server = endpoint(channel, loop, endless=True)+def test_looping_stream_is_cut_without_a_stream_callback(endpoint, api_mode, channel, loop, prefix):+ server = endpoint(channel, loop, endless=True, prefix=prefix)result = _run_turn(server, api_mode)@@ -202,7 +215,6 @@ def test_looping_stream_is_cut_without_a_stream_callback(endpoint, api_mode, cha@pytest.mark.parametrize("text", [_ASKED_FOR_REPEAT, _DISTINCT_ROWS], ids=["asked-for-repeat", "distinct-rows"])def test_repetitive_but_legitimate_stream_is_delivered(endpoint, text):- assert (len(text) < STOP_PATH_MIN_CHARS) == (text is _ASKED_FOR_REPEAT)server = endpoint("content", text, endless=False)result = _run_turn(server, "chat_completions")diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.mdindex a82447719de..b24fe878504 100644--- a/website/docs/integrations/providers.md+++ b/website/docs/integrations/providers.md@@ -1270,8 +1270,8 @@ Hermes no longer reads `model.max_tokens`, `HERMES_MAX_TOKENS`, provider output-settings, or `model_overrides.*.*.max_output_tokens`. Remove these legacy settings.Custom OpenAI-compatible endpoints receive no automatic catalog-sized output cap.Their server defaults apply; these can be lower than the model maximum.-A reply that degenerates into a repetition loop is still stopped: once the looping text-(visible or reasoning) passes 16,000 characters while it streams, Hermes closes the stream+A reply that degenerates into a repetition loop is still stopped: within about 100,000+characters of the loop starting (visible or reasoning text), Hermes closes the streamand ends the turn with a "Repetition Detected" notice, so an uncapped endpoint cannot keep alooping model running.diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.mdindex 36942cc8bb4..659b6ae9454 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.md@@ -1090,7 +1090,7 @@ model::::note 两个设置,容易混淆**`context_length`** 是**总上下文窗口**——输入和输出 token 的合计预算(例如 Claude Opus 4.6 为 200,000)。Hermes 用它来决定何时压缩历史记录以及验证 API 请求。-**输出上限**限制单次响应,而非对话历史。Hermes 不再读取 `model.max_tokens`、`HERMES_MAX_TOKENS` 或提供商及模型的输出上限设置。兼容端点使用服务器默认值;该值不一定是模型最大值。回复在流式输出中陷入重复循环时仍会被停止:循环文本(可见内容或推理内容)超过 16,000 个字符后,Hermes 会关闭该流并以“Repetition Detected”提示结束本轮,因此没有输出上限的端点也不会让循环中的模型一直运行下去。原生 Anthropic Messages 仍要求 `max_tokens`,Hermes 会提供内部值。Bedrock Converse 的可选输出限制默认省略。+**输出上限**限制单次响应,而非对话历史。Hermes 不再读取 `model.max_tokens`、`HERMES_MAX_TOKENS` 或提供商及模型的输出上限设置。兼容端点使用服务器默认值;该值不一定是模型最大值。回复在流式输出中陷入重复循环时仍会被停止:循环(可见内容或推理内容)开始后约 100,000 个字符以内,Hermes 会关闭该流并以“Repetition Detected”提示结束本轮,因此没有输出上限的端点也不会让循环中的模型一直运行下去。原生 Anthropic Messages 仍要求 `max_tokens`,Hermes 会提供内部值。Bedrock Converse 的可选输出限制默认省略。当自动检测获取的窗口大小不正确时,设置 `context_length`。请删除旧的用户输出上限配置;内部任务预算与 MCP 采样安全预算保持不变。