feat(hooks): introduce event hooks system for lifecycle management
Add a new hooks system allowing users to run custom code at key lifecycle points in the agent's operation. This includes support for events such as `gateway:startup`, `session:start`, `agent:step`, and more. Documentation for creating hooks and available events has been added to `README.md` and a new `hooks.md` file. Additionally, integrate step callbacks in the agent to facilitate hook execution during tool-calling iterations.
This commit is contained in:
parent
bf52468a91
commit
7f7643cf63
4 changed files with 252 additions and 0 deletions
18
run_agent.py
18
run_agent.py
|
|
@ -124,6 +124,7 @@ class AIAgent:
|
|||
session_id: str = None,
|
||||
tool_progress_callback: callable = None,
|
||||
clarify_callback: callable = None,
|
||||
step_callback: callable = None,
|
||||
max_tokens: int = None,
|
||||
reasoning_config: Dict[str, Any] = None,
|
||||
prefill_messages: List[Dict[str, Any]] = None,
|
||||
|
|
@ -195,6 +196,7 @@ class AIAgent:
|
|||
)
|
||||
self.tool_progress_callback = tool_progress_callback
|
||||
self.clarify_callback = clarify_callback
|
||||
self.step_callback = step_callback
|
||||
self._last_reported_tool = None # Track for "new tool" mode
|
||||
|
||||
# Interrupt mechanism for breaking out of tool loops
|
||||
|
|
@ -1936,6 +1938,22 @@ class AIAgent:
|
|||
|
||||
api_call_count += 1
|
||||
|
||||
# Fire step_callback for gateway hooks (agent:step event)
|
||||
if self.step_callback is not None:
|
||||
try:
|
||||
prev_tools = []
|
||||
for _m in reversed(messages):
|
||||
if _m.get("role") == "assistant" and _m.get("tool_calls"):
|
||||
prev_tools = [
|
||||
tc["function"]["name"]
|
||||
for tc in _m["tool_calls"]
|
||||
if isinstance(tc, dict)
|
||||
]
|
||||
break
|
||||
self.step_callback(api_call_count, prev_tools)
|
||||
except Exception as _step_err:
|
||||
logger.debug("step_callback error (iteration %s): %s", api_call_count, _step_err)
|
||||
|
||||
# Track tool-calling iterations for skill nudge.
|
||||
# Counter resets whenever skill_manage is actually used.
|
||||
if (self._skill_nudge_interval > 0
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue