strands.hooks
¶
Typed hook system for extending agent functionality.
This module provides a composable mechanism for building objects that can hook into specific events during the agent lifecycle. The hook system enables both built-in SDK components and user code to react to or modify agent behavior through strongly-typed event callbacks.
Example Usage
from strands.hooks import HookProvider, HookRegistry
from strands.hooks.events import StartRequestEvent, EndRequestEvent
class LoggingHooks(HookProvider):
def register_hooks(self, registry: HookRegistry) -> None:
registry.add_callback(StartRequestEvent, self.log_start)
registry.add_callback(EndRequestEvent, self.log_end)
def log_start(self, event: StartRequestEvent) -> None:
print(f"Request started for {event.agent.name}")
def log_end(self, event: EndRequestEvent) -> None:
print(f"Request completed for {event.agent.name}")
# Use with agent
agent = Agent(hooks=[LoggingHooks()])
This replaces the older callback_handler approach with a more composable, type-safe system that supports multiple subscribers per event type.
strands.hooks.events
¶
Hook events emitted as part of invoking Agents.
This module defines the events that are emitted as Agents run through the lifecycle of a request.
AfterInvocationEvent
dataclass
¶
Bases: HookEvent
Event triggered at the end of an agent request.
This event is fired after the agent has completed processing a request, regardless of whether it completed successfully or encountered an error. Hook providers can use this event for cleanup, logging, or state persistence.
Note: This event uses reverse callback ordering, meaning callbacks registered later will be invoked first during cleanup.
This event is triggered at the end of the following api calls
- Agent.call
- Agent.stream_async
- Agent.structured_output
Source code in strands/hooks/events.py
should_reverse_callbacks
property
¶
True to invoke callbacks in reverse order.
AgentInitializedEvent
dataclass
¶
Bases: HookEvent
Event triggered when an agent has finished initialization.
This event is fired after the agent has been fully constructed and all built-in components have been initialized. Hook providers can use this event to perform setup tasks that require a fully initialized agent.
Source code in strands/hooks/events.py
BeforeInvocationEvent
dataclass
¶
Bases: HookEvent
Event triggered at the beginning of a new agent request.
This event is fired before the agent begins processing a new user request, before any model inference or tool execution occurs. Hook providers can use this event to perform request-level setup, logging, or validation.
This event is triggered at the beginning of the following api calls
- Agent.call
- Agent.stream_async
- Agent.structured_output
Source code in strands/hooks/events.py
MessageAddedEvent
dataclass
¶
Bases: HookEvent
Event triggered when a message is added to the agent's conversation.
This event is fired whenever the agent adds a new message to its internal message history, including user messages, assistant responses, and tool results. Hook providers can use this event for logging, monitoring, or implementing custom message processing logic.
Note: This event is only triggered for messages added by the framework itself, not for messages manually added by tools or external code.
Attributes:
Name | Type | Description |
---|---|---|
message |
Message
|
The message that was added to the conversation history. |
Source code in strands/hooks/events.py
strands.hooks.registry
¶
Hook registry system for managing event callbacks in the Strands Agent SDK.
This module provides the core infrastructure for the typed hook system, enabling composable extension of agent functionality through strongly-typed event callbacks. The registry manages the mapping between event types and their associated callback functions, supporting both individual callback registration and bulk registration via hook provider objects.
TEvent = TypeVar('TEvent', bound=HookEvent, contravariant=True)
module-attribute
¶
Generic for adding callback handlers - contravariant to allow adding handlers which take in base classes.
TInvokeEvent = TypeVar('TInvokeEvent', bound=HookEvent)
module-attribute
¶
Generic for invoking events - non-contravariant to enable returning events.
HookCallback
¶
Bases: Protocol
, Generic[TEvent]
Protocol for callback functions that handle hook events.
Hook callbacks are functions that receive a single strongly-typed event argument and perform some action in response. They should not return values and any exceptions they raise will propagate to the caller.
Example
Source code in strands/hooks/registry.py
HookEvent
dataclass
¶
Base class for all hook events.
Attributes:
Name | Type | Description |
---|---|---|
agent |
Agent
|
The agent instance that triggered this event. |
Source code in strands/hooks/registry.py
should_reverse_callbacks
property
¶
Determine if callbacks for this event should be invoked in reverse order.
Returns:
Type | Description |
---|---|
bool
|
False by default. Override to return True for events that should |
bool
|
invoke callbacks in reverse order (e.g., cleanup/teardown events). |
__post_init__()
¶
Disallow writes to non-approved properties.
Source code in strands/hooks/registry.py
__setattr__(name, value)
¶
Prevent setting attributes on hook events.
Raises:
Type | Description |
---|---|
AttributeError
|
Always raised to prevent setting attributes on hook events. |
Source code in strands/hooks/registry.py
HookProvider
¶
Bases: Protocol
Protocol for objects that provide hook callbacks to an agent.
Hook providers offer a composable way to extend agent functionality by subscribing to various events in the agent lifecycle. This protocol enables building reusable components that can hook into agent events.
Example
Source code in strands/hooks/registry.py
register_hooks(registry, **kwargs)
¶
Register callback functions for specific event types.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
registry
|
HookRegistry
|
The hook registry to register callbacks with. |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/hooks/registry.py
HookRegistry
¶
Registry for managing hook callbacks associated with event types.
The HookRegistry maintains a mapping of event types to callback functions and provides methods for registering callbacks and invoking them when events occur.
The registry handles callback ordering, including reverse ordering for cleanup events, and provides type-safe event dispatching.
Source code in strands/hooks/registry.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
|
__init__()
¶
add_callback(event_type, callback)
¶
Register a callback function for a specific event type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_type
|
Type[TEvent]
|
The class type of events this callback should handle. |
required |
callback
|
HookCallback[TEvent]
|
The callback function to invoke when events of this type occur. |
required |
Example
Source code in strands/hooks/registry.py
add_hook(hook)
¶
Register all callbacks from a hook provider.
This method allows bulk registration of callbacks by delegating to the hook provider's register_hooks method. This is the preferred way to register multiple related callbacks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hook
|
HookProvider
|
The hook provider containing callbacks to register. |
required |
Example
Source code in strands/hooks/registry.py
get_callbacks_for(event)
¶
Get callbacks registered for the given event in the appropriate order.
This method returns callbacks in registration order for normal events, or reverse registration order for events that have should_reverse_callbacks=True. This enables proper cleanup ordering for teardown events.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TEvent
|
The event to get callbacks for. |
required |
Yields:
Type | Description |
---|---|
HookCallback[TEvent]
|
Callback functions registered for this event type, in the appropriate order. |
Example
Source code in strands/hooks/registry.py
has_callbacks()
¶
Check if the registry has any registered callbacks.
Returns:
Type | Description |
---|---|
bool
|
True if there are any registered callbacks, False otherwise. |
Source code in strands/hooks/registry.py
invoke_callbacks(event)
¶
Invoke all registered callbacks for the given event.
This method finds all callbacks registered for the event's type and invokes them in the appropriate order. For events with should_reverse_callbacks=True, callbacks are invoked in reverse registration order. Any exceptions raised by callback functions will propagate to the caller.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TInvokeEvent
|
The event to dispatch to registered callbacks. |
required |
Returns:
Type | Description |
---|---|
TInvokeEvent
|
The event dispatched to registered callbacks. |