Agent Zero AI framework
Stop runaway unusable response loops
Alessandrod33cac3bf36c
diff --git a/extensions/python/_functions/AGENTS.md b/extensions/python/_functions/AGENTS.mdindex 4a7331962..db75fd4af 100644--- a/extensions/python/_functions/AGENTS.md+++ b/extensions/python/_functions/AGENTS.md@@ -16,6 +16,7 @@- Extension functions must match the implicit hook's supplied arguments.- Preserve ordering prefixes where exception handling, watchdog registration, or cleanup depends on them.- Hooks that mirror persisted AI responses into UI logs must reuse existing stream log items and avoid duplicating live response-tool logs.+- Recovery-loop circuit breakers must stop at the General Settings limit and render their user-visible cost warning from a core framework prompt.## Work Guidancediff --git a/extensions/python/_functions/agent/Agent/hist_add_warning/end/_90_stop_unusable_response_loop.py b/extensions/python/_functions/agent/Agent/hist_add_warning/end/_90_stop_unusable_response_loop.pynew file mode 100644index 000000000..2c44a910c--- /dev/null+++ b/extensions/python/_functions/agent/Agent/hist_add_warning/end/_90_stop_unusable_response_loop.py@@ -0,0 +1,55 @@+from helpers.errors import HandledException+from helpers.extension import Extension+from helpers.settings import get_settings+++STATE_KEY = "_unusable_response_failures"+++class StopUnusableResponseLoop(Extension):+ def execute(self, data: dict | None = None, **kwargs):+ if not self.agent or not isinstance(data, dict):+ return++ call_kwargs = data.get("kwargs")+ message = call_kwargs.get("message") if isinstance(call_kwargs, dict) else None+ call_args = data.get("args")+ if message is None and isinstance(call_args, tuple) and len(call_args) > 1:+ message = call_args[1]++ if not isinstance(message, str):+ return+ if message not in {+ self.agent.read_prompt("fw.msg_misformat.md"),+ self.agent.read_prompt("fw.msg_repeat.md"),+ }:+ return++ loop_data = getattr(self.agent, "loop_data", None)+ state = getattr(loop_data, "params_persistent", None)+ iteration = getattr(loop_data, "iteration", None)+ if not isinstance(state, dict) or not isinstance(iteration, int):+ return++ previous = state.get(STATE_KEY, {})+ if not isinstance(previous, dict):+ previous = {}+ previous_iteration = previous.get("iteration")+ if previous_iteration == iteration:+ return++ count = (+ previous.get("count", 0) + 1+ if previous_iteration == iteration - 1+ else 1+ )+ state[STATE_KEY] = {"iteration": iteration, "count": count}+ limit = get_settings()["max_consecutive_unusable_responses"]+ if count < limit:+ return++ stop_message = self.agent.read_prompt(+ "fw.msg_unusable_response_limit.md", limit=limit+ )+ self.agent.context.log.log(type="warning", content=stop_message)+ data["exception"] = HandledException(stop_message)diff --git a/helpers/settings.py b/helpers/settings.pyindex 35b3f7beb..8e191441a 100644--- a/helpers/settings.py+++ b/helpers/settings.py@@ -56,6 +56,7 @@ class Settings(TypedDict):agent_profile: stragent_knowledge_subdir: str+ max_consecutive_unusable_responses: inttimezone: strtime_format: str@@ -401,6 +402,9 @@ def normalize_settings(settings: Settings) -> Settings:# mcp server token is set automaticallycopy["mcp_server_token"] = create_auth_token()+ copy["max_consecutive_unusable_responses"] = max(+ 1, copy["max_consecutive_unusable_responses"]+ )copy["timezone"] = _normalize_timezone_setting(copy.get("timezone"), default["timezone"])copy["time_format"] = _normalize_time_format(copy.get("time_format"), default["time_format"])@@ -498,6 +502,9 @@ def get_default_settings() -> Settings:root_password="",agent_profile=get_default_value("agent_profile", "agent0"),agent_knowledge_subdir=get_default_value("agent_knowledge_subdir", "custom"),+ max_consecutive_unusable_responses=get_default_value(+ "max_consecutive_unusable_responses", 2+ ),timezone=_normalize_timezone_setting(get_default_value("timezone", TIMEZONE_AUTO)),time_format=_normalize_time_format(get_default_value("time_format", TIME_FORMAT_12H)),workdir_path=get_default_value("workdir_path", files.get_abs_path_dockerized("usr/workdir")),diff --git a/helpers/settings.py.dox.md b/helpers/settings.py.dox.mdindex d5b61ce92..e136941b6 100644--- a/helpers/settings.py.dox.md+++ b/helpers/settings.py.dox.md@@ -64,6 +64,7 @@- Important called helpers/classes observed in the source: `TypeVar`, `files.get_abs_path`, `dotenv.get_dotenv_value`, `opts.insert`, `str.strip`, `_is_valid_timezone`, `str.strip.lower`, `_normalize_timezone_setting`, `SettingsOutput`, `get_default_settings`, `_ensure_option_present`, `_resolve_runtime_timezone`, `get_default_secrets_manager`, `get_settings`, `normalize_settings`, `_load_sensitive_settings`, `settings.copy`, `_write_settings_file`, `reload_settings`, `set_settings`, `initialize_agent`.- Applying settings refreshes active context configs while preserving each subordinate agent's own profile.- Applying settings starts a deferred `MCPConfig.update(...)` with the current `mcp_servers` string when global MCP server settings change.+- `max_consecutive_unusable_responses` defaults to `2` and controls the cost circuit breaker for malformed or repeated main-model outputs.- Keep request/response, tool, or helper semantics documented here at the same time as source changes.## Work Guidancediff --git a/prompts/fw.msg_unusable_response_limit.md b/prompts/fw.msg_unusable_response_limit.mdnew file mode 100644index 000000000..229057c7f--- /dev/null+++ b/prompts/fw.msg_unusable_response_limit.md@@ -0,0 +1 @@+Agent stopped after {{limit}} consecutive unusable model responses to prevent further API charges. Send a new message to try again.diff --git a/tests/test_unusable_response_loop.py b/tests/test_unusable_response_loop.pynew file mode 100644index 000000000..0db2a97ca--- /dev/null+++ b/tests/test_unusable_response_loop.py@@ -0,0 +1,99 @@+from pathlib import Path+from types import SimpleNamespace++from helpers.errors import HandledException+from helpers.files import read_prompt_file+from helpers.settings import get_default_settings, normalize_settings+from extensions.python._functions.agent.Agent.hist_add_warning.end import (+ _90_stop_unusable_response_loop as response_loop,+)+++class FakeLog:+ def __init__(self):+ self.entries = []++ def log(self, **entry):+ self.entries.append(entry)+++def _agent():+ prompts = {+ "fw.msg_misformat.md": "misformatted",+ "fw.msg_repeat.md": "repeated",+ }++ def read_prompt(name, **kwargs):+ if name == "fw.msg_unusable_response_limit.md":+ return f"stopped at {kwargs['limit']}"+ return prompts[name]++ return SimpleNamespace(+ loop_data=SimpleNamespace(iteration=0, params_persistent={}),+ context=SimpleNamespace(log=FakeLog()),+ read_prompt=read_prompt,+ )+++def _run(extension, agent, message):+ data = {"args": (agent, message), "kwargs": {}, "exception": None}+ extension.execute(data=data)+ return data+++def test_stops_at_configured_failure_limit(monkeypatch):+ monkeypatch.setattr(+ response_loop,+ "get_settings",+ lambda: {"max_consecutive_unusable_responses": 3},+ )+ agent = _agent()+ extension = response_loop.StopUnusableResponseLoop(agent=agent)++ assert _run(extension, agent, "misformatted")["exception"] is None++ agent.loop_data.iteration = 1+ assert _run(extension, agent, "repeated")["exception"] is None++ agent.loop_data.iteration = 2+ data = _run(extension, agent, "repeated")++ assert isinstance(data["exception"], HandledException)+ assert agent.loop_data.params_persistent[response_loop.STATE_KEY]["count"] == 3+ assert agent.context.log.entries == [+ {"type": "warning", "content": "stopped at 3"}+ ]+++def test_nonconsecutive_failure_starts_a_new_recovery_window(monkeypatch):+ monkeypatch.setattr(+ response_loop,+ "get_settings",+ lambda: {"max_consecutive_unusable_responses": 2},+ )+ agent = _agent()+ extension = response_loop.StopUnusableResponseLoop(agent=agent)++ assert _run(extension, agent, {"structured": "warning"})["exception"] is None+ _run(extension, agent, "misformatted")+ agent.loop_data.iteration = 2+ data = _run(extension, agent, "repeated")++ assert data["exception"] is None+ assert agent.loop_data.params_persistent[response_loop.STATE_KEY]["count"] == 1+++def test_general_settings_expose_the_default_failure_limit():+ settings = get_default_settings()+ assert settings["max_consecutive_unusable_responses"] == 2+ settings["max_consecutive_unusable_responses"] = 0+ assert normalize_settings(settings)["max_consecutive_unusable_responses"] == 1++ html = Path("webui/components/settings/agent/agent.html").read_text()+ assert (+ 'x-model.number="$store.settings.settings.max_consecutive_unusable_responses"'+ in html+ )+ assert "after 3 consecutive" in read_prompt_file(+ "fw.msg_unusable_response_limit.md", ["prompts"], limit=3+ )diff --git a/webui/components/settings/agent/agent.html b/webui/components/settings/agent/agent.htmlindex 73bf0fe36..6e2494f35 100644--- a/webui/components/settings/agent/agent.html+++ b/webui/components/settings/agent/agent.html@@ -66,6 +66,23 @@</label></div></div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Consecutive unusable response limit</div>+ <div class="field-description">+ Stop after this many malformed or repeated model responses. The default allows one corrective retry.+ </div>+ </div>+ <div class="field-control">+ <input+ type="number"+ min="1"+ step="1"+ x-model.number="$store.settings.settings.max_consecutive_unusable_responses"+ />+ </div>+ </div></div></div></div>