Agent Zero AI framework
Add extensible hooks and improve agent detection
frdelf7b7683918b7
diff --git a/agent.py b/agent.pyindex b682b0bed..5e4bfc2f6 100644--- a/agent.py+++ b/agent.py@@ -15,7 +15,7 @@ from python.helpers import (tokens,context as context_helper,dirty_json,- subagents+ subagents,)from python.helpers.print_style import PrintStyle@@ -29,7 +29,7 @@ from python.helpers.dirty_json import DirtyJsonfrom python.helpers.defer import DeferredTaskfrom typing import Callablefrom python.helpers.localization import Localization-from python.helpers.extension import call_extensions+from python.helpers.extension import call_extensions, extensiblefrom python.helpers.errors import RepairableException@@ -46,6 +46,7 @@ class AgentContext:_counter: int = 0_notification_manager = None+ @extensibledef __init__(self,config: "AgentConfig",@@ -151,6 +152,7 @@ class AgentContext:return cls._notification_manager@staticmethod+ @extensibledef remove(id: str):with AgentContext._contexts_lock:context = AgentContext._contexts.pop(id, None)@@ -174,6 +176,7 @@ class AgentContext:# recursive is not used now, prepared for context hierarchyself.output_data[key] = value+ @extensibledef output(self):return {"id": self.id,@@ -217,10 +220,12 @@ class AgentContext:)return items+ @extensibledef kill_process(self):if self.task:self.task.kill()+ @extensibledef reset(self):self.kill_process()self.log.reset()@@ -228,6 +233,7 @@ class AgentContext:self.streaming_agent = Noneself.paused = False+ @extensibledef nudge(self):self.kill_process()self.paused = False@@ -240,6 +246,7 @@ class AgentContext:def is_running(self) -> bool:return (self.task and self.task.is_alive()) or False+ @extensibledef communicate(self, msg: "UserMessage", broadcast_level: int = 1):self.paused = False # unpause if paused@@ -259,6 +266,7 @@ class AgentContext:return self.task+ @extensibledef run_task(self, func: Callable[..., Coroutine[Any, Any, Any]], *args: Any, **kwargs: Any):@@ -270,6 +278,7 @@ class AgentContext:return self.task# this wrapper ensures that superior agents are called back if the chat was loaded from file and original callstack is gone+ @extensibleasync def _process_chain(self, agent: "Agent", msg: "UserMessage|str", user=True):try:msg_template = (@@ -355,6 +364,7 @@ class Agent:DATA_NAME_SUBORDINATE = "_subordinate"DATA_NAME_CTX_WINDOW = "ctx_window"+ @extensibledef __init__(self, number: int, config: AgentConfig, context: AgentContext | None = None):@@ -376,6 +386,7 @@ class Agent:asyncio.run(self.call_extensions("agent_init"))+ @extensibleasync def monologue(self):error_retries = 0 # counter for critical error retrieswhile True:@@ -530,6 +541,7 @@ class Agent:if self.context.task and self.context.task.is_alive(): # don't call extensions post mortemawait self.call_extensions("monologue_end", loop_data=self.loop_data) # type: ignore+ @extensibleasync def prepare_prompt(self, loop_data: LoopData) -> list[BaseMessage]:self.context.log.set_progress("Building prompt")@@ -581,6 +593,7 @@ class Agent:return full_prompt+ @extensibleasync def retry_critical_exception(self, e: Exception, error_retries: int, delay: int = 3, max_retries: int = 1) -> int:@@ -606,6 +619,7 @@ class Agent:)return error_retries + 1+ @extensibledef handle_critical_exception(self, exception: Exception):if isinstance(exception, HandledException):raise exception # Re-raise the exception to kill the loop@@ -634,6 +648,7 @@ class Agent:raise HandledException(exception) # Re-raise the exception to kill the loop+ @extensibleasync def get_system_prompt(self, loop_data: LoopData) -> list[str]:system_prompt: list[str] = []await self.call_extensions(@@ -641,6 +656,7 @@ class Agent:)return system_prompt+ @extensibledef parse_prompt(self, _prompt_file: str, **kwargs):dirs = subagents.get_paths(self, "prompts")@@ -649,6 +665,7 @@ class Agent:)return prompt+ @extensibledef read_prompt(self, file: str, **kwargs) -> str:dirs = subagents.get_paths(self, "prompts")@@ -663,6 +680,7 @@ class Agent:def set_data(self, field: str, value):self.data[field] = value+ @extensibledef hist_add_message(self, ai: bool, content: history.MessageContent, tokens: int = 0):@@ -676,6 +694,7 @@ class Agent:ai=ai, content=content_data["content"], tokens=tokens)+ @extensibledef hist_add_user_message(self, message: UserMessage, intervention: bool = False):self.history.new_topic() # user message starts a new topic in history@@ -704,15 +723,18 @@ class Agent:self.last_user_message = msgreturn msg+ @extensibledef hist_add_ai_response(self, message: str):self.loop_data.last_response = messagecontent = self.parse_prompt("fw.ai_response.md", message=message)return self.hist_add_message(True, content=content)+ @extensibledef hist_add_warning(self, message: history.MessageContent):content = self.parse_prompt("fw.warning.md", message=message)return self.hist_add_message(False, content=content)+ @extensibledef hist_add_tool_result(self, tool_name: str, tool_result: str, **kwargs):data = {"tool_name": tool_name,@@ -727,6 +749,7 @@ class Agent:): # TODO add param for message range, topic, historyreturn self.history.output_text(human_label="user", ai_label="assistant")+ @extensibledef get_chat_model(self):return models.get_chat_model(self.config.chat_model.provider,@@ -735,6 +758,7 @@ class Agent:**self.config.chat_model.build_kwargs(),)+ @extensibledef get_utility_model(self):return models.get_chat_model(self.config.utility_model.provider,@@ -743,6 +767,7 @@ class Agent:**self.config.utility_model.build_kwargs(),)+ @extensibledef get_browser_model(self):return models.get_browser_model(self.config.browser_model.provider,@@ -751,6 +776,7 @@ class Agent:**self.config.browser_model.build_kwargs(),)+ @extensibledef get_embedding_model(self):return models.get_embedding_model(self.config.embeddings_model.provider,@@ -759,6 +785,7 @@ class Agent:**self.config.embeddings_model.build_kwargs(),)+ @extensibleasync def call_utility_model(self,system: str,@@ -794,6 +821,7 @@ class Agent:return response+ @extensibleasync def call_chat_model(self,messages: list[BaseMessage],@@ -820,6 +848,7 @@ class Agent:return response, reasoning+ @extensibleasync def rate_limiter_callback(self, message: str, key: str, total: int, limit: int):@@ -827,6 +856,7 @@ class Agent:self.context.log.set_progress(message, True)return False+ @extensibleasync def handle_intervention(self, progress: str = ""):while self.context.paused:await asyncio.sleep(0.1) # wait if paused@@ -852,6 +882,7 @@ class Agent:while self.context.paused:await asyncio.sleep(0.1)+ @extensibleasync def process_tools(self, msg: str):# search for tool usage requests in agent messagetool_request = extract_tools.json_parse_dirty(msg)@@ -971,6 +1002,7 @@ class Agent:except Exception as e:pass+ @extensibledef get_tool(self,name: str,diff --git a/python/helpers/extension.py b/python/helpers/extension.pyindex c07b8546f..ae848223a 100644--- a/python/helpers/extension.py+++ b/python/helpers/extension.py@@ -64,20 +64,28 @@ def extensible(func):# prepare extension points datamodule_name = getattr(func, "__module__", "")- func_name = getattr(func, "__name__", "")- start_point = f"{module_name}.{func_name}-start"- end_point = f"{module_name}.{func_name}-end"+ qual_name = getattr(func, "__qualname__", "")++ # skip if extension point cannot be determined+ if 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"++ def _get_agent() -> "Agent|None":+ candidate = kwargs.get("agent")+ if isinstance(candidate, Agent) and bool(getattr(candidate, "__dict__", None)):+ return candidate++ for a in args:+ if isinstance(a, Agent) and bool(getattr(a, "__dict__", None)):+ return a++ return None# try to find agent instance for better extension determination- agent = kwargs.get("agent")- if (not agent or not isinstance(agent, Agent)) and args:- try:- for a in args:- if isinstance(a, Agent):- agent = a- break- except Exception:- agent = None+ agent = _get_agent()# build extension data object - func input/outputdata = {@@ -106,6 +114,7 @@ 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 itdiff --git a/python/tools/code_execution_tool.py b/python/tools/code_execution_tool.pyindex f7435393a..7149278e9 100644--- a/python/tools/code_execution_tool.py+++ b/python/tools/code_execution_tool.py@@ -241,7 +241,7 @@ class CodeExecution(Tool):between_output_timeout=15, # Wait up to x seconds between outputsdialog_timeout=5, # potential dialog detection timeoutmax_exec_timeout=180, # hard cap on total runtime- sleep_time=0.1,+ sleep_time=0.5,prefix="",timeouts: dict | None = None,):diff --git a/run_ui.py b/run_ui.pyindex ee8aebbf5..08c4a061a 100644--- a/run_ui.py+++ b/run_ui.py@@ -11,7 +11,7 @@ from flask import Flask, request, Response, session, redirect, url_for, render_tfrom werkzeug.wrappers.request import Request as WerkzeugRequestimport initialize-from python.helpers import files, git, mcp_server, fasta2a_server, settings as settings_helper+from python.helpers import files, git, mcp_server, fasta2a_server, settings as settings_helper, extensionfrom python.helpers.files import get_abs_pathfrom python.helpers import runtime, dotenv, processfrom python.helpers.websocket import WebSocketHandler, validate_ws_origin@@ -83,6 +83,7 @@ websocket_manager.set_server_restart_broadcast(@webapp.route("/login", methods=["GET", "POST"])async def login_handler():error = Noneif request.method == 'POST':@@ -101,6 +102,7 @@ async def login_handler():@webapp.route("/logout")async def logout_handler():session.pop('authentication', None)return redirect(url_for('login_handler'))@@ -109,6 +111,7 @@ async def logout_handler():# handle default address, load index@webapp.route("/", methods=["GET"])@requires_authasync def serve_index():gitinfo = Nonetry:@@ -142,6 +145,7 @@ async def serve_plugin_asset(plugin_name, asset_path):return await _serve_plugin_asset(plugin_name, asset_path)async def _serve_plugin_asset(plugin_name, asset_path):"""Serve static assets from plugin directories.@@ -452,6 +456,7 @@ def wait_for_health(host: str, port: int):time.sleep(1)def init_a0():# initialize contexts and MCPinit_chats = initialize.initialize_chats()