-
Notifications
You must be signed in to change notification settings - Fork 6k
Lorenze/feat hooks #3902
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
Merged
Merged
Lorenze/feat hooks #3902
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3d708e2
feat: implement LLM call hooks and enhance agent execution context
lorenzejay 946532e
feat: implement LLM call hooks and enhance agent execution context
lorenzejay 152ef0b
fix verbose
lorenzejay b157b93
feat: introduce crew-scoped hook decorators and refactor hook registr…
lorenzejay 0364138
feat: enhance hook management with clear and unregister functions
lorenzejay be15318
refactor: enhance hook type management for LLM and tool hooks
lorenzejay 7bca00d
feat: add execution and tool hooks documentation
lorenzejay 2230fb8
Merge branch 'main' into lorenze/feat-hooks
greysonlalonde File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| from __future__ import annotations | ||
|
|
||
| # LLM Hooks | ||
| from crewai.hooks.llm_hooks import ( | ||
| LLMCallHookContext, | ||
| get_after_llm_call_hooks, | ||
| get_before_llm_call_hooks, | ||
| register_after_llm_call_hook, | ||
| register_before_llm_call_hook, | ||
| ) | ||
|
|
||
| # Tool Hooks | ||
| from crewai.hooks.tool_hooks import ( | ||
| ToolCallHookContext, | ||
| get_after_tool_call_hooks, | ||
| get_before_tool_call_hooks, | ||
| register_after_tool_call_hook, | ||
| register_before_tool_call_hook, | ||
| ) | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "LLMCallHookContext", | ||
| "ToolCallHookContext", | ||
| "get_after_llm_call_hooks", | ||
| "get_after_tool_call_hooks", | ||
| "get_before_llm_call_hooks", | ||
| "get_before_tool_call_hooks", | ||
| "register_after_llm_call_hook", | ||
| "register_after_tool_call_hook", | ||
| "register_before_llm_call_hook", | ||
| "register_before_tool_call_hook", | ||
| ] |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import TypeVar | ||
|
|
||
|
|
||
| # Type variable for hook context types | ||
| HookContextT = TypeVar("HookContextT") | ||
|
|
||
|
|
||
| def validate_hook_callable(hook: object, hook_type: str) -> None: | ||
| """Validate that a hook is callable. | ||
|
|
||
| Args: | ||
| hook: The hook object to validate | ||
| hook_type: Description of the hook type for error messages | ||
|
|
||
| Raises: | ||
| TypeError: If the hook is not callable | ||
| """ | ||
| if not callable(hook): | ||
| raise TypeError(f"{hook_type} must be callable, got {type(hook).__name__}") | ||
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
greysonlalonde marked this conversation as resolved.
Show resolved
Hide resolved
|
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Callable | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from crewai.events.event_listener import event_listener | ||
| from crewai.utilities.printer import Printer | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from crewai.agent import Agent | ||
| from crewai.agents.agent_builder.base_agent import BaseAgent | ||
| from crewai.crew import Crew | ||
| from crewai.task import Task | ||
| from crewai.tools.structured_tool import CrewStructuredTool | ||
|
|
||
|
|
||
| class ToolCallHookContext: | ||
| """Context object passed to tool call hooks. | ||
|
|
||
| Provides hooks with access to the tool being called, its input, | ||
| the agent/task/crew context, and the result (for after hooks). | ||
|
|
||
| Attributes: | ||
| tool_name: Name of the tool being called | ||
| tool_input: Tool input parameters (mutable dict). | ||
| Can be modified in-place by before_tool_call hooks. | ||
| IMPORTANT: Modify in-place (e.g., context.tool_input['key'] = value). | ||
| Do NOT replace the dict (e.g., context.tool_input = {}), as this | ||
| will not affect the actual tool execution. | ||
| tool: Reference to the CrewStructuredTool instance | ||
| agent: Agent executing the tool (may be None) | ||
| task: Current task being executed (may be None) | ||
| crew: Crew instance (may be None) | ||
| tool_result: Tool execution result (only set for after_tool_call hooks). | ||
| Can be modified by returning a new string from after_tool_call hook. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| tool_name: str, | ||
| tool_input: dict[str, Any], | ||
| tool: CrewStructuredTool, | ||
| agent: Agent | BaseAgent | None = None, | ||
| task: Task | None = None, | ||
| crew: Crew | None = None, | ||
| tool_result: str | None = None, | ||
| ) -> None: | ||
| """Initialize tool call hook context. | ||
|
|
||
| Args: | ||
| tool_name: Name of the tool being called | ||
| tool_input: Tool input parameters (mutable) | ||
| tool: Tool instance reference | ||
| agent: Optional agent executing the tool | ||
| task: Optional current task | ||
| crew: Optional crew instance | ||
| tool_result: Optional tool result (for after hooks) | ||
| """ | ||
| self.tool_name = tool_name | ||
| self.tool_input = tool_input | ||
| self.tool = tool | ||
| self.agent = agent | ||
| self.task = task | ||
| self.crew = crew | ||
| self.tool_result = tool_result | ||
|
|
||
| def request_human_input( | ||
| self, | ||
| prompt: str, | ||
| default_message: str = "Press Enter to continue, or provide feedback:", | ||
| ) -> str: | ||
| """Request human input during tool hook execution. | ||
|
|
||
| This method pauses live console updates, displays a prompt to the user, | ||
| waits for their input, and then resumes live updates. This is useful for | ||
| approval gates, reviewing tool results, or getting human feedback during execution. | ||
|
|
||
| Args: | ||
| prompt: Custom message to display to the user | ||
| default_message: Message shown after the prompt | ||
|
|
||
| Returns: | ||
| User's input as a string (empty string if just Enter pressed) | ||
|
|
||
| Example: | ||
| >>> def approval_hook(context: ToolCallHookContext) -> bool | None: | ||
| ... if context.tool_name == "delete_file": | ||
| ... response = context.request_human_input( | ||
| ... prompt="Allow file deletion?", | ||
| ... default_message="Type 'approve' to continue:", | ||
| ... ) | ||
| ... if response.lower() != "approve": | ||
| ... return False # Block execution | ||
| ... return None # Allow execution | ||
| """ | ||
|
|
||
| printer = Printer() | ||
| event_listener.formatter.pause_live_updates() | ||
|
|
||
| try: | ||
| printer.print(content=f"\n{prompt}", color="bold_yellow") | ||
| printer.print(content=default_message, color="cyan") | ||
| response = input().strip() | ||
|
|
||
| if response: | ||
| printer.print(content="\nProcessing your input...", color="cyan") | ||
|
|
||
| return response | ||
| finally: | ||
| event_listener.formatter.resume_live_updates() | ||
|
|
||
|
|
||
| # Global hook registries | ||
| _before_tool_call_hooks: list[Callable[[ToolCallHookContext], bool | None]] = [] | ||
| _after_tool_call_hooks: list[Callable[[ToolCallHookContext], str | None]] = [] | ||
|
|
||
|
|
||
| def register_before_tool_call_hook( | ||
| hook: Callable[[ToolCallHookContext], bool | None], | ||
| ) -> None: | ||
| """Register a global before_tool_call hook. | ||
|
|
||
| Global hooks are added to all tool executions automatically. | ||
| This is a convenience function for registering hooks that should | ||
| apply to all tool calls across all agents and crews. | ||
|
|
||
| Args: | ||
| hook: Function that receives ToolCallHookContext and can: | ||
| - Modify tool_input in-place | ||
| - Return False to block tool execution | ||
| - Return True or None to allow execution | ||
| IMPORTANT: Modify tool_input in-place (e.g., context.tool_input['key'] = value). | ||
| Do NOT replace the dict (context.tool_input = {}), as this will not affect | ||
| the actual tool execution. | ||
|
|
||
| Example: | ||
| >>> def log_tool_usage(context: ToolCallHookContext) -> None: | ||
| ... print(f"Executing tool: {context.tool_name}") | ||
| ... print(f"Input: {context.tool_input}") | ||
| ... return None # Allow execution | ||
| >>> | ||
| >>> register_before_tool_call_hook(log_tool_usage) | ||
|
|
||
| >>> def block_dangerous_tools(context: ToolCallHookContext) -> bool | None: | ||
| ... if context.tool_name == "delete_database": | ||
| ... print("Blocked dangerous tool execution!") | ||
| ... return False # Block execution | ||
| ... return None # Allow execution | ||
| >>> | ||
| >>> register_before_tool_call_hook(block_dangerous_tools) | ||
| """ | ||
| _before_tool_call_hooks.append(hook) | ||
|
|
||
|
|
||
| def register_after_tool_call_hook( | ||
| hook: Callable[[ToolCallHookContext], str | None], | ||
| ) -> None: | ||
| """Register a global after_tool_call hook. | ||
|
|
||
| Global hooks are added to all tool executions automatically. | ||
| This is a convenience function for registering hooks that should | ||
| apply to all tool calls across all agents and crews. | ||
|
|
||
| Args: | ||
| hook: Function that receives ToolCallHookContext and can modify | ||
| the tool result. Return modified result string or None to keep | ||
| the original result. The tool_result is available in context.tool_result. | ||
|
|
||
| Example: | ||
| >>> def sanitize_output(context: ToolCallHookContext) -> str | None: | ||
| ... if context.tool_result and "SECRET_KEY" in context.tool_result: | ||
| ... return context.tool_result.replace("SECRET_KEY=...", "[REDACTED]") | ||
| ... return None # Keep original result | ||
| >>> | ||
| >>> register_after_tool_call_hook(sanitize_output) | ||
|
|
||
| >>> def log_tool_results(context: ToolCallHookContext) -> None: | ||
| ... print(f"Tool {context.tool_name} returned: {context.tool_result[:100]}") | ||
| ... return None # Keep original result | ||
| >>> | ||
| >>> register_after_tool_call_hook(log_tool_results) | ||
| """ | ||
| _after_tool_call_hooks.append(hook) | ||
|
|
||
|
|
||
| def get_before_tool_call_hooks() -> list[Callable[[ToolCallHookContext], bool | None]]: | ||
| """Get all registered global before_tool_call hooks. | ||
|
|
||
| Returns: | ||
| List of registered before hooks | ||
| """ | ||
| return _before_tool_call_hooks.copy() | ||
|
|
||
|
|
||
| def get_after_tool_call_hooks() -> list[Callable[[ToolCallHookContext], str | None]]: | ||
| """Get all registered global after_tool_call hooks. | ||
|
|
||
| Returns: | ||
| List of registered after hooks | ||
| """ | ||
| return _after_tool_call_hooks.copy() |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.