Skip to content

Agent Zero AI framework

Make error retry count configurable

Alessandrocf51c792f51c
diff --git a/plugins/_error_retry/README.md b/plugins/_error_retry/README.md
index 90dffb56f..b2cf4caff 100644
--- a/plugins/_error_retry/README.md
+++ b/plugins/_error_retry/README.md
@@ -1,10 +1,10 @@
# Error Retry
-Retry once after an unexpected critical exception so the agent has a chance to recover instead of failing immediately.
+Retry after an unexpected critical exception so the agent has a chance to recover instead of failing immediately.
## What It Does
-This plugin hooks into the agent lifecycle and automatically retries the current loop once when an unhandled critical exception occurs.
+This plugin hooks into the agent lifecycle and automatically retries the current loop when an unhandled critical exception occurs.
It does **not** retry exceptions that are already treated as controlled agent flow, such as:
@@ -16,9 +16,9 @@ It does **not** retry exceptions that are already treated as controlled agent fl
- **Counter reset per monologue**
- Clears the retry counter at the start of a new monologue.
- **Critical exception retry**
- - On an unexpected exception, logs a warning, waits briefly, injects an agent-facing critical error message into history, and suppresses the original exception once.
-- **Single retry only**
- - Uses an internal counter so the retry happens at most one time per monologue.
+ - On an unexpected exception, logs a warning, waits briefly, injects an agent-facing critical error message into history, and suppresses the original exception while retries remain.
+- **Configurable retry count**
+ - Uses the plugin's `retries` setting to control how many times recovery is attempted per monologue. The default is `1`.
## Key Files
diff --git a/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py b/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py
index 91c2ca344..e920d29a7 100644
--- a/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py
+++ b/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py
@@ -10,6 +10,20 @@ from helpers.print_style import PrintStyle
from plugins._error_retry.extensions.python._functions.agent.Agent.monologue.start._10_reset_critical_exception_counter import DATA_NAME_COUNTER
+DEFAULT_MAX_RETRIES = 1
+RETRY_DELAY_SECONDS = 3
+
+
+def normalize_max_retries(value, default: int = DEFAULT_MAX_RETRIES) -> int:
+ if value is None or isinstance(value, bool):
+ return default
+
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return default
+
+
class RetryCriticalException(Extension):
async def execute(self, data: dict = {}, **kwargs):
if not self.agent:
@@ -24,8 +38,8 @@ class RetryCriticalException(Extension):
self.agent.set_data(DATA_NAME_COUNTER, 0) # reset counter if exception has been handled
return
- max_retries = 1
- delay = 3
+ cfg = plugins.get_plugin_config("_error_retry", agent=self.agent) or {}
+ max_retries = normalize_max_retries(cfg.get("retries"))
counter = self.agent.get_data(DATA_NAME_COUNTER) or 0
if counter >= max_retries:
@@ -46,7 +60,7 @@ class RetryCriticalException(Extension):
PrintStyle(font_color="orange", padding=True).print(
"Critical error occurred, retrying..."
)
- await asyncio.sleep(delay)
+ await asyncio.sleep(RETRY_DELAY_SECONDS)
await self.agent.handle_intervention()
agent_facing_error = self.agent.read_prompt(
"fw.msg_critical_error.md", error_message=error_message
@@ -89,4 +103,4 @@ class RetryCriticalException(Extension):
)
PrintStyle(font_color="orange", padding=True).print(
f"Cleared {removed} embedded media messages from history after persistent LiteLLM bad request."
- )
\ No newline at end of file
+ )
diff --git a/plugins/_error_retry/webui/config.html b/plugins/_error_retry/webui/config.html
index 662e4aff4..c7dabf4cb 100644
--- a/plugins/_error_retry/webui/config.html
+++ b/plugins/_error_retry/webui/config.html
@@ -20,7 +20,8 @@
</div>
</div>
<div class="field-control">
- <input type="number" min="0"
+ <input type="number" min="0" step="1"
+ x-init="if (config.retries === undefined || config.retries === null) config.retries = 1"
x-model.number="config.retries" />
</div>
</div>
diff --git a/tests/test_error_retry_plugin.py b/tests/test_error_retry_plugin.py
new file mode 100644
index 000000000..331c7044e
--- /dev/null
+++ b/tests/test_error_retry_plugin.py
@@ -0,0 +1,122 @@
+import asyncio
+import importlib
+import sys
+import types
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+if str(PROJECT_ROOT) not in sys.path:
+ sys.path.insert(0, str(PROJECT_ROOT))
+
+agent_stub = types.ModuleType("agent")
+agent_stub.LoopData = object
+original_agent_module = sys.modules.get("agent")
+sys.modules["agent"] = agent_stub
+
+try:
+ retry_module = importlib.import_module(
+ "plugins._error_retry.extensions.python._functions.agent.Agent."
+ "handle_exception.end._80_retry_critical_exception"
+ )
+ counter_module = importlib.import_module(
+ "plugins._error_retry.extensions.python._functions.agent.Agent."
+ "monologue.start._10_reset_critical_exception_counter"
+ )
+finally:
+ if original_agent_module is None:
+ sys.modules.pop("agent", None)
+ else:
+ sys.modules["agent"] = original_agent_module
+
+DATA_NAME_COUNTER = counter_module.DATA_NAME_COUNTER
+
+
+class FakeLog:
+ def __init__(self):
+ self.entries = []
+
+ def log(self, **entry):
+ self.entries.append(entry)
+
+
+class FakeAgent:
+ def __init__(self, counter=0):
+ self._data = {DATA_NAME_COUNTER: counter}
+ self.context = SimpleNamespace(log=FakeLog())
+ self.history = SimpleNamespace(remove_all_embeds=lambda: 0)
+ self.interventions = 0
+ self.warnings = []
+
+ def get_data(self, key):
+ return self._data.get(key)
+
+ def set_data(self, key, value):
+ self._data[key] = value
+
+ async def handle_intervention(self):
+ self.interventions += 1
+
+ def read_prompt(self, prompt, **kwargs):
+ return f"{prompt}: {kwargs['error_message']}"
+
+ def hist_add_warning(self, **warning):
+ self.warnings.append(warning)
+
+
+async def _no_sleep(_delay):
+ return None
+
+
+def _set_retry_config(monkeypatch, retries):
+ monkeypatch.setattr(
+ retry_module.plugins,
+ "get_plugin_config",
+ lambda *args, **kwargs: {"retries": retries},
+ )
+ monkeypatch.setattr(retry_module.asyncio, "sleep", _no_sleep)
+
+
+ ("value", "expected"),
+ [
+ (None, 1),
+ ("", 1),
+ (False, 1),
+ ("3", 3),
+ (2.9, 2),
+ (-4, 0),
+ ],
+)
+def test_normalize_max_retries(value, expected):
+ assert retry_module.normalize_max_retries(value) == expected
+
+
+def test_error_retry_uses_configured_retry_limit(monkeypatch):
+ _set_retry_config(monkeypatch, 2)
+ agent = FakeAgent(counter=1)
+ data = {"exception": RuntimeError("boom")}
+
+ asyncio.run(retry_module.RetryCriticalException(agent=agent).execute(data))
+
+ assert agent.get_data(DATA_NAME_COUNTER) == 2
+ assert data["exception"] is None
+ assert agent.interventions == 1
+ assert len(agent.context.log.entries) == 1
+ assert len(agent.warnings) == 1
+
+
+def test_zero_configured_retries_disables_retry(monkeypatch):
+ _set_retry_config(monkeypatch, 0)
+ agent = FakeAgent(counter=0)
+ exception = RuntimeError("boom")
+ data = {"exception": exception}
+
+ asyncio.run(retry_module.RetryCriticalException(agent=agent).execute(data))
+
+ assert agent.get_data(DATA_NAME_COUNTER) == 0
+ assert data["exception"] is exception
+ assert agent.interventions == 0
+ assert agent.context.log.entries == []