generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 604
feat(hooks): add @hook decorator for simplified hook definitions #1484
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
strands-agent
wants to merge
4
commits into
strands-agents:main
Choose a base branch
from
strands-agent:feat/hook-decorator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat(hooks): add @hook decorator for simplified hook definitions #1484
strands-agent
wants to merge
4
commits into
strands-agents:main
from
strands-agent:feat/hook-decorator
+1,289
−4
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This adds a @hook decorator that transforms Python functions into HookProvider implementations with automatic event type detection from type hints - mirroring the ergonomics of the existing @tool decorator. Features: - Simple decorator syntax: @hook - Automatic event type extraction from type hints - Explicit event type specification: @hook(event=EventType) - Multi-event support: @hook(events=[...]) or Union types - Support for both sync and async hook functions - Preserves function metadata (name, docstring) - Direct invocation for testing New exports: - from strands import hook - from strands.hooks import hook, DecoratedFunctionHook, FunctionHookMetadata, HookMetadata Example: from strands import Agent, hook from strands.hooks import BeforeToolCallEvent @hook def log_tool_calls(event: BeforeToolCallEvent) -> None: print(f'Tool: {event.tool_use}') agent = Agent(hooks=[log_tool_calls]) Fixes strands-agents#1483
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
- Add cast() for HookCallback type in register_hooks method - Add HookCallback import from registry - Use keyword-only arguments in overload signature 2 to satisfy mypy
This enhancement addresses feedback from @cagataycali - the agent instance is now automatically injected to @hook decorated functions when they have an 'agent' parameter in their signature. Usage: @hook def my_hook(event: BeforeToolCallEvent, agent: Agent) -> None: # agent is automatically injected from event.agent print(f'Agent {agent.name} calling tool') Features: - Detect 'agent' parameter in function signature - Automatically extract agent from event.agent when callback is invoked - Works with both sync and async hooks - Backward compatible - hooks without agent param work unchanged - Direct invocation supports explicit agent override for testing Tests added: - test_agent_param_detection - test_agent_injection_in_repr - test_hook_without_agent_param_not_injected - test_hook_with_agent_param_receives_agent - test_direct_call_with_explicit_agent - test_agent_injection_with_registry - test_async_hook_with_agent_injection - test_hook_metadata_includes_agent_param - test_mixed_hooks_with_and_without_agent
Add 13 new test cases to improve code coverage from 89% to 98%: - TestCoverageGaps: Optional type hint, async/sync agent injection via registry, direct call without agent param, hook() empty parentheses, Union types - TestAdditionalErrorCases: Invalid annotation types, invalid explicit event list - TestEdgeCases: get_type_hints exception fallback, empty type hints fallback Coverage improvements: - Lines 139-141: get_type_hints exception handling - Line 157: Annotation fallback when type hints unavailable - Lines 203-205: NoneType skipping in Optional[X] - Line 216: Invalid annotation error path - Lines 313-320: Async/sync callback with agent injection Addresses codecov patch coverage failure in PR strands-agents#1484.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR adds a
@hookdecorator that transforms Python functions intoHookProviderimplementations with automatic event type detection from type hints - mirroring the ergonomics of the existing@tooldecorator.Features
@hookextracts event type from type hints@hook(event=EventType)for functions without type hints@hook(events=[...])or Union types (A | B)functools.wrapsBefore (Class-based):
After (Decorator-based):
New Exports
Related Issues
Fixes #1483
Documentation PR
No documentation changes required - follows existing patterns established by
@tool.Type of Change
New feature (non-breaking addition)
Testing
hatch run prepareChecklist
__init__.py)