JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:增加重试通知输出
Chenchong_RD16752f1cfd33
diff --git a/jiuwenswarm/agents/harness/common/rails/__init__.py b/jiuwenswarm/agents/harness/common/rails/__init__.pyindex 1e6599c84b..60d77d1d2d 100644--- a/jiuwenswarm/agents/harness/common/rails/__init__.py+++ b/jiuwenswarm/agents/harness/common/rails/__init__.py@@ -24,6 +24,7 @@ from jiuwenswarm.agents.harness.common.rails.multimodal_image_rail import Multimfrom jiuwenswarm.agents.harness.common.rails.stream_event_rail import JiuSwarmStreamEventRailfrom jiuwenswarm.agents.harness.common.rails.task_execution_rail import TaskExecutionRailfrom jiuwenswarm.agents.harness.common.rails.context_overflow_recovery_rail import ContextOverflowRecoveryRail+from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import NotifyingLLMRetryRailfrom jiuwenswarm.agents.harness.common.rails.deepresearch_execution_rail import (DeepResearchExecutionRail,)@@ -41,6 +42,7 @@ __all__ = ["MemberSkillToolkitRail","StructuredAskUserRail","ContextOverflowRecoveryRail",+ "NotifyingLLMRetryRail","DeepResearchExecutionRail","DisabledToolsRail",]diff --git a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.pynew file mode 100644index 0000000000..3d5d1bfca7--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py@@ -0,0 +1,197 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Host-side LLM retry rail that surfaces retry progress to the user stream."""++from __future__ import annotations++import inspect+from typing import Any++from openjiuwen.core.common.logging import logger+from openjiuwen.core.session.stream import OutputSchema+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.llm_retry_rail import LLMRetryRail++_REASON_LABELS: dict[str, str] = {+ "repeat": "重复输出",+ "stream_timeout": "流式超时",+ "transient_invoke": "连接/超时",+}+_TRANSIENT_MESSAGE_MARKERS = (+ "connection error",+ "connection reset",+ "connection refused",+ "request timed out",+ "read timeout",+ "connect timeout",+)+++def _parent_accepts_retry_transient_invoke_errors() -> bool:+ return "retry_transient_invoke_errors" in inspect.signature(LLMRetryRail.__init__).parameters+++class NotifyingLLMRetryRail(LLMRetryRail):+ """Extend :class:`LLMRetryRail` with jiuwenswarm user-visible retry notifications."""++ def __init__(+ self,+ *,+ notify_user_on_retry: bool = True,+ notify_user_on_exhausted: bool = True,+ retry_transient_invoke_errors: bool = True,+ **kwargs: Any,+ ) -> None:+ self.notify_user_on_retry = notify_user_on_retry+ self.notify_user_on_exhausted = notify_user_on_exhausted+ self.retry_transient_invoke_errors = retry_transient_invoke_errors+ self._parent_supports_transient_invoke = _parent_accepts_retry_transient_invoke_errors()++ parent_kwargs = dict(kwargs)+ if self._parent_supports_transient_invoke:+ parent_kwargs["retry_transient_invoke_errors"] = retry_transient_invoke_errors+ super().__init__(**parent_kwargs)++ if not hasattr(self, "transient_invoke_retry_count"):+ self.transient_invoke_retry_count = 0++ @classmethod+ def _looks_like_transient_invoke(cls, exc: BaseException | None) -> bool:+ checker = getattr(LLMRetryRail, "_is_transient_invoke_exception", None)+ if callable(checker):+ return bool(checker(exc))+ message = str(exc or "").lower()+ for marker in _TRANSIENT_MESSAGE_MARKERS:+ if marker in message:+ return True+ return False++ async def on_model_exception(self, ctx: AgentCallbackContext) -> None:+ reason: str | None = None+ if self._is_repeat_exception(ctx.exception):+ reason = "repeat"+ elif self._is_stream_timeout_exception(ctx.exception):+ reason = "stream_timeout"+ elif self.retry_transient_invoke_errors and self._looks_like_transient_invoke(+ ctx.exception+ ):+ reason = "transient_invoke"+ if reason is None:+ return++ will_retry, attempt, max_attempts, delay = self._peek_retry(reason)+ if will_retry and self.notify_user_on_retry:+ await self._emit_retry_notification(ctx, reason, attempt, max_attempts, delay)+ elif not will_retry and self.notify_user_on_exhausted:+ await self._emit_retry_exhausted(ctx, reason, ctx.exception)++ self._request_retry_or_reset(ctx, reason)++ def _request_retry_or_reset(self, ctx: AgentCallbackContext, reason: str) -> None:+ if reason == "transient_invoke" and not self._parent_supports_transient_invoke:+ if self.transient_invoke_retry_count < self.max_retries:+ delay = self.backoff_delay(self.transient_invoke_retry_count)+ self.transient_invoke_retry_count += 1+ logger.warning(+ "[NotifyingLLMRetryRail] retrying model call after transient invoke error "+ f"({self.transient_invoke_retry_count}/{self.max_retries}) after {delay:.2f}s backoff: "+ f"{ctx.exception!r}"+ )+ ctx.request_retry(delay_seconds=delay)+ else:+ self.transient_invoke_retry_count = 0+ return+ super()._request_retry_or_reset(ctx, reason)++ def _peek_retry(self, reason: str) -> tuple[bool, int, int, float]:+ """Return ``(will_retry, attempt_number, max_attempts, delay_seconds)``."""+ if reason == "repeat":+ count = self.repeat_retry_count+ if count < self.max_retries:+ return True, count + 1, self.max_retries, self.backoff_delay(count)+ return False, count, self.max_retries, 0.0++ if reason == "transient_invoke":+ count = self.transient_invoke_retry_count+ if count < self.max_retries:+ return True, count + 1, self.max_retries, self.backoff_delay(count)+ return False, count, self.max_retries, 0.0++ count = self.stream_timeout_retry_count+ if count < self.max_retries:+ return True, count + 1, self.max_retries, self.backoff_delay(count)+ return False, count, self.max_retries, 0.0++ @staticmethod+ async def _emit_retry_notification(+ ctx: AgentCallbackContext,+ reason: str,+ attempt: int,+ max_attempts: int,+ delay: float,+ ) -> None:+ session = ctx.session+ if session is None or not hasattr(session, "write_stream"):+ return++ label = _REASON_LABELS.get(reason, reason)+ message = (+ f"\n\n⚠️ 模型调用异常 [{label}],"+ f"将在 {delay:.1f} 秒后进行第 {attempt}/{max_attempts} 次重试..."+ )+ try:+ await session.write_stream(+ OutputSchema(+ type="retry_notification",+ index=999,+ payload={+ "output": {+ "output": message,+ "result_type": "text",+ },+ "reason": reason,+ "attempt": attempt,+ "max_attempts": max_attempts,+ "delay_seconds": delay,+ },+ )+ )+ except Exception as exc:+ logger.warning(+ "[NotifyingLLMRetryRail] retry notification failed: %s",+ exc,+ )++ @staticmethod+ async def _emit_retry_exhausted(+ ctx: AgentCallbackContext,+ reason: str,+ exc: BaseException | None,+ ) -> None:+ session = ctx.session+ if session is None or not hasattr(session, "write_stream"):+ return++ label = _REASON_LABELS.get(reason, reason)+ detail = str(exc) if exc is not None else "unknown error"+ message = f"模型调用失败 [{label}],已用尽自动重试:{detail}"+ try:+ await session.write_stream(+ OutputSchema(+ type="error",+ index=999,+ payload={+ "error": message,+ "error_type": "llm_retry_exhausted",+ "reason": reason,+ },+ )+ )+ except Exception as write_exc:+ logger.warning(+ "[NotifyingLLMRetryRail] retry exhaustion notification failed: %s",+ write_exc,+ )+++__all__ = ["NotifyingLLMRetryRail"]diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex d37de1a7ca..1184d4034c 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -815,12 +815,18 @@ heartbeat:end: 22:00execution_guard:- # LLM 重试护栏:处理模型重复输出和流式帧超时,命中后重新发起模型请求+ # LLM 重试护栏:处理模型重复输出、流式帧超时,以及非流式 invoke 的瞬时网络/超时错误llm_retry_rail:# 总开关。关闭后不注册 LLMRetryRail,也不会额外拦截重复输出/流式帧超时enabled: true# 单次 invoke 内同一类异常最多重试次数;超过后把异常继续抛给上层max_retries: 2+ # 非流式 invoke 遇到 Connection error / Request timed out 等瞬时错误时是否自动重试+ retry_transient_invoke_errors: true+ # 重试进行中是否向前端推送可见提示(映射为 chat.delta)+ notify_user_on_retry: true+ # 重试用尽后是否向前端推送 chat.error,避免静默结束+ notify_user_on_exhausted: true# 重复片段检测的最短长度,单位:字符;用于检测短句/短片段循环输出repeat_min_pattern_chars: 2# 重复片段检测的最长长度,单位:字符;过长片段不作为循环模式检测diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex f8d5030b29..ed35f71d1e 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -210,6 +210,7 @@ from jiuwenswarm.agents.harness.common.tools.todo_compat import ()from jiuwenswarm.common.openjiuwen_rail_compat import install_evolution_rail_kwargs_compatfrom jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_prompt+from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import NotifyingLLMRetryRailfrom jiuwenswarm.agents.harness.common.rails import (DeepResearchExecutionRail,JiuSwarmStreamEventRail,@@ -6784,7 +6785,7 @@ class JiuWenSwarmDeepAdapter:return None@staticmethod- def _build_llm_retry_rail(config_base: dict[str, Any] | None = None) -> LLMRetryRail | None:+ def _build_llm_retry_rail(config_base: dict[str, Any] | None = None) -> NotifyingLLMRetryRail | None:try:config_base = config_base or get_config()guard_cfg = config_base.get("execution_guard", {}) if isinstance(config_base, dict) else {}@@ -6792,7 +6793,7 @@ class JiuWenSwarmDeepAdapter:if retry_cfg.get("enabled", False) is not True:logger.info("[JiuWenSwarmDeepAdapter] LLMRetryRail disabled by config")return None- rail = LLMRetryRail(+ rail = NotifyingLLMRetryRail(max_retries=retry_cfg.get("max_retries", 2),repeat_min_pattern_chars=retry_cfg.get("repeat_min_pattern_chars", 2),repeat_max_pattern_chars=retry_cfg.get("repeat_max_pattern_chars", 64),@@ -6800,8 +6801,11 @@ class JiuWenSwarmDeepAdapter:repeat_min_total_chars=retry_cfg.get("repeat_min_total_chars", 160),repeat_window_chars=retry_cfg.get("repeat_window_chars", 1024),single_char_repeat_count=retry_cfg.get("single_char_repeat_count", 100),+ retry_transient_invoke_errors=retry_cfg.get("retry_transient_invoke_errors", True),+ notify_user_on_retry=retry_cfg.get("notify_user_on_retry", True),+ notify_user_on_exhausted=retry_cfg.get("notify_user_on_exhausted", True),)- logger.info("[JiuWenSwarmDeepAdapter] LLMRetryRail create success")+ logger.info("[JiuWenSwarmDeepAdapter] NotifyingLLMRetryRail create success")return railexcept Exception as exc:logger.warning("[JiuWenSwarmDeepAdapter] LLMRetryRail create failed: %s", exc)@@ -15343,6 +15347,7 @@ class JiuWenSwarmDeepAdapter:))run_failure: tuple[str, str] | None = None+ emitted_chat_error = False# HITL 暂停标志:本轮有 ask_user 卡片发出时置位,收尾据此发# chat.invocation_paused 终结帧(而非普通完成帧),避免前端把"等待用户# 输入"误判为"任务完成"。镜像 vendor(clowder-ai) 的 _detect_hitl_pause。@@ -15438,6 +15443,8 @@ class JiuWenSwarmDeepAdapter:accumulated_reasoning = ""if parsed.get("event_type") == "chat.final":self._stream_content_run_kind = None+ if parsed.get("event_type") == "chat.error":+ emitted_chat_error = Trueyield AgentResponseChunk(request_id=rid,channel_id=cid,@@ -15578,6 +15585,8 @@ class JiuWenSwarmDeepAdapter:hitl_pending_stream = Trueif parsed.get("event_type") == "chat.final":self._stream_content_run_kind = None+ if parsed.get("event_type") == "chat.error":+ emitted_chat_error = Trueyield AgentResponseChunk(request_id=rid,channel_id=cid,@@ -15597,6 +15606,8 @@ class JiuWenSwarmDeepAdapter:hitl_pending_stream = Trueif parsed.get("event_type") == "chat.final":self._stream_content_run_kind = None+ if parsed.get("event_type") == "chat.error":+ emitted_chat_error = Trueyield AgentResponseChunk(request_id=rid,channel_id=cid,@@ -15633,6 +15644,8 @@ class JiuWenSwarmDeepAdapter:hitl_pending_stream = Trueif parsed.get("event_type") == "chat.final":self._stream_content_run_kind = None+ if parsed.get("event_type") == "chat.error":+ emitted_chat_error = Trueyield AgentResponseChunk(request_id=rid,channel_id=cid,@@ -15643,6 +15656,20 @@ class JiuWenSwarmDeepAdapter:suppress_stream_after_hitl = Truecontinue+ if run_failure is not None and not emitted_chat_error:+ error_type, error_message = run_failure+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=note_chat_payload({+ "event_type": "chat.error",+ "error": error_message,+ "error_type": error_type,+ }),+ is_complete=False,+ )+ emitted_chat_error = True+if accumulated_text and not hitl_pending_stream:# Same rule as _adapt_goal_intermediate_final: demote host# flush only when the flushed text belonged to a goal round.@@ -16181,6 +16208,18 @@ class JiuWenSwarmDeepAdapter:)return {"event_type": "chat.error", "error": error_msg}+ if chunk_type == "retry_notification":+ if isinstance(payload, dict):+ output = payload.get("output", {})+ content = output.get("output", "") if isinstance(output, dict) else str(output)+ else:+ content = str(payload)+ return {+ "event_type": "chat.delta",+ "content": content,+ "source_chunk_type": chunk_type,+ }+if chunk_type == "security.alert":if isinstance(payload, dict):return {diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.pyindex 5136a6b4e6..9063d4248f 100644--- a/jiuwenswarm/server/utils/stream_utils.py+++ b/jiuwenswarm/server/utils/stream_utils.py@@ -406,6 +406,18 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any)return {"event_type": "chat.error", "error": error_msg}+ if chunk_type == "retry_notification":+ if isinstance(payload, dict):+ output = payload.get("output", {})+ content = output.get("output", "") if isinstance(output, dict) else str(output)+ else:+ content = str(payload)+ return {+ "event_type": "chat.delta",+ "content": content,+ "source_chunk_type": chunk_type,+ }+if chunk_type in ("thinking", "llm_toolcall_progress"):# `thinking`: model 处理中(既有)。# `llm_toolcall_progress`: tool_call 长流式期间 react_agent 节流发的心跳