Agent Zero AI framework
Move exception handling to extensions
frdel0372c05f2b5d
diff --git a/agent.py b/agent.pyindex 5e4bfc2f6..d3422e8fc 100644--- a/agent.py+++ b/agent.py@@ -17,6 +17,7 @@ from python.helpers import (dirty_json,subagents,)+from python.helpers import extensionfrom python.helpers.print_style import PrintStylefrom langchain_core.prompts import (@@ -30,7 +31,7 @@ from python.helpers.defer import DeferredTaskfrom typing import Callablefrom python.helpers.localization import Localizationfrom python.helpers.extension import call_extensions, extensible-from python.helpers.errors import RepairableException+from python.helpers.errors import RepairableException, InterventionException, HandledExceptionclass AgentContextType(Enum):@@ -240,6 +241,7 @@ class AgentContext:self.task = self.communicate(UserMessage(self.agent0.read_prompt("fw.msg_nudge.md")))return self.task+ @extensibledef get_agent(self):return self.streaming_agent or self.agent0@@ -298,7 +300,10 @@ class AgentContext:return responseexcept Exception as e:- agent.handle_critical_exception(e)+ exception_data = {"exception": e}+ await extension.call_extensions("context_chain_exception", agent=agent, exception_data=exception_data)+ if exception_data.get("exception"):+ raise exception_data["exception"]@dataclass@@ -346,18 +351,6 @@ class LoopData:setattr(self, key, value)-# intervention exception class - skips rest of message loop iteration-class InterventionException(Exception):- pass---# killer exception class - not forwarded to LLM, cannot be fixed on its own, ends message loop---class HandledException(Exception):- pass--class Agent:DATA_NAME_SUPERIOR = "_superior"@@ -388,7 +381,6 @@ class Agent:@extensibleasync def monologue(self):- error_retries = 0 # counter for critical error retrieswhile True:try:# loop data dictionary to pass to extensions@@ -498,24 +490,12 @@ class Agent:if tools_result: # final response of message loop availablereturn tools_result # break the execution if the task is done- error_retries = 0 # reset retry counter on successful iteration-# exceptions inside message loop:- except InterventionException as e:- error_retries = 0 # reset retry counter on user intervention- pass # intervention message has been handled in handle_intervention(), proceed with conversation loop- except RepairableException as e:- # Forward repairable errors to the LLM, maybe it can fix them- msg = {"message": errors.format_error(e)}- await self.call_extensions("error_format", msg=msg)- self.hist_add_warning(msg["message"])- PrintStyle(font_color="red", padding=True).print(msg["message"])- self.context.log.log(type="warning", content=msg["message"])except Exception as e:- # Retry critical exceptions before failing- error_retries = await self.retry_critical_exception(- e, error_retries- )+ exception_data = { "exception": e }+ await self.call_extensions("message_loop_exception", loop_data=self.loop_data, exception_data=exception_data)+ if exception_data["exception"]:+ raise exception_data["exception"]finally:# call message_loop_end extensions@@ -527,14 +507,11 @@ class Agent:# exceptions outside message loop:- except InterventionException as e:- error_retries = 0 # reset retry counter on user intervention- pass # just start overexcept Exception as e:- # Retry critical exceptions before failing- error_retries = await self.retry_critical_exception(- e, error_retries- )+ exception_data = { "exception": e }+ await self.call_extensions("monologue_exception", exception_data=exception_data)+ if exception_data["exception"]:+ raise exception_data["exception"]finally:self.context.streaming_agent = None # unset current streamer# call monologue_end extensions@@ -594,59 +571,42 @@ class Agent:return full_prompt@extensible- async def retry_critical_exception(- self, e: Exception, error_retries: int, delay: int = 3, max_retries: int = 1- ) -> int:- if error_retries >= max_retries:- self.handle_critical_exception(e)-- error_message = errors.format_error(e)-- self.context.log.log(- type="warning", heading="Critical error occurred, retrying...", content=error_message- )- PrintStyle(font_color="orange", padding=True).print(- "Critical error occurred, retrying..."- )- await asyncio.sleep(delay)- await self.handle_intervention()- agent_facing_error = self.read_prompt(- "fw.msg_critical_error.md", error_message=error_message- )- self.hist_add_warning(message=agent_facing_error)- PrintStyle(font_color="orange", padding=True).print(- agent_facing_error- )- return error_retries + 1-- @extensible- def handle_critical_exception(self, exception: Exception):- if isinstance(exception, HandledException):- raise exception # Re-raise the exception to kill the loop- elif isinstance(exception, asyncio.CancelledError):- # Handling for asyncio.CancelledError- PrintStyle(font_color="white", background_color="red", padding=True).print(- f"Context {self.context.id} terminated during message loop"- )- raise HandledException(- exception- ) # Re-raise the exception to cancel the loop- else:- # Handling for general exceptions- error_text = errors.error_text(exception)- error_message = errors.format_error(exception)-- # Mask secrets in error messages- PrintStyle(font_color="red", padding=True).print(error_message)- self.context.log.log(- type="error",- content=error_message,- )- PrintStyle(font_color="red", padding=True).print(- f"{self.agent_name}: {error_text}"- )-- raise HandledException(exception) # Re-raise the exception to kill the loop+ async def handle_critical_exception(self, exception: Exception):+ pass+ # exception_data = {"exception": exception}+ # await self.call_extensions(+ # "message_loop_exception", exception_data=exception_data+ # )++ # # If extensions cleared the exception, continue.+ # if not exception_data.get("exception"):+ # return++ # # Backwards-compatible fallback (should normally be handled by _90 extension).+ # exception = exception_data["exception"]+ # if isinstance(exception, HandledException):+ # raise exception+ # elif isinstance(exception, asyncio.CancelledError):+ # PrintStyle(font_color="white", background_color="red", padding=True).print(+ # f"Context {self.context.id} terminated during message loop"+ # )+ # raise HandledException(exception)++ # else:+ # error_text = errors.error_text(exception)+ # error_message = errors.format_error(exception)++ # # Mask secrets in error messages+ # PrintStyle(font_color="red", padding=True).print(error_message)+ # self.context.log.log(+ # type="error",+ # content=error_message,+ # )+ # PrintStyle(font_color="red", padding=True).print(+ # f"{self.agent_name}: {error_text}"+ # )++ # raise HandledException(exception) # Re-raise the exception to kill the loop@extensibleasync def get_system_prompt(self, loop_data: LoopData) -> list[str]:@@ -858,8 +818,7 @@ class Agent:@extensibleasync def handle_intervention(self, progress: str = ""):- while self.context.paused:- await asyncio.sleep(0.1) # wait if paused+ await self.wait_if_paused()if (self.intervention): # if there is an intervention message, but not yet processeddiff --git a/plugins/error_retry/extensions/python/agent_Agent_monologue_start/_10_reset_critical_exception_counter.py b/plugins/error_retry/extensions/python/agent_Agent_monologue_start/_10_reset_critical_exception_counter.pynew file mode 100644index 000000000..7f997c6bf--- /dev/null+++ b/plugins/error_retry/extensions/python/agent_Agent_monologue_start/_10_reset_critical_exception_counter.py@@ -0,0 +1,18 @@+from datetime import datetime, timezone+from python.helpers.extension import Extension+from agent import LoopData+from python.helpers.localization import Localization+from python.helpers.errors import RepairableException+from python.helpers import errors+from python.helpers.print_style import PrintStyle++DATA_NAME_COUNTER = "_plugin.error_retry.critical_exception_counter"++class ResetCriticalExceptionCounter(Extension):+ async def execute(self, exception_data: dict = {}, **kwargs):+ if not self.agent:+ return++ self.agent.set_data(DATA_NAME_COUNTER, 0)++\ No newline at end of filediff --git a/plugins/error_retry/extensions/python/message_loop_end/_80_retry_critical_exception.py b/plugins/error_retry/extensions/python/message_loop_end/_80_retry_critical_exception.pynew file mode 100644index 000000000..408c9996f--- /dev/null+++ b/plugins/error_retry/extensions/python/message_loop_end/_80_retry_critical_exception.py@@ -0,0 +1,11 @@+from datetime import datetime, timezone+from python.helpers.extension import Extension+from agent import LoopData+from python.helpers.localization import Localization+from python.helpers.errors import RepairableException+from python.helpers import errors+from python.helpers.print_style import PrintStyle++# we can reuse the monologue exception handler here like this+from plugins.error_retry.extensions.python.monologue_exception._80_retry_critical_exception import RetryCriticalException+diff --git a/plugins/error_retry/extensions/python/message_loop_exception/_80_retry_critical_exception.py b/plugins/error_retry/extensions/python/message_loop_exception/_80_retry_critical_exception.pynew file mode 100644index 000000000..1b7a9bdcb--- /dev/null+++ b/plugins/error_retry/extensions/python/message_loop_exception/_80_retry_critical_exception.py@@ -0,0 +1 @@+from plugins.error_retry.extensions.python.monologue_exception._80_retry_critical_exception import RetryCriticalExceptiondiff --git a/plugins/error_retry/extensions/python/monologue_exception/_80_retry_critical_exception.py b/plugins/error_retry/extensions/python/monologue_exception/_80_retry_critical_exception.pynew file mode 100644index 000000000..4ea89e9b2--- /dev/null+++ b/plugins/error_retry/extensions/python/monologue_exception/_80_retry_critical_exception.py@@ -0,0 +1,52 @@+import asyncio+from datetime import datetime, timezone+from python.helpers.extension import Extension+from agent import LoopData+from python.helpers.localization import Localization+from python.helpers.errors import RepairableException, HandledException+from python.helpers import errors+from python.helpers.print_style import PrintStyle++from plugins.error_retry.extensions.python.agent_Agent_monologue_start._10_reset_critical_exception_counter import DATA_NAME_COUNTER++class RetryCriticalException(Extension):+ async def execute(self, exception_data: dict = {}, **kwargs):+ if not self.agent:+ return++ exception = exception_data.get("exception")+ if not exception:+ return++ if isinstance(exception, (HandledException, RepairableException)):+ return++ max_retries = 1+ delay = 3++ counter = self.agent.get_data(DATA_NAME_COUNTER) or 0+ if counter >= max_retries:+ return++ self.agent.set_data(DATA_NAME_COUNTER, counter + 1)++ error_message = errors.format_error(exception)+ self.agent.context.log.log(+ type="warning",+ heading="Critical error occurred, retrying...",+ content=error_message,+ )+ PrintStyle(font_color="orange", padding=True).print(+ "Critical error occurred, retrying..."+ )+ await asyncio.sleep(delay)+ await self.agent.handle_intervention()+ agent_facing_error = self.agent.read_prompt(+ "fw.msg_critical_error.md", error_message=error_message+ )+ self.agent.hist_add_warning(message=agent_facing_error)+ PrintStyle(font_color="orange", padding=True).print(agent_facing_error)++ exception_data["exception"] = None++diff --git a/plugins/error_retry/plugin.yaml b/plugins/error_retry/plugin.yamlnew file mode 100644index 000000000..0dfb2224d--- /dev/null+++ b/plugins/error_retry/plugin.yaml@@ -0,0 +1,7 @@+title: Error retry+description: Retry on critical exceptions before failing+version: 1.0.0+settings_sections: ["agent"]+per_project_config: true+per_agent_config: true+always_enabled: falsediff --git a/plugins/memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py b/plugins/memory/extensions/python/message_loop_prompts_after/_50_recall_memories.pyindex ab8ec6ac2..7380a8727 100644--- a/plugins/memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py+++ b/plugins/memory/extensions/python/message_loop_prompts_after/_50_recall_memories.py@@ -24,6 +24,8 @@ class RecallMemories(Extension):# THRESHOLD = DEFAULT_MEMORY_THRESHOLDasync def execute(self, loop_data: LoopData = LoopData(), **kwargs):+ if not self.agent:+ returnset = plugins.get_plugin_config("memory", self.agent)if not set:@@ -56,6 +58,8 @@ class RecallMemories(Extension):self.agent.set_data(DATA_NAME_ITER, loop_data.iteration)async def search_memories(self, log_item: log.LogItem, loop_data: LoopData, **kwargs):+ if not self.agent:+ return# cleanupextras = loop_data.extras_persistentdiff --git a/plugins/memory/extensions/python/message_loop_prompts_after/_91_recall_wait.py b/plugins/memory/extensions/python/message_loop_prompts_after/_91_recall_wait.pyindex 45965a222..d108a6da6 100644--- a/plugins/memory/extensions/python/message_loop_prompts_after/_91_recall_wait.py+++ b/plugins/memory/extensions/python/message_loop_prompts_after/_91_recall_wait.py@@ -6,6 +6,9 @@ from python.helpers import pluginsclass RecallWait(Extension):async def execute(self, loop_data: LoopData = LoopData(), **kwargs):+ if not self.agent:+ return+set = plugins.get_plugin_config("memory", self.agent)if not set:return Nonediff --git a/plugins/memory/extensions/python/monologue_end/_50_memorize_fragments.py b/plugins/memory/extensions/python/monologue_end/_50_memorize_fragments.pyindex 391cf4104..363bc8971 100644--- a/plugins/memory/extensions/python/monologue_end/_50_memorize_fragments.py+++ b/plugins/memory/extensions/python/monologue_end/_50_memorize_fragments.py@@ -15,6 +15,8 @@ class MemorizeMemories(Extension):async def execute(self, loop_data: LoopData = LoopData(), **kwargs):# try:+ if not self.agent:+ returnset = plugins.get_plugin_config("memory", self.agent)if not set:@@ -36,6 +38,8 @@ class MemorizeMemories(Extension):return taskasync def memorize(self, loop_data: LoopData, log_item: LogItem, **kwargs):+ if not self.agent:+ returntry:set = plugins.get_plugin_config("memory", self.agent)diff --git a/plugins/memory/extensions/python/monologue_end/_51_memorize_solutions.py b/plugins/memory/extensions/python/monologue_end/_51_memorize_solutions.pyindex aeef9ea1c..10ffa20d5 100644--- a/plugins/memory/extensions/python/monologue_end/_51_memorize_solutions.py+++ b/plugins/memory/extensions/python/monologue_end/_51_memorize_solutions.py@@ -14,6 +14,8 @@ class MemorizeSolutions(Extension):async def execute(self, loop_data: LoopData = LoopData(), **kwargs):# try:+ if not self.agent:+ returnset = plugins.get_plugin_config("memory", self.agent)if not set:@@ -35,7 +37,11 @@ class MemorizeSolutions(Extension):return taskasync def memorize(self, loop_data: LoopData, log_item: LogItem, **kwargs):+ if not self.agent:+ return+try:+set = plugins.get_plugin_config("memory", self.agent)if not set:return Nonediff --git a/plugins/memory/extensions/python/monologue_start/_10_memory_init.py b/plugins/memory/extensions/python/monologue_start/_10_memory_init.pyindex 1bacc881c..5a3e3c549 100644--- a/plugins/memory/extensions/python/monologue_start/_10_memory_init.py+++ b/plugins/memory/extensions/python/monologue_start/_10_memory_init.py@@ -8,4 +8,7 @@ from plugins.memory.helpers import memoryclass MemoryInit(Extension):async def execute(self, loop_data: LoopData = LoopData(), **kwargs):+ if not self.agent:+ return+db = await memory.Memory.get(self.agent)diff --git a/plugins/memory/extensions/python/system_prompt/_20_behaviour_prompt.py b/plugins/memory/extensions/python/system_prompt/_20_behaviour_prompt.pyindex bec18f0fd..c2f5e7998 100644--- a/plugins/memory/extensions/python/system_prompt/_20_behaviour_prompt.py+++ b/plugins/memory/extensions/python/system_prompt/_20_behaviour_prompt.py@@ -9,6 +9,9 @@ from plugins.memory.helpers import memoryclass BehaviourPrompt(Extension):async def execute(self, system_prompt: list[str]=[], loop_data: LoopData = LoopData(), **kwargs):+ if not self.agent:+ return+prompt = read_rules(self.agent)system_prompt.insert(0, prompt)diff --git a/python/extensions/message_loop_exception/_50_handle_repairable_exception.py b/python/extensions/message_loop_exception/_50_handle_repairable_exception.pynew file mode 100644index 000000000..2399361bb--- /dev/null+++ b/python/extensions/message_loop_exception/_50_handle_repairable_exception.py@@ -0,0 +1,3 @@+# we can reuse the monologue exception handler here like this+from python.extensions.monologue_exception._50_handle_repairable_exception import HandleRepairableException+diff --git a/python/extensions/message_loop_exception/_90_handle_critical_exception.py b/python/extensions/message_loop_exception/_90_handle_critical_exception.pynew file mode 100644index 000000000..7b03c42b4--- /dev/null+++ b/python/extensions/message_loop_exception/_90_handle_critical_exception.py@@ -0,0 +1,2 @@+# we can reuse the monologue exception handler here like this+from python.extensions.monologue_exception._90_handle_critical_exception import HandleCriticalException\ No newline at end of filediff --git a/python/extensions/monologue_exception/_40_handle_intervention_exception.py b/python/extensions/monologue_exception/_40_handle_intervention_exception.pynew file mode 100644index 000000000..8e458c28f--- /dev/null+++ b/python/extensions/monologue_exception/_40_handle_intervention_exception.py@@ -0,0 +1,21 @@+from datetime import datetime, timezone+from python.helpers.extension import Extension+from agent import LoopData+from python.helpers.localization import Localization+from python.helpers.errors import InterventionException+from python.helpers import errors+from python.helpers.print_style import PrintStyle+++class HandleInterventionException(Extension):+ async def execute(self, exception_data: dict = {}, **kwargs):+ if not self.agent:+ return++ if not exception_data.get("exception"):+ return++ if isinstance(exception_data["exception"], InterventionException):+ exception_data["exception"] = None # skip the exception and continue message loop++diff --git a/python/extensions/monologue_exception/_50_handle_repairable_exception.py b/python/extensions/monologue_exception/_50_handle_repairable_exception.pynew file mode 100644index 000000000..ed36d5cfd--- /dev/null+++ b/python/extensions/monologue_exception/_50_handle_repairable_exception.py@@ -0,0 +1,26 @@+from datetime import datetime, timezone+from python.helpers.extension import Extension+from agent import LoopData+from python.helpers.localization import Localization+from python.helpers.errors import RepairableException+from python.helpers import errors+from python.helpers.print_style import PrintStyle+++class HandleRepairableException(Extension):+ async def execute(self, exception_data: dict = {}, **kwargs):+ if not self.agent:+ return++ if not exception_data.get("exception"):+ return++ if isinstance(exception_data["exception"], RepairableException):+ msg = {"message": errors.format_error(exception_data["exception"])}+ await self.agent.call_extensions("error_format", msg=msg)+ self.agent.hist_add_warning(msg["message"])+ PrintStyle(font_color="red", padding=True).print(msg["message"])+ self.agent.context.log.log(type="warning", content=msg["message"])+ exception_data["exception"] = None++diff --git a/python/extensions/monologue_exception/_90_handle_critical_exception.py b/python/extensions/monologue_exception/_90_handle_critical_exception.pynew file mode 100644index 000000000..a575a426f--- /dev/null+++ b/python/extensions/monologue_exception/_90_handle_critical_exception.py@@ -0,0 +1,43 @@+import asyncio++from python.helpers.extension import Extension+from python.helpers.print_style import PrintStyle+from python.helpers import errors++from python.helpers.errors import HandledException+++class HandleCriticalException(Extension):+ async def execute(self, exception_data: dict = {}, **kwargs):+ if not self.agent:+ return++ if not (exception:= exception_data.get("exception")):+ return++ # when exception is HandledException, keep it active, no logging here+ if isinstance(exception, HandledException):+ return++ # asyncio cancel - chat is being terminated, print out and re-raise as handledException+ if isinstance(exception, asyncio.CancelledError):+ PrintStyle(font_color="white", background_color="red", padding=True).print(+ f"Context {self.agent.context.id} terminated during message loop"+ )+ exception_data["exception"] = HandledException(exception)+ return++ # other exceptions should be logged and re-raised as HandledException+ error_text = errors.error_text(exception)+ error_message = errors.format_error(exception)++ PrintStyle(font_color="red", padding=True).print(error_message)+ self.agent.context.log.log(+ type="error",+ content=error_message,+ )+ PrintStyle(font_color="red", padding=True).print(+ f"{self.agent.agent_name}: {error_text}"+ )++ exception_data["exception"] = HandledException(exception)diff --git a/python/helpers/errors.py b/python/helpers/errors.pyindex 4a2beb35d..3f98a1be5 100644--- a/python/helpers/errors.py+++ b/python/helpers/errors.py@@ -78,3 +78,11 @@ def format_error(e: Exception, start_entries=20, end_entries=15, error_message_pclass RepairableException(Exception):"""An exception type indicating errors that can be surfaced to the LLM for potential self-repair."""pass++class InterventionException(Exception):+ """An exception type raised on user intervention, skipping rest of message loop iteration."""+ pass+++class HandledException(Exception):+ pass\ No newline at end of filediff --git a/python/helpers/extension.py b/python/helpers/extension.pyindex ae848223a..921dbe380 100644--- a/python/helpers/extension.py+++ b/python/helpers/extension.py@@ -63,15 +63,15 @@ def extensible(func):from agent import Agent# prepare extension points data- module_name = getattr(func, "__module__", "")- qual_name = getattr(func, "__qualname__", "")+ module_name = getattr(func, "__module__", "").replace(".", "_")+ qual_name = getattr(func, "__qualname__", "").replace(".", "_")# skip if extension point cannot be determinedif not module_name or not qual_name:return await func(*args, **kwargs)- start_point = f"{module_name}.{qual_name}-start"- end_point = f"{module_name}.{qual_name}-end"+ start_point = f"{module_name}_{qual_name}_start"+ end_point = f"{module_name}_{qual_name}_end"def _get_agent() -> "Agent|None":candidate = kwargs.get("agent")diff --git a/python/helpers/task_scheduler.py b/python/helpers/task_scheduler.pyindex b4fb0fbeb..103f28732 100644--- a/python/helpers/task_scheduler.py+++ b/python/helpers/task_scheduler.py@@ -933,8 +933,8 @@ class TaskScheduler:PrintStyle.warning(f"Fixing task state consistency: '{current_task.name}' state is not ERROR after failure")await self.update_task(task_uuid, state=TaskState.ERROR)- if agent:- agent.handle_critical_exception(e)+ # if agent:+ # await agent.handle_critical_exception(e)finally:# Call on_finish for task-specific cleanuptry:diff --git a/plugins/tests/test_webui_extension_surfaces.py b/tests/test_webui_extension_surfaces.pysimilarity index 100%rename from plugins/tests/test_webui_extension_surfaces.pyrename to tests/test_webui_extension_surfaces.pydiff --git a/webui/components/sidebar/top-section/quick-actions.html b/webui/components/sidebar/top-section/quick-actions.htmlindex 988e977e1..f67fe771f 100644--- a/webui/components/sidebar/top-section/quick-actions.html+++ b/webui/components/sidebar/top-section/quick-actions.html@@ -56,7 +56,7 @@<span>Projects</span></button>- <button class="dropdown-item" @click="openModal('components/scheduler/scheduler-modal.html'); dropdownOpen = false">+ <button class="dropdown-item" @click="openModal('components/modals/scheduler/scheduler-modal.html'); dropdownOpen = false"><span class="material-symbols-outlined">schedule</span><span>Scheduler</span></button>