Skip to content

Agent Zero AI framework

Unify exception handling via extensible handle_exception

frdeld7f39cd79ba6
diff --git a/agent.py b/agent.py
index d3422e8fc..4904734e7 100644
--- a/agent.py
+++ b/agent.py
@@ -300,10 +300,12 @@ class AgentContext:
return response
except Exception as 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"]
+ await self.handle_exception("process_chain", e)
+
+ @extensible
+ async def handle_exception(self, location: str, exception: Exception):
+ if exception:
+ raise exception # exception handling is done by extensions
@dataclass
@@ -492,10 +494,7 @@ class Agent:
# exceptions inside message loop:
except Exception as e:
- 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"]
+ await self.handle_exception("message_loop", e)
finally:
# call message_loop_end extensions
@@ -508,10 +507,7 @@ class Agent:
# exceptions outside message loop:
except Exception as e:
- exception_data = { "exception": e }
- await self.call_extensions("monologue_exception", exception_data=exception_data)
- if exception_data["exception"]:
- raise exception_data["exception"]
+ await self.handle_exception("monologue", e)
finally:
self.context.streaming_agent = None # unset current streamer
# call monologue_end extensions
@@ -571,8 +567,10 @@ class Agent:
return full_prompt
@extensible
- async def handle_critical_exception(self, exception: Exception):
- pass
+ async def handle_exception(self, location: str, exception: Exception):
+ if exception:
+ raise exception # exception handling is done by extensions
+
# exception_data = {"exception": exception}
# await self.call_extensions(
# "message_loop_exception", exception_data=exception_data
diff --git a/plugins/error_retry/extensions/python/monologue_exception/_80_retry_critical_exception.py b/plugins/error_retry/extensions/python/agent_Agent_handle_exception_end/_80_retry_critical_exception.py
similarity index 91%
rename from plugins/error_retry/extensions/python/monologue_exception/_80_retry_critical_exception.py
rename to plugins/error_retry/extensions/python/agent_Agent_handle_exception_end/_80_retry_critical_exception.py
index 4ea89e9b2..9d3fa6e87 100644
--- a/plugins/error_retry/extensions/python/monologue_exception/_80_retry_critical_exception.py
+++ b/plugins/error_retry/extensions/python/agent_Agent_handle_exception_end/_80_retry_critical_exception.py
@@ -10,11 +10,11 @@ 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):
+ async def execute(self, data: dict = {}, **kwargs):
if not self.agent:
return
- exception = exception_data.get("exception")
+ exception = data.get("exception")
if not exception:
return
@@ -47,6 +47,6 @@ class RetryCriticalException(Extension):
self.agent.hist_add_warning(message=agent_facing_error)
PrintStyle(font_color="orange", padding=True).print(agent_facing_error)
- exception_data["exception"] = None
+ data["exception"] = None
diff --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.py
deleted file mode 100644
index 408c9996f..000000000
--- a/plugins/error_retry/extensions/python/message_loop_end/_80_retry_critical_exception.py
+++ /dev/null
@@ -1,11 +0,0 @@
-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.py
deleted file mode 100644
index 1b7a9bdcb..000000000
--- a/plugins/error_retry/extensions/python/message_loop_exception/_80_retry_critical_exception.py
+++ /dev/null
@@ -1 +0,0 @@
-from plugins.error_retry.extensions.python.monologue_exception._80_retry_critical_exception import RetryCriticalException
diff --git a/python/api/load_webui_extensions.py b/python/api/load_webui_extensions.py
index c993651e9..667d326fe 100644
--- a/python/api/load_webui_extensions.py
+++ b/python/api/load_webui_extensions.py
@@ -15,6 +15,6 @@ class LoadWebuiExtensions(ApiHandler):
if not extension_point:
return Response(status=400, response="Missing extension_point")
- exts = plugins.get_webui_extensions(extension_point, filters)
+ exts = plugins.get_webui_extensions(agent=None, extension_point=extension_point, filters=filters)
return {"extensions": exts or []}
diff --git a/python/extensions/monologue_exception/_40_handle_intervention_exception.py b/python/extensions/agent_Agent_handle_exception_end/_40_handle_intervention_exception.py
similarity index 60%
rename from python/extensions/monologue_exception/_40_handle_intervention_exception.py
rename to python/extensions/agent_Agent_handle_exception_end/_40_handle_intervention_exception.py
index 8e458c28f..6374113de 100644
--- a/python/extensions/monologue_exception/_40_handle_intervention_exception.py
+++ b/python/extensions/agent_Agent_handle_exception_end/_40_handle_intervention_exception.py
@@ -8,14 +8,14 @@ from python.helpers.print_style import PrintStyle
class HandleInterventionException(Extension):
- async def execute(self, exception_data: dict = {}, **kwargs):
+ async def execute(self, data: dict = {}, **kwargs):
if not self.agent:
return
- if not exception_data.get("exception"):
+ if not data.get("exception"):
return
- if isinstance(exception_data["exception"], InterventionException):
- exception_data["exception"] = None # skip the exception and continue message loop
+ if isinstance(data["exception"], InterventionException):
+ 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/agent_Agent_handle_exception_end/_50_handle_repairable_exception.py
similarity index 69%
rename from python/extensions/monologue_exception/_50_handle_repairable_exception.py
rename to python/extensions/agent_Agent_handle_exception_end/_50_handle_repairable_exception.py
index ed36d5cfd..980d4dda5 100644
--- a/python/extensions/monologue_exception/_50_handle_repairable_exception.py
+++ b/python/extensions/agent_Agent_handle_exception_end/_50_handle_repairable_exception.py
@@ -8,19 +8,19 @@ from python.helpers.print_style import PrintStyle
class HandleRepairableException(Extension):
- async def execute(self, exception_data: dict = {}, **kwargs):
+ async def execute(self, data: dict = {}, **kwargs):
if not self.agent:
return
- if not exception_data.get("exception"):
+ if not data.get("exception"):
return
- if isinstance(exception_data["exception"], RepairableException):
- msg = {"message": errors.format_error(exception_data["exception"])}
+ if isinstance(data["exception"], RepairableException):
+ msg = {"message": errors.format_error(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
+ data["exception"] = None
diff --git a/python/extensions/monologue_exception/_90_handle_critical_exception.py b/python/extensions/agent_Agent_handle_exception_end/_90_handle_critical_exception.py
similarity index 83%
rename from python/extensions/monologue_exception/_90_handle_critical_exception.py
rename to python/extensions/agent_Agent_handle_exception_end/_90_handle_critical_exception.py
index a575a426f..d6b4d904a 100644
--- a/python/extensions/monologue_exception/_90_handle_critical_exception.py
+++ b/python/extensions/agent_Agent_handle_exception_end/_90_handle_critical_exception.py
@@ -8,11 +8,11 @@ from python.helpers.errors import HandledException
class HandleCriticalException(Extension):
- async def execute(self, exception_data: dict = {}, **kwargs):
+ async def execute(self, data: dict = {}, **kwargs):
if not self.agent:
return
- if not (exception:= exception_data.get("exception")):
+ if not (exception:= data.get("exception")):
return
# when exception is HandledException, keep it active, no logging here
@@ -24,7 +24,7 @@ class HandleCriticalException(Extension):
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)
+ data["exception"] = HandledException(exception)
return
# other exceptions should be logged and re-raised as HandledException
@@ -40,4 +40,4 @@ class HandleCriticalException(Extension):
f"{self.agent.agent_name}: {error_text}"
)
- exception_data["exception"] = HandledException(exception)
+ data["exception"] = HandledException(exception)
diff --git a/python/extensions/message_loop_exception/_50_handle_repairable_exception.py b/python/extensions/message_loop_exception/_50_handle_repairable_exception.py
deleted file mode 100644
index 2399361bb..000000000
--- a/python/extensions/message_loop_exception/_50_handle_repairable_exception.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# 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.py
deleted file mode 100644
index 7b03c42b4..000000000
--- a/python/extensions/message_loop_exception/_90_handle_critical_exception.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# 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 file
diff --git a/python/helpers/errors.py b/python/helpers/errors.py
index 3f98a1be5..a0ee7c89a 100644
--- a/python/helpers/errors.py
+++ b/python/helpers/errors.py
@@ -82,6 +82,9 @@ class RepairableException(Exception):
class InterventionException(Exception):
"""An exception type raised on user intervention, skipping rest of message loop iteration."""
pass
+class InterventionException(Exception):
+ """An exception type raised on user intervention, skipping rest of message loop iteration."""
+ pass
class HandledException(Exception):
diff --git a/python/helpers/extension.py b/python/helpers/extension.py
index 921dbe380..87d81404f 100644
--- a/python/helpers/extension.py
+++ b/python/helpers/extension.py
@@ -31,8 +31,8 @@ def extensible(func):
The decorator derives two extension point names from the wrapped function:
- - ``{func.__module__}.{func.__name__}-start``
- - ``{func.__module__}.{func.__name__}-end``
+ - ``{func.__module__}_{func.__qualname__}_start`` with `.` replaced by `_`
+ - ``{func.__module__}_{func.__qualname__}_end`` with `.` replaced by `_`
When the wrapped function is called, the decorator builds a mutable ``data``
payload and passes it to both extension points via ``call_extensions``:
@@ -92,7 +92,7 @@ def extensible(func):
"args": args,
"kwargs": kwargs,
"result": _UNSET,
- "exception": _UNSET,
+ "exception": None,
}
# call start extensions, these can modify inputs, produce output or exception
@@ -114,7 +114,6 @@ def extensible(func):
data["exception"] = e
# call end extensions, these can modify outputs or exception
- agent = _get_agent()
await call_extensions(end_point, agent=agent, data=data)
# if there's an exception, raise it
diff --git a/python/helpers/plugins.py b/python/helpers/plugins.py
index 1e97fb3f7..4b8dbc62e 100644
--- a/python/helpers/plugins.py
+++ b/python/helpers/plugins.py
@@ -204,9 +204,8 @@ def get_enabled_plugin_paths(agent: Agent | None, *subpaths: str) -> List[str]:
paths.append(base_dir)
continue
- path = files.get_abs_path(base_dir, *subpaths)
- if files.exists(path):
- paths.append(path)
+ path_pattern = files.get_abs_path(base_dir, *subpaths)
+ paths.extend(files.find_existing_paths_by_pattern(path_pattern))
return paths
@@ -339,12 +338,12 @@ def toggle_plugin(
files.write_file(disabled_file, "")
-def get_webui_extensions(extension_point: str, filters: List[str] | None = None):
+def get_webui_extensions(agent: Agent | None, extension_point: str, filters: List[str] | None = None):
entries: List[str] = []
effective_filters = filters or ["*"]
for filter in effective_filters:
- extensions = get_plugin_paths("extensions", "webui", extension_point, filter)
+ extensions = get_enabled_plugin_paths(agent, "extensions", "webui", extension_point, filter)
for extension in extensions:
rel_path = files.deabsolute_path(extension)
entries.append(rel_path)
diff --git a/python/helpers/task_scheduler.py b/python/helpers/task_scheduler.py
index 103f28732..fb230622b 100644
--- a/python/helpers/task_scheduler.py
+++ b/python/helpers/task_scheduler.py
@@ -934,7 +934,7 @@ class TaskScheduler:
await self.update_task(task_uuid, state=TaskState.ERROR)
# if agent:
- # await agent.handle_critical_exception(e)
+ # await agent.handle_exception("scheduler", e)
finally:
# Call on_finish for task-specific cleanup
try: