generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 617
feat(hooks): Add hook decorator #1581
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
Draft
mkmeral
wants to merge
11
commits into
strands-agents:main
Choose a base branch
from
mkmeral:fix/hook-decorator-review-fixes
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.
Draft
feat(hooks): Add hook decorator #1581
mkmeral
wants to merge
11
commits into
strands-agents:main
from
mkmeral:fix/hook-decorator-review-fixes
+930
−9
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
- 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.
- Fix mypy type errors by importing HookEvent and properly casting events - Add __get__ descriptor method to support class methods like @tool - Fix agent injection to validate event types at decoration time - Reject agent injection for multiagent events (BaseHookEvent without .agent) - Skip 'self' and 'cls' params when detecting event type for class methods - Remove version check for types.UnionType (SDK requires Python 3.10+) - Add comprehensive tests for new functionality Issues fixed: 1. Mypy type errors accessing event.agent on BaseHookEvent 2. Missing descriptor protocol for class method support 3. Agent injection failing at runtime for multiagent events 4. Merge conflicts with main branch (ModelRetryStrategy, multiagent events)
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Agent injection was unnecessary complexity - users can simply access event.agent directly when needed, which is consistent with how class-based HookProviders work. Changes: - Remove agent parameter detection and injection logic - Remove has_agent_param from HookMetadata - Simplify DecoratedFunctionHook (532 -> 327 lines) - Update tests to remove agent injection tests (53 -> 35 tests) - Add PR_DESCRIPTION.md
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.Motivation
Defining hooks currently requires implementing the
HookProviderprotocol with a class, which is verbose for simple use cases:The
@hookdecorator provides a simpler function-based approach that reduces boilerplate while maintaining full compatibility with the existing hooks system.Resolves: #1483
Public API Changes
New
@hookdecorator exported fromstrandsandstrands.hooks:The decorator supports multiple usage patterns:
Agent injection is available for hooks handling
HookEventsubclasses:Related Issues
Fixes #1483
Documentation PR
No documentation changes required.
Type of Change
New feature
Testing
hatch run prepareChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.