Skip to content

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(swarm): retry transient team model calls

FrancesShaw007d9f56bc800ff
diff --git a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py
index 23942a2f2c..69883f1eef 100644
--- a/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/llm_retry_notify_rail.py
@@ -26,6 +26,14 @@ _TRANSIENT_MESSAGE_MARKERS = (
"read timeout",
"connect timeout",
)
+# Observed wrapper: agent-core OpenAIModelClient.stream() exception text.
+# Require all markers to avoid broadening retries to bare or unrelated 404s.
+# Wrapper wording drift disables this extra 404 rule; generic retry rules remain.
+_MEMBER_NETWORK_404_MARKERS = (
+ "async stream error",
+ "notfounderror",
+ "error code: 404",
+)
# Per-call budget lives on ctx.extra so concurrent call_llm/stream_llm that
# share one rail instance (SkillTurbo PPT page gather) cannot steal or reset
# each other's retry counts. Instance attrs are mirrored for observability only.
@@ -265,4 +273,15 @@ class NotifyingLLMRetryRail(LLMRetryRail):
)
-__all__ = ["NotifyingLLMRetryRail"]
+class TeamMemberNotifyingLLMRetryRail(NotifyingLLMRetryRail):
+ """Retry the observed async-stream 404 transport error only for team members."""
+
+ @classmethod
+ def _looks_like_transient_invoke(cls, exc: BaseException | None) -> bool:
+ if super()._looks_like_transient_invoke(exc):
+ return True
+ message = str(exc or "").lower()
+ return all(marker in message for marker in _MEMBER_NETWORK_404_MARKERS)
+
+
+__all__ = ["NotifyingLLMRetryRail", "TeamMemberNotifyingLLMRetryRail"]
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index fe1491f1df..e82fd34ffc 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -44,7 +44,6 @@ from jiuwenswarm.common.config import (
get_default_model_provider,
get_evolution_auto_save_enabled,
get_evolution_review_trigger_enabled,
- get_evolution_signal_trigger_enabled,
get_passive_skill_evolution_triggers,
get_skill_create_enabled,
resolve_string_or_list_config,
@@ -395,6 +394,25 @@ def _member_evolution_rail_params(config: dict[str, Any]) -> dict[str, Any]:
}
+def _llm_retry_params(config: dict[str, Any]) -> dict[str, Any]:
+ """Project adapter retry settings into the serializable member rail spec."""
+ guard = _config_section(config, "execution_guard")
+ retry = _config_section(guard, "llm_retry_rail")
+ params: dict[str, Any] = {
+ "max_retries": retry.get("max_retries", 2),
+ "repeat_min_pattern_chars": retry.get("repeat_min_pattern_chars", 2),
+ "repeat_max_pattern_chars": retry.get("repeat_max_pattern_chars", 64),
+ "repeat_min_count": retry.get("repeat_min_count", 6),
+ "repeat_min_total_chars": retry.get("repeat_min_total_chars", 160),
+ "repeat_window_chars": retry.get("repeat_window_chars", 1024),
+ "single_char_repeat_count": retry.get("single_char_repeat_count", 100),
+ "retry_transient_invoke_errors": retry.get("retry_transient_invoke_errors", True),
+ "notify_user_on_retry": retry.get("notify_user_on_retry", True),
+ "notify_user_on_exhausted": retry.get("notify_user_on_exhausted", True),
+ }
+ return params
+
+
# Per-element attribute params, keyed by provider name; empty for parameterless.
_RAIL_PARAM_BUILDERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
registry.DISABLED_TOOLS: lambda c: {
@@ -413,6 +431,7 @@ _RAIL_PARAM_BUILDERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
registry.TEAM_PERMISSION_POLICY: lambda c: {
"permissions_config": _config_section(c, "permissions"),
},
+ registry.TEAM_MEMBER_LLM_RETRY: _llm_retry_params,
registry.CODE_CODING_MEMORY: lambda c: {
"embed_config": _config_section(c, "embed")
},
@@ -458,6 +477,13 @@ def _tool_params(name: str, config: dict[str, Any]) -> dict[str, Any]:
return builder(config) if builder else {}
+def _llm_retry_enabled(config: dict[str, Any]) -> bool:
+ """Reuse the adapter's existing retry guard switch for team members."""
+ guard = _config_section(config, "execution_guard")
+ retry = _config_section(guard, "llm_retry_rail")
+ return retry.get("enabled", False) is True
+
+
def _team_common_rail_names(role: str) -> tuple[str, ...]:
"""Shared chat-team rails; leaders omit harness todo planning."""
if role == "leader":
@@ -515,6 +541,13 @@ def _build_team_capability_specs(
RailSpec(type=name, params=_rail_params(name, config))
for name in _team_common_rail_names(role)
]
+ if role in {"leader", "teammate"} and _llm_retry_enabled(config):
+ rails_specs.append(
+ RailSpec(
+ type=registry.TEAM_MEMBER_LLM_RETRY,
+ params=_rail_params(registry.TEAM_MEMBER_LLM_RETRY, config),
+ )
+ )
if role == "leader":
rails_specs.append(RailSpec(type=registry.STRUCTURED_ASK_USER))
@@ -599,6 +632,13 @@ def _build_code_capability_specs(
RailSpec(type=name, params=_rail_params(name, config))
for name in _code_base_rail_names(role)
]
+ if role in {"leader", "teammate"} and _llm_retry_enabled(config):
+ rails_specs.append(
+ RailSpec(
+ type=registry.TEAM_MEMBER_LLM_RETRY,
+ params=_rail_params(registry.TEAM_MEMBER_LLM_RETRY, config),
+ )
+ )
if is_team_plan_leader:
rails_specs.append(RailSpec(type=registry.TEAM_PLAN_APPROVAL))
diff --git a/jiuwenswarm/agents/swarm/providers/builtin_rails.py b/jiuwenswarm/agents/swarm/providers/builtin_rails.py
index 50a1fb22fc..440dda2381 100644
--- a/jiuwenswarm/agents/swarm/providers/builtin_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/builtin_rails.py
@@ -1,11 +1,10 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""No-factory class-rail declarations for swarm-owned team rails.
+"""Built-in rail declarations for swarm-owned team rails.
-These rails take no construction params (a bare ``cls()``), so they are declared
-with a class ``builder`` rather than a factory function. Only swarm-owned rail
-classes live here; the generic openjiuwen rails (``sys_operation`` /
-``task_planning`` / ``security`` / ``heartbeat`` / ...) are declared and
+Parameterless rails use a class ``builder``; parameterized rails use a factory
+function. Only swarm-owned rails live here; the generic openjiuwen rails
+(``sys_operation`` / ``task_planning`` / ``security`` / ``heartbeat`` / ...) are declared and
registered by openjiuwen itself and referenced by their bare names from
``config_specs``.
@@ -26,6 +25,9 @@ from openjiuwen.agent_teams.harness.manifest import (
)
from jiuwenswarm.agents.harness.common.rails.avatar_rail import AvatarPromptRail
+from jiuwenswarm.agents.harness.common.rails.llm_retry_notify_rail import (
+ TeamMemberNotifyingLLMRetryRail,
+)
from jiuwenswarm.agents.harness.common.rails.response_prompt_rail import (
ResponsePromptRail,
)
@@ -36,11 +38,12 @@ from jiuwenswarm.agents.harness.common.rails.workspace_quota_rail import (
WorkspaceQuotaRail,
)
-# No-parameter swarm-owned rail type names; namespaced under "swarm.".
+# Swarm-owned rail type names; namespaced under "swarm.".
RESPONSE_PROMPT = "swarm.response_prompt"
STREAM_EVENT = "swarm.stream_event"
AVATAR_PROMPT = "swarm.avatar_prompt"
WORKSPACE_QUOTA = "swarm.workspace_quota"
+TEAM_MEMBER_LLM_RETRY = "swarm.team_member_llm_retry"
class ResponsePromptInput(ConstructionInput):
@@ -87,9 +90,24 @@ harness_element(
builder=WorkspaceQuotaRail,
)
+
+@harness_element(
+ kind=ElementKind.RAIL,
+ name=TEAM_MEMBER_LLM_RETRY,
+ description="Retries transient model-call failures for team members with user notifications.",
+)
+def _build_team_member_llm_retry_rail(
+ params: dict[str, Any],
+ context: Any,
+) -> TeamMemberNotifyingLLMRetryRail:
+ del context
+ return TeamMemberNotifyingLLMRetryRail(**params)
+
+
__all__ = [
"RESPONSE_PROMPT",
"STREAM_EVENT",
"AVATAR_PROMPT",
"WORKSPACE_QUOTA",
+ "TEAM_MEMBER_LLM_RETRY",
]
diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.py
index 9e7dfdd27d..ac179ab67d 100644
--- a/jiuwenswarm/agents/swarm/registry.py
+++ b/jiuwenswarm/agents/swarm/registry.py
@@ -121,11 +121,12 @@ DEFAULT_STATUSLINE_SETUP_MAX_ITERATIONS = (
)
STATUSLINE_SETUP_AGENT = _code_subagents.STATUSLINE_SETUP_AGENT
-# Swarm-owned no-parameter class rails declared in ``builtin_rails``.
+# Swarm-owned rails declared in ``builtin_rails``.
RESPONSE_PROMPT = _builtin_rails.RESPONSE_PROMPT
STREAM_EVENT = _builtin_rails.STREAM_EVENT
AVATAR_PROMPT = _builtin_rails.AVATAR_PROMPT
WORKSPACE_QUOTA = _builtin_rails.WORKSPACE_QUOTA
+TEAM_MEMBER_LLM_RETRY = _builtin_rails.TEAM_MEMBER_LLM_RETRY
# Generic rails provided + registered by openjiuwen (referenced by bare name).
SYS_OPERATION = _OJ_SYS_OPERATION
@@ -218,6 +219,7 @@ __all__ = [
"SECURITY",
"HEARTBEAT",
"AVATAR_PROMPT",
+ "TEAM_MEMBER_LLM_RETRY",
"CODE_EXTRA_TOOLS",
"CODE_RUNTIME_PROMPT",
"CODE_LSP",
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index 30960cfa23..7346eae102 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -192,6 +192,8 @@ def test_team_a2a_live_session_does_not_borrow_build_identity():
# Sourced from the registry symbols so the test tracks renames automatically.
_TEAM_SHARED_RAIL_NAMES: frozenset[str] = frozenset(
{
+ registry.MODEL_ROUTING,
+ registry.WORKSPACE_QUOTA,
registry.RUNTIME_PROMPT,
registry.TEAM_SKILL_STORAGE_POLICY,
registry.TEAM_SHARED_SKILL_LINK_REFRESH,
@@ -525,7 +527,7 @@ def test_build_member_capability_specs_rail_names(
assert _TEAM_SHARED_RAIL_NAMES <= rail_names
assert extra_rails <= rail_names
- assert len(_TEAM_SHARED_RAIL_NAMES) == 19
+ assert len(_TEAM_SHARED_RAIL_NAMES) == 21
assert rail_names == expected
disabled_tools = next(
spec for spec in rails_specs if spec.type == registry.DISABLED_TOOLS
diff --git a/tests/agents/swarm/test_team_member_llm_retry.py b/tests/agents/swarm/test_team_member_llm_retry.py
new file mode 100644
index 0000000000..e8563338b6
--- /dev/null
+++ b/tests/agents/swarm/test_team_member_llm_retry.py
@@ -0,0 +1,217 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Team retry wiring, bounded stream-404 retries, and inherited worker specs."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from openjiuwen.agent_teams.schema.deep_agent_spec import DeepAgentSpec, RailSpec
+from openjiuwen.agent_teams.workflow.backends._member_spec import derive_member_spec
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ModelCallInputs
+
+from jiuwenswarm.agents.harness.common.rails import llm_retry_notify_rail
+from jiuwenswarm.agents.swarm import register_swarm_providers
+from jiuwenswarm.agents.swarm.config_specs import build_member_capability_specs
+from jiuwenswarm.agents.swarm.context import SwarmBuildContext
+
+
+_RETRY_PROVIDER = "swarm.team_member_llm_retry"
+_STREAM_404 = "openAI API async stream error: NotFoundError: Error code: 404"
+
+
+def _retry_spec(
+ settings: dict[str, Any], mode: str = "team", role: str = "teammate"
+) -> RailSpec:
+ config = {"execution_guard": {"llm_retry_rail": {"enabled": True, **settings}}}
+ rails, _ = build_member_capability_specs(config, mode, role)
+ retries = [spec for spec in rails if spec.type == _RETRY_PROVIDER]
+ assert len(retries) == 1, "Team member must mount exactly one configured retry rail"
+ return retries[0]
+
+
+def _build_rail(settings: dict[str, Any]):
+ register_swarm_providers()
+ return _retry_spec(settings).build(
+ language="cn", context=SwarmBuildContext(session_id="s1", mode="team")
+ )
+
+
+def _ctx(message: str = _STREAM_404) -> AgentCallbackContext:
+ return AgentCallbackContext(
+ agent=None,
+ inputs=ModelCallInputs(messages=[], tools=None, model_context=None),
+ exception=RuntimeError(message),
+ )
+
+
[email protected]("mode", ["team", "code.team", "team.plan"])
[email protected]("role", ["leader", "teammate"])
+def test_retry_rail_is_mounted_once_for_each_team_profile(mode: str, role: str) -> None:
+ _retry_spec({}, mode, role)
+
+
+ "config",
+ [{}, {"execution_guard": {}}, {"execution_guard": {"llm_retry_rail": {"enabled": False}}}],
+)
+def test_retry_provider_requires_existing_guard_switch(config: dict[str, Any]) -> None:
+ rails, _ = build_member_capability_specs(config, "team", "teammate")
+ assert _RETRY_PROVIDER not in {spec.type for spec in rails}
+
+
+ ("message", "expected"),
+ [
+ (_STREAM_404, True),
+ (_STREAM_404.upper(), True),
+ ("Connection error", True),
+ ("NotFoundError: Error code: 404", False),
+ ("openAI API async stream error: Error code: 404", False),
+ ("openAI API async stream error: AuthenticationError: 401", False),
+ ],
+)
+async def test_only_observed_stream_404_and_transient_errors_request_retry(
+ message: str, expected: bool
+) -> None:
+ rail = _build_rail({"notify_user_on_retry": False})
+ ctx = _ctx(message)
+
+ await rail.on_model_exception(ctx)
+
+ assert (ctx.consume_retry_request() is not None) is expected
+ assert not llm_retry_notify_rail.NotifyingLLMRetryRail._looks_like_transient_invoke(
+ RuntimeError(_STREAM_404)
+ )
+
+
+async def test_configured_retry_budget_and_detection_settings_are_preserved(monkeypatch) -> None:
+ monkeypatch.setattr(llm_retry_notify_rail.random, "uniform", lambda *_: 1.0)
+ rail = _build_rail(
+ {
+ "max_retries": 3,
+ "repeat_min_pattern_chars": 3,
+ "repeat_max_pattern_chars": 32,
+ "repeat_min_count": 4,
+ "repeat_min_total_chars": 80,
+ "repeat_window_chars": 512,
+ "single_char_repeat_count": 90,
+ "notify_user_on_retry": False,
+ "notify_user_on_exhausted": False,
+ }
+ )
+ ctx = _ctx()
+ delays = []
+
+ for _ in range(4):
+ await rail.on_model_exception(ctx)
+ request = ctx.consume_retry_request()
+ if request is not None:
+ delays.append(request.delay_seconds)
+
+ assert delays == [5.0, 10.0, 20.0]
+ assert rail.repeat_min_pattern_chars == 3
+ assert rail.repeat_max_pattern_chars == 32
+ assert rail.repeat_min_count == 4
+ assert rail.repeat_min_total_chars == 80
+ assert rail.repeat_window_chars == 512
+ assert rail.single_char_repeat_count == 90
+
+
+async def test_transient_retry_can_be_disabled_for_team_stream_404() -> None:
+ rail = _build_rail({"retry_transient_invoke_errors": False})
+ ctx = _ctx()
+
+ await rail.on_model_exception(ctx)
+
+ assert ctx.consume_retry_request() is None
+
+
[email protected]("notify", [True, False])
+async def test_retry_and_exhaustion_notifications_respect_config(notify: bool) -> None:
+ rail = _build_rail(
+ {
+ "max_retries": 1,
+ "notify_user_on_retry": notify,
+ "notify_user_on_exhausted": notify,
+ }
+ )
+ events = []
+
+ async def write_stream(event):
+ events.append(event)
+
+ ctx = _ctx()
+ ctx.session = SimpleNamespace(write_stream=write_stream)
+
+ await rail.on_model_exception(ctx)
+ assert ctx.consume_retry_request() is not None
+ await rail.on_model_exception(ctx)
+ assert ctx.consume_retry_request() is None
+
+ assert [event.type for event in events] == (["retry_notification", "error"] if notify else [])
+ if notify:
+ assert events[0].payload["attempt"] == 1
+ assert events[0].payload["max_attempts"] == 1
+ assert events[1].payload["error_type"] == "llm_retry_exhausted"
+
+
+async def test_team_retry_keeps_per_context_budgets() -> None:
+ rail = _build_rail(
+ {"max_retries": 1, "notify_user_on_exhausted": False}
+ )
+ first, second = _ctx(), _ctx()
+ await rail.before_invoke(first)
+ await rail.on_model_exception(first)
+ assert first.consume_retry_request() is not None
+
+ await rail.before_invoke(second)
+ await rail.on_model_exception(first)
+ assert first.consume_retry_request() is None
+ await rail.on_model_exception(second)
+ assert second.consume_retry_request() is not None
+
+
[email protected]("settings", [{}, {"backoff_seconds": [0.0, 0.25]}])
+async def test_team_retry_keeps_current_default_exponential_backoff(settings, monkeypatch) -> None:
+ monkeypatch.setattr(llm_retry_notify_rail.random, "uniform", lambda *_: 1.0)
+ rail = _build_rail(settings)
+ ctx = _ctx()
+ delays = []
+
+ for _ in range(2):
+ await rail.on_model_exception(ctx)
+ request = ctx.consume_retry_request()
+ assert request is not None
+ delays.append(request.delay_seconds)
+
+ assert delays == [5.0, 10.0]
+
+
+async def test_swarmflow_worker_keeps_retry_settings_after_serialization(monkeypatch) -> None:
+ monkeypatch.setattr(llm_retry_notify_rail.random, "uniform", lambda *_: 1.0)
+ base = DeepAgentSpec(rails=[_retry_spec({"max_retries": 1})])
+ worker = derive_member_spec(
+ base, team_name="team", member_name="worker-1", system_prompt="worker", model=None
+ )
+ restored = DeepAgentSpec.model_validate_json(worker.model_dump_json())
+ register_swarm_providers()
+ rail = restored.rails[0].build(language="cn", context=SwarmBuildContext(mode="team"))
+ ctx = _ctx()
+
+ await rail.on_model_exception(ctx)
+ request = ctx.consume_retry_request()
+ assert request is not None
+ assert request.delay_seconds == 5.0
+ await rail.on_model_exception(ctx)
+ assert ctx.consume_retry_request() is None