Skip to main content
Hooking functions are extension points that let you customize agent behavior at specific execution points without modifying the agent’s core code.

Logging and Monitoring

Log the agent’s internal state, reasoning process, and actions for debugging and analysis.

Customizing Behavior

Modify or intercept the input/output of core functions to extend or override agent behavior.
In AgentScope, hooking functions attach to the following core agent functions:

Hooking Signature

To simplify the usage, AgentScope provides unified signatures for all hooks.

Pre-hooks

All the pre-hooks have the same signature: A pre-hook template looks like this:

Post-hooks

All post-hooks have an additional output argument, which is the output of the core function or the previous hook. If the core function has no output, the output will be None. The post-hook template looks like this:

Hook Management

Registration and Execution

AgentScope provides the following APIs to manage the hooking functions: Once registered, the hooks will be executed automatically at the corresponding execution points of the core functions. Execution order:
  • Hooks are executed in registration order.
  • Multiple hooks can be chained together.
Return value handling:
  • For pre-hooks, non-None return values are passed to the next hook or core function, that is
    • When a hook returns None, the next hook will use the most recent non-None return value from previous hooks
    • If all previous hooks return None, the next hook receives a copy of the original arguments
    • The final non-None return value (or original arguments if all hooks return None) is passed to the core function
  • The post-hooks works similarly as the pre-hooks.
Never call a core function (reply, observe, _reasoning, _acting) from within a hook — doing so creates an infinite loop.

Example

Tasking the pre-reply hook as an example, we first create a hook function that modifies the input messages before replying:
Then we can register the hook function to a specific agent instance:
Now, when the agent is called to reply a message, the instance_pre_reply_hook will be executed before the reply, and the message content will be modified accordingly.