mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-09 08:08:32 +00:00
Lorenze/feat hooks (#3902)
* feat: implement LLM call hooks and enhance agent execution context - Introduced LLM call hooks to allow modification of messages and responses during LLM interactions. - Added support for before and after hooks in the CrewAgentExecutor, enabling dynamic adjustments to the execution flow. - Created LLMCallHookContext for comprehensive access to the executor state, facilitating in-place modifications. - Added validation for hook callables to ensure proper functionality. - Enhanced tests for LLM hooks and tool hooks to verify their behavior and error handling capabilities. - Updated LiteAgent and CrewAgentExecutor to accommodate the new crew context in their execution processes. * feat: implement LLM call hooks and enhance agent execution context - Introduced LLM call hooks to allow modification of messages and responses during LLM interactions. - Added support for before and after hooks in the CrewAgentExecutor, enabling dynamic adjustments to the execution flow. - Created LLMCallHookContext for comprehensive access to the executor state, facilitating in-place modifications. - Added validation for hook callables to ensure proper functionality. - Enhanced tests for LLM hooks and tool hooks to verify their behavior and error handling capabilities. - Updated LiteAgent and CrewAgentExecutor to accommodate the new crew context in their execution processes. * fix verbose * feat: introduce crew-scoped hook decorators and refactor hook registration - Added decorators for before and after LLM and tool calls to enhance flexibility in modifying execution behavior. - Implemented a centralized hook registration mechanism within CrewBase to automatically register crew-scoped hooks. - Removed the obsolete base.py file as its functionality has been integrated into the new decorators and registration system. - Enhanced tests for the new hook decorators to ensure proper registration and execution flow. - Updated existing hook handling to accommodate the new decorator-based approach, improving code organization and maintainability. * feat: enhance hook management with clear and unregister functions - Introduced functions to unregister specific before and after hooks for both LLM and tool calls, improving flexibility in hook management. - Added clear functions to remove all registered hooks of each type, facilitating easier state management and cleanup. - Implemented a convenience function to clear all global hooks in one call, streamlining the process for testing and execution context resets. - Enhanced tests to verify the functionality of unregistering and clearing hooks, ensuring robust behavior in various scenarios. * refactor: enhance hook type management for LLM and tool hooks - Updated hook type definitions to use generic protocols for better type safety and flexibility. - Replaced Callable type annotations with specific BeforeLLMCallHookType and AfterLLMCallHookType for clarity. - Improved the registration and retrieval functions for before and after hooks to align with the new type definitions. - Enhanced the setup functions to handle hook execution results, allowing for blocking of LLM calls based on hook logic. - Updated related tests to ensure proper functionality and type adherence across the hook management system. * feat: add execution and tool hooks documentation - Introduced new documentation for execution hooks, LLM call hooks, and tool call hooks to provide comprehensive guidance on their usage and implementation in CrewAI. - Updated existing documentation to include references to the new hooks, enhancing the learning resources available for users. - Ensured consistency across multiple languages (English, Portuguese, Korean) for the new documentation, improving accessibility for a wider audience. - Added examples and troubleshooting sections to assist users in effectively utilizing hooks for agent operations. --------- Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
This commit is contained in:
@@ -313,7 +313,10 @@
|
||||
"en/learn/multimodal-agents",
|
||||
"en/learn/replay-tasks-from-latest-crew-kickoff",
|
||||
"en/learn/sequential-process",
|
||||
"en/learn/using-annotations"
|
||||
"en/learn/using-annotations",
|
||||
"en/learn/execution-hooks",
|
||||
"en/learn/llm-hooks",
|
||||
"en/learn/tool-hooks"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -737,7 +740,10 @@
|
||||
"pt-BR/learn/multimodal-agents",
|
||||
"pt-BR/learn/replay-tasks-from-latest-crew-kickoff",
|
||||
"pt-BR/learn/sequential-process",
|
||||
"pt-BR/learn/using-annotations"
|
||||
"pt-BR/learn/using-annotations",
|
||||
"pt-BR/learn/execution-hooks",
|
||||
"pt-BR/learn/llm-hooks",
|
||||
"pt-BR/learn/tool-hooks"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1170,7 +1176,10 @@
|
||||
"ko/learn/multimodal-agents",
|
||||
"ko/learn/replay-tasks-from-latest-crew-kickoff",
|
||||
"ko/learn/sequential-process",
|
||||
"ko/learn/using-annotations"
|
||||
"ko/learn/using-annotations",
|
||||
"ko/learn/execution-hooks",
|
||||
"ko/learn/llm-hooks",
|
||||
"ko/learn/tool-hooks"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
522
docs/en/learn/execution-hooks.mdx
Normal file
522
docs/en/learn/execution-hooks.mdx
Normal file
@@ -0,0 +1,522 @@
|
||||
---
|
||||
title: Execution Hooks Overview
|
||||
description: Understanding and using execution hooks in CrewAI for fine-grained control over agent operations
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Execution Hooks provide fine-grained control over the runtime behavior of your CrewAI agents. Unlike kickoff hooks that run before and after crew execution, execution hooks intercept specific operations during agent execution, allowing you to modify behavior, implement safety checks, and add comprehensive monitoring.
|
||||
|
||||
## Types of Execution Hooks
|
||||
|
||||
CrewAI provides two main categories of execution hooks:
|
||||
|
||||
### 1. [LLM Call Hooks](/learn/llm-hooks)
|
||||
|
||||
Control and monitor language model interactions:
|
||||
- **Before LLM Call**: Modify prompts, validate inputs, implement approval gates
|
||||
- **After LLM Call**: Transform responses, sanitize outputs, update conversation history
|
||||
|
||||
**Use Cases:**
|
||||
- Iteration limiting
|
||||
- Cost tracking and token usage monitoring
|
||||
- Response sanitization and content filtering
|
||||
- Human-in-the-loop approval for LLM calls
|
||||
- Adding safety guidelines or context
|
||||
- Debug logging and request/response inspection
|
||||
|
||||
[View LLM Hooks Documentation →](/learn/llm-hooks)
|
||||
|
||||
### 2. [Tool Call Hooks](/learn/tool-hooks)
|
||||
|
||||
Control and monitor tool execution:
|
||||
- **Before Tool Call**: Modify inputs, validate parameters, block dangerous operations
|
||||
- **After Tool Call**: Transform results, sanitize outputs, log execution details
|
||||
|
||||
**Use Cases:**
|
||||
- Safety guardrails for destructive operations
|
||||
- Human approval for sensitive actions
|
||||
- Input validation and sanitization
|
||||
- Result caching and rate limiting
|
||||
- Tool usage analytics
|
||||
- Debug logging and monitoring
|
||||
|
||||
[View Tool Hooks Documentation →](/learn/tool-hooks)
|
||||
|
||||
## Hook Registration Methods
|
||||
|
||||
### 1. Decorator-Based Hooks (Recommended)
|
||||
|
||||
The cleanest and most Pythonic way to register hooks:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call, before_tool_call, after_tool_call
|
||||
|
||||
@before_llm_call
|
||||
def limit_iterations(context):
|
||||
"""Prevent infinite loops by limiting iterations."""
|
||||
if context.iterations > 10:
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
"""Remove sensitive data from LLM responses."""
|
||||
if "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
"""Block destructive operations."""
|
||||
if context.tool_name == "delete_database":
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def log_tool_result(context):
|
||||
"""Log tool execution."""
|
||||
print(f"Tool {context.tool_name} completed")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Crew-Scoped Hooks
|
||||
|
||||
Apply hooks only to specific crew instances:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# Only applies to this crew
|
||||
print(f"LLM call in {self.__class__.__name__}")
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_results(self, context):
|
||||
# Crew-specific logging
|
||||
print(f"Tool result: {context.tool_result[:50]}...")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential
|
||||
)
|
||||
```
|
||||
|
||||
## Hook Execution Flow
|
||||
|
||||
### LLM Call Flow
|
||||
|
||||
```
|
||||
Agent needs to call LLM
|
||||
↓
|
||||
[Before LLM Call Hooks Execute]
|
||||
├→ Hook 1: Validate iteration count
|
||||
├→ Hook 2: Add safety context
|
||||
└→ Hook 3: Log request
|
||||
↓
|
||||
If any hook returns False:
|
||||
├→ Block LLM call
|
||||
└→ Raise ValueError
|
||||
↓
|
||||
If all hooks return True/None:
|
||||
├→ LLM call proceeds
|
||||
└→ Response generated
|
||||
↓
|
||||
[After LLM Call Hooks Execute]
|
||||
├→ Hook 1: Sanitize response
|
||||
├→ Hook 2: Log response
|
||||
└→ Hook 3: Update metrics
|
||||
↓
|
||||
Final response returned
|
||||
```
|
||||
|
||||
### Tool Call Flow
|
||||
|
||||
```
|
||||
Agent needs to execute tool
|
||||
↓
|
||||
[Before Tool Call Hooks Execute]
|
||||
├→ Hook 1: Check if tool is allowed
|
||||
├→ Hook 2: Validate inputs
|
||||
└→ Hook 3: Request approval if needed
|
||||
↓
|
||||
If any hook returns False:
|
||||
├→ Block tool execution
|
||||
└→ Return error message
|
||||
↓
|
||||
If all hooks return True/None:
|
||||
├→ Tool execution proceeds
|
||||
└→ Result generated
|
||||
↓
|
||||
[After Tool Call Hooks Execute]
|
||||
├→ Hook 1: Sanitize result
|
||||
├→ Hook 2: Cache result
|
||||
└→ Hook 3: Log metrics
|
||||
↓
|
||||
Final result returned
|
||||
```
|
||||
|
||||
## Hook Context Objects
|
||||
|
||||
### LLMCallHookContext
|
||||
|
||||
Provides access to LLM execution state:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # Full executor access
|
||||
messages: list # Mutable message list
|
||||
agent: Agent # Current agent
|
||||
task: Task # Current task
|
||||
crew: Crew # Crew instance
|
||||
llm: BaseLLM # LLM instance
|
||||
iterations: int # Current iteration
|
||||
response: str | None # LLM response (after hooks)
|
||||
```
|
||||
|
||||
### ToolCallHookContext
|
||||
|
||||
Provides access to tool execution state:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # Tool being called
|
||||
tool_input: dict # Mutable input parameters
|
||||
tool: CrewStructuredTool # Tool instance
|
||||
agent: Agent | None # Agent executing
|
||||
task: Task | None # Current task
|
||||
crew: Crew | None # Crew instance
|
||||
tool_result: str | None # Tool result (after hooks)
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Safety and Validation
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context):
|
||||
"""Block destructive operations."""
|
||||
dangerous = ['delete_file', 'drop_table', 'system_shutdown']
|
||||
if context.tool_name in dangerous:
|
||||
print(f"🛑 Blocked: {context.tool_name}")
|
||||
return False
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def iteration_limit(context):
|
||||
"""Prevent infinite loops."""
|
||||
if context.iterations > 15:
|
||||
print("⛔ Maximum iterations exceeded")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### Human-in-the-Loop
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval(context):
|
||||
"""Require approval for sensitive operations."""
|
||||
sensitive = ['send_email', 'make_payment', 'post_message']
|
||||
|
||||
if context.tool_name in sensitive:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Approve {context.tool_name}?",
|
||||
default_message="Type 'yes' to approve:"
|
||||
)
|
||||
|
||||
if response.lower() != 'yes':
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Monitoring and Analytics
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
metrics = defaultdict(lambda: {'count': 0, 'total_time': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context):
|
||||
context.tool_input['_start'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_metrics(context):
|
||||
start = context.tool_input.get('_start', time.time())
|
||||
duration = time.time() - start
|
||||
|
||||
metrics[context.tool_name]['count'] += 1
|
||||
metrics[context.tool_name]['total_time'] += duration
|
||||
|
||||
return None
|
||||
|
||||
# View metrics
|
||||
def print_metrics():
|
||||
for tool, data in metrics.items():
|
||||
avg = data['total_time'] / data['count']
|
||||
print(f"{tool}: {data['count']} calls, {avg:.2f}s avg")
|
||||
```
|
||||
|
||||
### Response Sanitization
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_llm_response(context):
|
||||
"""Remove sensitive data from LLM responses."""
|
||||
if not context.response:
|
||||
return None
|
||||
|
||||
result = context.response
|
||||
result = re.sub(r'(api[_-]?key)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r'\1: [REDACTED]', result, flags=re.IGNORECASE)
|
||||
return result
|
||||
|
||||
@after_tool_call
|
||||
def sanitize_tool_result(context):
|
||||
"""Remove sensitive data from tool results."""
|
||||
if not context.tool_result:
|
||||
return None
|
||||
|
||||
result = context.tool_result
|
||||
result = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
'[EMAIL-REDACTED]', result)
|
||||
return result
|
||||
```
|
||||
|
||||
## Hook Management
|
||||
|
||||
### Clearing All Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
# Clear all hooks at once
|
||||
result = clear_all_global_hooks()
|
||||
print(f"Cleared {result['total']} hooks")
|
||||
# Output: {'llm_hooks': (2, 1), 'tool_hooks': (1, 2), 'total': (3, 3)}
|
||||
```
|
||||
|
||||
### Clearing Specific Hook Types
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks
|
||||
)
|
||||
|
||||
# Clear specific types
|
||||
llm_before_count = clear_before_llm_call_hooks()
|
||||
tool_after_count = clear_after_tool_call_hooks()
|
||||
```
|
||||
|
||||
### Unregistering Individual Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_tool_call_hook
|
||||
)
|
||||
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
# Register
|
||||
register_before_llm_call_hook(my_hook)
|
||||
|
||||
# Later, unregister
|
||||
success = unregister_before_llm_call_hook(my_hook)
|
||||
print(f"Unregistered: {success}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Keep Hooks Focused
|
||||
Each hook should have a single, clear responsibility:
|
||||
|
||||
```python
|
||||
# ✅ Good - focused responsibility
|
||||
@before_tool_call
|
||||
def validate_file_path(context):
|
||||
if context.tool_name == 'read_file':
|
||||
if '..' in context.tool_input.get('path', ''):
|
||||
return False
|
||||
return None
|
||||
|
||||
# ❌ Bad - too many responsibilities
|
||||
@before_tool_call
|
||||
def do_everything(context):
|
||||
# Validation + logging + metrics + approval...
|
||||
...
|
||||
```
|
||||
|
||||
### 2. Handle Errors Gracefully
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context):
|
||||
try:
|
||||
# Your logic
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Hook error: {e}")
|
||||
return None # Allow execution despite error
|
||||
```
|
||||
|
||||
### 3. Modify Context In-Place
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
@before_llm_call
|
||||
def add_context(context):
|
||||
context.messages.append({"role": "system", "content": "Be concise"})
|
||||
|
||||
# ❌ Wrong - replaces reference
|
||||
@before_llm_call
|
||||
def wrong_approach(context):
|
||||
context.messages = [{"role": "system", "content": "Be concise"}]
|
||||
```
|
||||
|
||||
### 4. Use Type Hints
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, ToolCallHookContext
|
||||
|
||||
def my_llm_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# IDE autocomplete and type checking
|
||||
return None
|
||||
|
||||
def my_tool_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
```
|
||||
|
||||
### 5. Clean Up in Tests
|
||||
|
||||
```python
|
||||
import pytest
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_hooks():
|
||||
"""Reset hooks before each test."""
|
||||
yield
|
||||
clear_all_global_hooks()
|
||||
```
|
||||
|
||||
## When to Use Which Hook
|
||||
|
||||
### Use LLM Hooks When:
|
||||
- Implementing iteration limits
|
||||
- Adding context or safety guidelines to prompts
|
||||
- Tracking token usage and costs
|
||||
- Sanitizing or transforming responses
|
||||
- Implementing approval gates for LLM calls
|
||||
- Debugging prompt/response interactions
|
||||
|
||||
### Use Tool Hooks When:
|
||||
- Blocking dangerous or destructive operations
|
||||
- Validating tool inputs before execution
|
||||
- Implementing approval gates for sensitive actions
|
||||
- Caching tool results
|
||||
- Tracking tool usage and performance
|
||||
- Sanitizing tool outputs
|
||||
- Rate limiting tool calls
|
||||
|
||||
### Use Both When:
|
||||
Building comprehensive observability, safety, or approval systems that need to monitor all agent operations.
|
||||
|
||||
## Alternative Registration Methods
|
||||
|
||||
### Programmatic Registration (Advanced)
|
||||
|
||||
For dynamic hook registration or when you need to register hooks programmatically:
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
register_before_llm_call_hook,
|
||||
register_after_tool_call_hook
|
||||
)
|
||||
|
||||
def my_hook(context):
|
||||
return None
|
||||
|
||||
# Register programmatically
|
||||
register_before_llm_call_hook(my_hook)
|
||||
|
||||
# Useful for:
|
||||
# - Loading hooks from configuration
|
||||
# - Conditional hook registration
|
||||
# - Plugin systems
|
||||
```
|
||||
|
||||
**Note:** For most use cases, decorators are cleaner and more maintainable.
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Keep Hooks Fast**: Hooks execute on every call - avoid heavy computation
|
||||
2. **Cache When Possible**: Store expensive validations or lookups
|
||||
3. **Be Selective**: Use crew-scoped hooks when global hooks aren't needed
|
||||
4. **Monitor Hook Overhead**: Profile hook execution time in production
|
||||
5. **Lazy Import**: Import heavy dependencies only when needed
|
||||
|
||||
## Debugging Hooks
|
||||
|
||||
### Enable Debug Logging
|
||||
|
||||
```python
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@before_llm_call
|
||||
def debug_hook(context):
|
||||
logger.debug(f"LLM call: {context.agent.role}, iteration {context.iterations}")
|
||||
return None
|
||||
```
|
||||
|
||||
### Hook Execution Order
|
||||
|
||||
Hooks execute in registration order. If a before hook returns `False`, subsequent hooks don't execute:
|
||||
|
||||
```python
|
||||
# Register order matters!
|
||||
register_before_tool_call_hook(hook1) # Executes first
|
||||
register_before_tool_call_hook(hook2) # Executes second
|
||||
register_before_tool_call_hook(hook3) # Executes third
|
||||
|
||||
# If hook2 returns False:
|
||||
# - hook1 executed
|
||||
# - hook2 executed and returned False
|
||||
# - hook3 NOT executed
|
||||
# - Tool call blocked
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [LLM Call Hooks →](/learn/llm-hooks) - Detailed LLM hook documentation
|
||||
- [Tool Call Hooks →](/learn/tool-hooks) - Detailed tool hook documentation
|
||||
- [Before and After Kickoff Hooks →](/learn/before-and-after-kickoff-hooks) - Crew lifecycle hooks
|
||||
- [Human-in-the-Loop →](/learn/human-in-the-loop) - Human input patterns
|
||||
|
||||
## Conclusion
|
||||
|
||||
Execution hooks provide powerful control over agent runtime behavior. Use them to implement safety guardrails, approval workflows, comprehensive monitoring, and custom business logic. Combined with proper error handling, type safety, and performance considerations, hooks enable production-ready, secure, and observable agent systems.
|
||||
427
docs/en/learn/llm-hooks.mdx
Normal file
427
docs/en/learn/llm-hooks.mdx
Normal file
@@ -0,0 +1,427 @@
|
||||
---
|
||||
title: LLM Call Hooks
|
||||
description: Learn how to use LLM call hooks to intercept, modify, and control language model interactions in CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
LLM Call Hooks provide fine-grained control over language model interactions during agent execution. These hooks allow you to intercept LLM calls, modify prompts, transform responses, implement approval gates, and add custom logging or monitoring.
|
||||
|
||||
## Overview
|
||||
|
||||
LLM hooks are executed at two critical points:
|
||||
- **Before LLM Call**: Modify messages, validate inputs, or block execution
|
||||
- **After LLM Call**: Transform responses, sanitize outputs, or modify conversation history
|
||||
|
||||
## Hook Types
|
||||
|
||||
### Before LLM Call Hooks
|
||||
|
||||
Executed before every LLM call, these hooks can:
|
||||
- Inspect and modify messages sent to the LLM
|
||||
- Block LLM execution based on conditions
|
||||
- Implement rate limiting or approval gates
|
||||
- Add context or system messages
|
||||
- Log request details
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# Return False to block execution
|
||||
# Return True or None to allow execution
|
||||
...
|
||||
```
|
||||
|
||||
### After LLM Call Hooks
|
||||
|
||||
Executed after every LLM call, these hooks can:
|
||||
- Modify or sanitize LLM responses
|
||||
- Add metadata or formatting
|
||||
- Log response details
|
||||
- Update conversation history
|
||||
- Implement content filtering
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def after_hook(context: LLMCallHookContext) -> str | None:
|
||||
# Return modified response string
|
||||
# Return None to keep original response
|
||||
...
|
||||
```
|
||||
|
||||
## LLM Hook Context
|
||||
|
||||
The `LLMCallHookContext` object provides comprehensive access to execution state:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # Full executor reference
|
||||
messages: list # Mutable message list
|
||||
agent: Agent # Current agent
|
||||
task: Task # Current task
|
||||
crew: Crew # Crew instance
|
||||
llm: BaseLLM # LLM instance
|
||||
iterations: int # Current iteration count
|
||||
response: str | None # LLM response (after hooks only)
|
||||
```
|
||||
|
||||
### Modifying Messages
|
||||
|
||||
**Important:** Always modify messages in-place:
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
def add_context(context: LLMCallHookContext) -> None:
|
||||
context.messages.append({"role": "system", "content": "Be concise"})
|
||||
|
||||
# ❌ Wrong - replaces list reference
|
||||
def wrong_approach(context: LLMCallHookContext) -> None:
|
||||
context.messages = [{"role": "system", "content": "Be concise"}]
|
||||
```
|
||||
|
||||
## Registration Methods
|
||||
|
||||
### 1. Global Hook Registration
|
||||
|
||||
Register hooks that apply to all LLM calls across all crews:
|
||||
|
||||
```python
|
||||
from crewai.hooks import register_before_llm_call_hook, register_after_llm_call_hook
|
||||
|
||||
def log_llm_call(context):
|
||||
print(f"LLM call by {context.agent.role} at iteration {context.iterations}")
|
||||
return None # Allow execution
|
||||
|
||||
register_before_llm_call_hook(log_llm_call)
|
||||
```
|
||||
|
||||
### 2. Decorator-Based Registration
|
||||
|
||||
Use decorators for cleaner syntax:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call
|
||||
|
||||
@before_llm_call
|
||||
def validate_iteration_count(context):
|
||||
if context.iterations > 10:
|
||||
print("⚠️ Exceeded maximum iterations")
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
if context.response and "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Crew-Scoped Hooks
|
||||
|
||||
Register hooks for a specific crew instance:
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# Only applies to this crew
|
||||
if context.iterations == 0:
|
||||
print(f"Starting task: {context.task.description}")
|
||||
return None
|
||||
|
||||
@after_llm_call_crew
|
||||
def log_responses(self, context):
|
||||
# Crew-specific response logging
|
||||
print(f"Response length: {len(context.response)}")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### 1. Iteration Limiting
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def limit_iterations(context: LLMCallHookContext) -> bool | None:
|
||||
max_iterations = 15
|
||||
if context.iterations > max_iterations:
|
||||
print(f"⛔ Blocked: Exceeded {max_iterations} iterations")
|
||||
return False # Block execution
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Human Approval Gate
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def require_approval(context: LLMCallHookContext) -> bool | None:
|
||||
if context.iterations > 5:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Iteration {context.iterations}: Approve LLM call?",
|
||||
default_message="Press Enter to approve, or type 'no' to block:"
|
||||
)
|
||||
if response.lower() == "no":
|
||||
print("🚫 LLM call blocked by user")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Adding System Context
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def add_guardrails(context: LLMCallHookContext) -> None:
|
||||
# Add safety guidelines to every LLM call
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Ensure responses are factual and cite sources when possible."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. Response Sanitization
|
||||
|
||||
```python
|
||||
@after_llm_call
|
||||
def sanitize_sensitive_data(context: LLMCallHookContext) -> str | None:
|
||||
if not context.response:
|
||||
return None
|
||||
|
||||
# Remove sensitive patterns
|
||||
import re
|
||||
sanitized = context.response
|
||||
sanitized = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN-REDACTED]', sanitized)
|
||||
sanitized = re.sub(r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b', '[CARD-REDACTED]', sanitized)
|
||||
|
||||
return sanitized
|
||||
```
|
||||
|
||||
### 5. Cost Tracking
|
||||
|
||||
```python
|
||||
import tiktoken
|
||||
|
||||
@before_llm_call
|
||||
def track_token_usage(context: LLMCallHookContext) -> None:
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
total_tokens = sum(
|
||||
len(encoding.encode(msg.get("content", "")))
|
||||
for msg in context.messages
|
||||
)
|
||||
print(f"📊 Input tokens: ~{total_tokens}")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def track_response_tokens(context: LLMCallHookContext) -> None:
|
||||
if context.response:
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
tokens = len(encoding.encode(context.response))
|
||||
print(f"📊 Response tokens: ~{tokens}")
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. Debug Logging
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def debug_request(context: LLMCallHookContext) -> None:
|
||||
print(f"""
|
||||
🔍 LLM Call Debug:
|
||||
- Agent: {context.agent.role}
|
||||
- Task: {context.task.description[:50]}...
|
||||
- Iteration: {context.iterations}
|
||||
- Message Count: {len(context.messages)}
|
||||
- Last Message: {context.messages[-1] if context.messages else 'None'}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def debug_response(context: LLMCallHookContext) -> None:
|
||||
if context.response:
|
||||
print(f"✅ Response Preview: {context.response[:100]}...")
|
||||
return None
|
||||
```
|
||||
|
||||
## Hook Management
|
||||
|
||||
### Unregistering Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_llm_call_hook
|
||||
)
|
||||
|
||||
# Unregister specific hook
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_llm_call_hook(my_hook)
|
||||
# Later...
|
||||
unregister_before_llm_call_hook(my_hook) # Returns True if found
|
||||
```
|
||||
|
||||
### Clearing Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_all_llm_call_hooks
|
||||
)
|
||||
|
||||
# Clear specific hook type
|
||||
count = clear_before_llm_call_hooks()
|
||||
print(f"Cleared {count} before hooks")
|
||||
|
||||
# Clear all LLM hooks
|
||||
before_count, after_count = clear_all_llm_call_hooks()
|
||||
print(f"Cleared {before_count} before and {after_count} after hooks")
|
||||
```
|
||||
|
||||
### Listing Registered Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
get_before_llm_call_hooks,
|
||||
get_after_llm_call_hooks
|
||||
)
|
||||
|
||||
# Get current hooks
|
||||
before_hooks = get_before_llm_call_hooks()
|
||||
after_hooks = get_after_llm_call_hooks()
|
||||
|
||||
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")
|
||||
```
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Conditional Hook Execution
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def conditional_blocking(context: LLMCallHookContext) -> bool | None:
|
||||
# Only block for specific agents
|
||||
if context.agent.role == "researcher" and context.iterations > 10:
|
||||
return False
|
||||
|
||||
# Only block for specific tasks
|
||||
if "sensitive" in context.task.description.lower() and context.iterations > 5:
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Context-Aware Modifications
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def adaptive_prompting(context: LLMCallHookContext) -> None:
|
||||
# Add different context based on iteration
|
||||
if context.iterations == 0:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Start with a high-level overview."
|
||||
})
|
||||
elif context.iterations > 3:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Focus on specific details and provide examples."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### Chaining Hooks
|
||||
|
||||
```python
|
||||
# Multiple hooks execute in registration order
|
||||
|
||||
@before_llm_call
|
||||
def first_hook(context):
|
||||
print("1. First hook executed")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def second_hook(context):
|
||||
print("2. Second hook executed")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def blocking_hook(context):
|
||||
if context.iterations > 10:
|
||||
print("3. Blocking hook - execution stopped")
|
||||
return False # Subsequent hooks won't execute
|
||||
print("3. Blocking hook - execution allowed")
|
||||
return None
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep Hooks Focused**: Each hook should have a single responsibility
|
||||
2. **Avoid Heavy Computation**: Hooks execute on every LLM call
|
||||
3. **Handle Errors Gracefully**: Use try-except to prevent hook failures from breaking execution
|
||||
4. **Use Type Hints**: Leverage `LLMCallHookContext` for better IDE support
|
||||
5. **Document Hook Behavior**: Especially for blocking conditions
|
||||
6. **Test Hooks Independently**: Unit test hooks before using in production
|
||||
7. **Clear Hooks in Tests**: Use `clear_all_llm_call_hooks()` between test runs
|
||||
8. **Modify In-Place**: Always modify `context.messages` in-place, never replace
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context: LLMCallHookContext) -> bool | None:
|
||||
try:
|
||||
# Your hook logic
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Hook error: {e}")
|
||||
# Decide: allow or block on error
|
||||
return None # Allow execution despite error
|
||||
```
|
||||
|
||||
## Type Safety
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, BeforeLLMCallHookType, AfterLLMCallHookType
|
||||
|
||||
# Explicit type annotations
|
||||
def my_before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: LLMCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Type-safe registration
|
||||
register_before_llm_call_hook(my_before_hook)
|
||||
register_after_llm_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Hook Not Executing
|
||||
- Verify hook is registered before crew execution
|
||||
- Check if previous hook returned `False` (blocks subsequent hooks)
|
||||
- Ensure hook signature matches expected type
|
||||
|
||||
### Message Modifications Not Persisting
|
||||
- Use in-place modifications: `context.messages.append()`
|
||||
- Don't replace the list: `context.messages = []`
|
||||
|
||||
### Response Modifications Not Working
|
||||
- Return the modified string from after hooks
|
||||
- Returning `None` keeps the original response
|
||||
|
||||
## Conclusion
|
||||
|
||||
LLM Call Hooks provide powerful capabilities for controlling and monitoring language model interactions in CrewAI. Use them to implement safety guardrails, approval gates, logging, cost tracking, and response sanitization. Combined with proper error handling and type safety, hooks enable robust and production-ready agent systems.
|
||||
600
docs/en/learn/tool-hooks.mdx
Normal file
600
docs/en/learn/tool-hooks.mdx
Normal file
@@ -0,0 +1,600 @@
|
||||
---
|
||||
title: Tool Call Hooks
|
||||
description: Learn how to use tool call hooks to intercept, modify, and control tool execution in CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Tool Call Hooks provide fine-grained control over tool execution during agent operations. These hooks allow you to intercept tool calls, modify inputs, transform outputs, implement safety checks, and add comprehensive logging or monitoring.
|
||||
|
||||
## Overview
|
||||
|
||||
Tool hooks are executed at two critical points:
|
||||
- **Before Tool Call**: Modify inputs, validate parameters, or block execution
|
||||
- **After Tool Call**: Transform results, sanitize outputs, or log execution details
|
||||
|
||||
## Hook Types
|
||||
|
||||
### Before Tool Call Hooks
|
||||
|
||||
Executed before every tool execution, these hooks can:
|
||||
- Inspect and modify tool inputs
|
||||
- Block tool execution based on conditions
|
||||
- Implement approval gates for dangerous operations
|
||||
- Validate parameters
|
||||
- Log tool invocations
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
# Return False to block execution
|
||||
# Return True or None to allow execution
|
||||
...
|
||||
```
|
||||
|
||||
### After Tool Call Hooks
|
||||
|
||||
Executed after every tool execution, these hooks can:
|
||||
- Modify or sanitize tool results
|
||||
- Add metadata or formatting
|
||||
- Log execution results
|
||||
- Implement result validation
|
||||
- Transform output formats
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def after_hook(context: ToolCallHookContext) -> str | None:
|
||||
# Return modified result string
|
||||
# Return None to keep original result
|
||||
...
|
||||
```
|
||||
|
||||
## Tool Hook Context
|
||||
|
||||
The `ToolCallHookContext` object provides comprehensive access to tool execution state:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # Name of the tool being called
|
||||
tool_input: dict[str, Any] # Mutable tool input parameters
|
||||
tool: CrewStructuredTool # Tool instance reference
|
||||
agent: Agent | BaseAgent | None # Agent executing the tool
|
||||
task: Task | None # Current task
|
||||
crew: Crew | None # Crew instance
|
||||
tool_result: str | None # Tool result (after hooks only)
|
||||
```
|
||||
|
||||
### Modifying Tool Inputs
|
||||
|
||||
**Important:** Always modify tool inputs in-place:
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
def sanitize_input(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['query'] = context.tool_input['query'].lower()
|
||||
|
||||
# ❌ Wrong - replaces dict reference
|
||||
def wrong_approach(context: ToolCallHookContext) -> None:
|
||||
context.tool_input = {'query': 'new query'}
|
||||
```
|
||||
|
||||
## Registration Methods
|
||||
|
||||
### 1. Global Hook Registration
|
||||
|
||||
Register hooks that apply to all tool calls across all crews:
|
||||
|
||||
```python
|
||||
from crewai.hooks import register_before_tool_call_hook, register_after_tool_call_hook
|
||||
|
||||
def log_tool_call(context):
|
||||
print(f"Tool: {context.tool_name}")
|
||||
print(f"Input: {context.tool_input}")
|
||||
return None # Allow execution
|
||||
|
||||
register_before_tool_call_hook(log_tool_call)
|
||||
```
|
||||
|
||||
### 2. Decorator-Based Registration
|
||||
|
||||
Use decorators for cleaner syntax:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_tool_call, after_tool_call
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
dangerous_tools = ['delete_database', 'drop_table', 'rm_rf']
|
||||
if context.tool_name in dangerous_tools:
|
||||
print(f"⛔ Blocked dangerous tool: {context.tool_name}")
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def sanitize_results(context):
|
||||
if context.tool_result and "password" in context.tool_result.lower():
|
||||
return context.tool_result.replace("password", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Crew-Scoped Hooks
|
||||
|
||||
Register hooks for a specific crew instance:
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_tool_call_crew
|
||||
def validate_tool_inputs(self, context):
|
||||
# Only applies to this crew
|
||||
if context.tool_name == "web_search":
|
||||
if not context.tool_input.get('query'):
|
||||
print("❌ Invalid search query")
|
||||
return False
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_tool_results(self, context):
|
||||
# Crew-specific tool logging
|
||||
print(f"✅ {context.tool_name} completed")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### 1. Safety Guardrails
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context: ToolCallHookContext) -> bool | None:
|
||||
# Block tools that could cause harm
|
||||
destructive_tools = [
|
||||
'delete_file',
|
||||
'drop_table',
|
||||
'remove_user',
|
||||
'system_shutdown'
|
||||
]
|
||||
|
||||
if context.tool_name in destructive_tools:
|
||||
print(f"🛑 Blocked destructive tool: {context.tool_name}")
|
||||
return False
|
||||
|
||||
# Warn on sensitive operations
|
||||
sensitive_tools = ['send_email', 'post_to_social_media', 'charge_payment']
|
||||
if context.tool_name in sensitive_tools:
|
||||
print(f"⚠️ Executing sensitive tool: {context.tool_name}")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Human Approval Gate
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval_for_actions(context: ToolCallHookContext) -> bool | None:
|
||||
approval_required = [
|
||||
'send_email',
|
||||
'make_purchase',
|
||||
'delete_file',
|
||||
'post_message'
|
||||
]
|
||||
|
||||
if context.tool_name in approval_required:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Approve {context.tool_name}?",
|
||||
default_message=f"Input: {context.tool_input}\nType 'yes' to approve:"
|
||||
)
|
||||
|
||||
if response.lower() != 'yes':
|
||||
print(f"❌ Tool execution denied: {context.tool_name}")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Input Validation and Sanitization
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def validate_and_sanitize_inputs(context: ToolCallHookContext) -> bool | None:
|
||||
# Validate search queries
|
||||
if context.tool_name == 'web_search':
|
||||
query = context.tool_input.get('query', '')
|
||||
if len(query) < 3:
|
||||
print("❌ Search query too short")
|
||||
return False
|
||||
|
||||
# Sanitize query
|
||||
context.tool_input['query'] = query.strip().lower()
|
||||
|
||||
# Validate file paths
|
||||
if context.tool_name == 'read_file':
|
||||
path = context.tool_input.get('path', '')
|
||||
if '..' in path or path.startswith('/'):
|
||||
print("❌ Invalid file path")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. Result Sanitization
|
||||
|
||||
```python
|
||||
@after_tool_call
|
||||
def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
|
||||
if not context.tool_result:
|
||||
return None
|
||||
|
||||
import re
|
||||
result = context.tool_result
|
||||
|
||||
# Remove API keys
|
||||
result = re.sub(
|
||||
r'(api[_-]?key|token)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r'\1: [REDACTED]',
|
||||
result,
|
||||
flags=re.IGNORECASE
|
||||
)
|
||||
|
||||
# Remove email addresses
|
||||
result = re.sub(
|
||||
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
'[EMAIL-REDACTED]',
|
||||
result
|
||||
)
|
||||
|
||||
# Remove credit card numbers
|
||||
result = re.sub(
|
||||
r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b',
|
||||
'[CARD-REDACTED]',
|
||||
result
|
||||
)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
### 5. Tool Usage Analytics
|
||||
|
||||
```python
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0, 'failures': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['_start_time'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_tool_usage(context: ToolCallHookContext) -> None:
|
||||
start_time = context.tool_input.get('_start_time', time.time())
|
||||
duration = time.time() - start_time
|
||||
|
||||
tool_stats[context.tool_name]['count'] += 1
|
||||
tool_stats[context.tool_name]['total_time'] += duration
|
||||
|
||||
if not context.tool_result or 'error' in context.tool_result.lower():
|
||||
tool_stats[context.tool_name]['failures'] += 1
|
||||
|
||||
print(f"""
|
||||
📊 Tool Stats for {context.tool_name}:
|
||||
- Executions: {tool_stats[context.tool_name]['count']}
|
||||
- Avg Time: {tool_stats[context.tool_name]['total_time'] / tool_stats[context.tool_name]['count']:.2f}s
|
||||
- Failures: {tool_stats[context.tool_name]['failures']}
|
||||
""")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. Rate Limiting
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
tool_call_history = defaultdict(list)
|
||||
|
||||
@before_tool_call
|
||||
def rate_limit_tools(context: ToolCallHookContext) -> bool | None:
|
||||
tool_name = context.tool_name
|
||||
now = datetime.now()
|
||||
|
||||
# Clean old entries (older than 1 minute)
|
||||
tool_call_history[tool_name] = [
|
||||
call_time for call_time in tool_call_history[tool_name]
|
||||
if now - call_time < timedelta(minutes=1)
|
||||
]
|
||||
|
||||
# Check rate limit (max 10 calls per minute)
|
||||
if len(tool_call_history[tool_name]) >= 10:
|
||||
print(f"🚫 Rate limit exceeded for {tool_name}")
|
||||
return False
|
||||
|
||||
# Record this call
|
||||
tool_call_history[tool_name].append(now)
|
||||
return None
|
||||
```
|
||||
|
||||
### 7. Caching Tool Results
|
||||
|
||||
```python
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
tool_cache = {}
|
||||
|
||||
def cache_key(tool_name: str, tool_input: dict) -> str:
|
||||
"""Generate cache key from tool name and input."""
|
||||
input_str = json.dumps(tool_input, sort_keys=True)
|
||||
return hashlib.md5(f"{tool_name}:{input_str}".encode()).hexdigest()
|
||||
|
||||
@before_tool_call
|
||||
def check_cache(context: ToolCallHookContext) -> bool | None:
|
||||
key = cache_key(context.tool_name, context.tool_input)
|
||||
if key in tool_cache:
|
||||
print(f"💾 Cache hit for {context.tool_name}")
|
||||
# Note: Can't return cached result from before hook
|
||||
# Would need to implement this differently
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def cache_result(context: ToolCallHookContext) -> None:
|
||||
if context.tool_result:
|
||||
key = cache_key(context.tool_name, context.tool_input)
|
||||
tool_cache[key] = context.tool_result
|
||||
print(f"💾 Cached result for {context.tool_name}")
|
||||
return None
|
||||
```
|
||||
|
||||
### 8. Debug Logging
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def debug_tool_call(context: ToolCallHookContext) -> None:
|
||||
print(f"""
|
||||
🔍 Tool Call Debug:
|
||||
- Tool: {context.tool_name}
|
||||
- Agent: {context.agent.role if context.agent else 'Unknown'}
|
||||
- Task: {context.task.description[:50] if context.task else 'Unknown'}...
|
||||
- Input: {context.tool_input}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def debug_tool_result(context: ToolCallHookContext) -> None:
|
||||
if context.tool_result:
|
||||
result_preview = context.tool_result[:200]
|
||||
print(f"✅ Result Preview: {result_preview}...")
|
||||
else:
|
||||
print("⚠️ No result returned")
|
||||
return None
|
||||
```
|
||||
|
||||
## Hook Management
|
||||
|
||||
### Unregistering Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_tool_call_hook,
|
||||
unregister_after_tool_call_hook
|
||||
)
|
||||
|
||||
# Unregister specific hook
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_tool_call_hook(my_hook)
|
||||
# Later...
|
||||
success = unregister_before_tool_call_hook(my_hook)
|
||||
print(f"Unregistered: {success}")
|
||||
```
|
||||
|
||||
### Clearing Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks,
|
||||
clear_all_tool_call_hooks
|
||||
)
|
||||
|
||||
# Clear specific hook type
|
||||
count = clear_before_tool_call_hooks()
|
||||
print(f"Cleared {count} before hooks")
|
||||
|
||||
# Clear all tool hooks
|
||||
before_count, after_count = clear_all_tool_call_hooks()
|
||||
print(f"Cleared {before_count} before and {after_count} after hooks")
|
||||
```
|
||||
|
||||
### Listing Registered Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
get_before_tool_call_hooks,
|
||||
get_after_tool_call_hooks
|
||||
)
|
||||
|
||||
# Get current hooks
|
||||
before_hooks = get_before_tool_call_hooks()
|
||||
after_hooks = get_after_tool_call_hooks()
|
||||
|
||||
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")
|
||||
```
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Conditional Hook Execution
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def conditional_blocking(context: ToolCallHookContext) -> bool | None:
|
||||
# Only block for specific agents
|
||||
if context.agent and context.agent.role == "junior_agent":
|
||||
if context.tool_name in ['delete_file', 'send_email']:
|
||||
print(f"❌ Junior agents cannot use {context.tool_name}")
|
||||
return False
|
||||
|
||||
# Only block during specific tasks
|
||||
if context.task and "sensitive" in context.task.description.lower():
|
||||
if context.tool_name == 'web_search':
|
||||
print("❌ Web search blocked for sensitive tasks")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Context-Aware Input Modification
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def enhance_tool_inputs(context: ToolCallHookContext) -> None:
|
||||
# Add context based on agent role
|
||||
if context.agent and context.agent.role == "researcher":
|
||||
if context.tool_name == 'web_search':
|
||||
# Add domain restrictions for researchers
|
||||
context.tool_input['domains'] = ['edu', 'gov', 'org']
|
||||
|
||||
# Add context based on task
|
||||
if context.task and "urgent" in context.task.description.lower():
|
||||
if context.tool_name == 'send_email':
|
||||
context.tool_input['priority'] = 'high'
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Tool Chain Monitoring
|
||||
|
||||
```python
|
||||
tool_call_chain = []
|
||||
|
||||
@before_tool_call
|
||||
def track_tool_chain(context: ToolCallHookContext) -> None:
|
||||
tool_call_chain.append({
|
||||
'tool': context.tool_name,
|
||||
'timestamp': time.time(),
|
||||
'agent': context.agent.role if context.agent else 'Unknown'
|
||||
})
|
||||
|
||||
# Detect potential infinite loops
|
||||
recent_calls = tool_call_chain[-5:]
|
||||
if len(recent_calls) == 5 and all(c['tool'] == context.tool_name for c in recent_calls):
|
||||
print(f"⚠️ Warning: {context.tool_name} called 5 times in a row")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep Hooks Focused**: Each hook should have a single responsibility
|
||||
2. **Avoid Heavy Computation**: Hooks execute on every tool call
|
||||
3. **Handle Errors Gracefully**: Use try-except to prevent hook failures
|
||||
4. **Use Type Hints**: Leverage `ToolCallHookContext` for better IDE support
|
||||
5. **Document Blocking Conditions**: Make it clear when/why tools are blocked
|
||||
6. **Test Hooks Independently**: Unit test hooks before using in production
|
||||
7. **Clear Hooks in Tests**: Use `clear_all_tool_call_hooks()` between test runs
|
||||
8. **Modify In-Place**: Always modify `context.tool_input` in-place, never replace
|
||||
9. **Log Important Decisions**: Especially when blocking tool execution
|
||||
10. **Consider Performance**: Cache expensive validations when possible
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safe_validation(context: ToolCallHookContext) -> bool | None:
|
||||
try:
|
||||
# Your validation logic
|
||||
if not validate_input(context.tool_input):
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Hook error: {e}")
|
||||
# Decide: allow or block on error
|
||||
return None # Allow execution despite error
|
||||
```
|
||||
|
||||
## Type Safety
|
||||
|
||||
```python
|
||||
from crewai.hooks import ToolCallHookContext, BeforeToolCallHookType, AfterToolCallHookType
|
||||
|
||||
# Explicit type annotations
|
||||
def my_before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Type-safe registration
|
||||
register_before_tool_call_hook(my_before_hook)
|
||||
register_after_tool_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## Integration with Existing Tools
|
||||
|
||||
### Wrapping Existing Validation
|
||||
|
||||
```python
|
||||
def existing_validator(tool_name: str, inputs: dict) -> bool:
|
||||
"""Your existing validation function."""
|
||||
# Your validation logic
|
||||
return True
|
||||
|
||||
@before_tool_call
|
||||
def integrate_validator(context: ToolCallHookContext) -> bool | None:
|
||||
if not existing_validator(context.tool_name, context.tool_input):
|
||||
print(f"❌ Validation failed for {context.tool_name}")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### Logging to External Systems
|
||||
|
||||
```python
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@before_tool_call
|
||||
def log_to_external_system(context: ToolCallHookContext) -> None:
|
||||
logger.info(f"Tool call: {context.tool_name}", extra={
|
||||
'tool_name': context.tool_name,
|
||||
'tool_input': context.tool_input,
|
||||
'agent': context.agent.role if context.agent else None
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Hook Not Executing
|
||||
- Verify hook is registered before crew execution
|
||||
- Check if previous hook returned `False` (blocks execution and subsequent hooks)
|
||||
- Ensure hook signature matches expected type
|
||||
|
||||
### Input Modifications Not Working
|
||||
- Use in-place modifications: `context.tool_input['key'] = value`
|
||||
- Don't replace the dict: `context.tool_input = {}`
|
||||
|
||||
### Result Modifications Not Working
|
||||
- Return the modified string from after hooks
|
||||
- Returning `None` keeps the original result
|
||||
- Ensure the tool actually returned a result
|
||||
|
||||
### Tool Blocked Unexpectedly
|
||||
- Check all before hooks for blocking conditions
|
||||
- Verify hook execution order
|
||||
- Add debug logging to identify which hook is blocking
|
||||
|
||||
## Conclusion
|
||||
|
||||
Tool Call Hooks provide powerful capabilities for controlling and monitoring tool execution in CrewAI. Use them to implement safety guardrails, approval gates, input validation, result sanitization, logging, and analytics. Combined with proper error handling and type safety, hooks enable secure and production-ready agent systems with comprehensive observability.
|
||||
379
docs/ko/learn/execution-hooks.mdx
Normal file
379
docs/ko/learn/execution-hooks.mdx
Normal file
@@ -0,0 +1,379 @@
|
||||
---
|
||||
title: 실행 훅 개요
|
||||
description: 에이전트 작업에 대한 세밀한 제어를 위한 CrewAI 실행 훅 이해 및 사용
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
실행 훅(Execution Hooks)은 CrewAI 에이전트의 런타임 동작을 세밀하게 제어할 수 있게 해줍니다. 크루 실행 전후에 실행되는 킥오프 훅과 달리, 실행 훅은 에이전트 실행 중 특정 작업을 가로채서 동작을 수정하고, 안전성 검사를 구현하며, 포괄적인 모니터링을 추가할 수 있습니다.
|
||||
|
||||
## 실행 훅의 유형
|
||||
|
||||
CrewAI는 두 가지 주요 범주의 실행 훅을 제공합니다:
|
||||
|
||||
### 1. [LLM 호출 훅](/learn/llm-hooks)
|
||||
|
||||
언어 모델 상호작용을 제어하고 모니터링합니다:
|
||||
- **LLM 호출 전**: 프롬프트 수정, 입력 검증, 승인 게이트 구현
|
||||
- **LLM 호출 후**: 응답 변환, 출력 정제, 대화 기록 업데이트
|
||||
|
||||
**사용 사례:**
|
||||
- 반복 제한
|
||||
- 비용 추적 및 토큰 사용량 모니터링
|
||||
- 응답 정제 및 콘텐츠 필터링
|
||||
- LLM 호출에 대한 사람의 승인
|
||||
- 안전 가이드라인 또는 컨텍스트 추가
|
||||
- 디버그 로깅 및 요청/응답 검사
|
||||
|
||||
[LLM 훅 문서 보기 →](/learn/llm-hooks)
|
||||
|
||||
### 2. [도구 호출 훅](/learn/tool-hooks)
|
||||
|
||||
도구 실행을 제어하고 모니터링합니다:
|
||||
- **도구 호출 전**: 입력 수정, 매개변수 검증, 위험한 작업 차단
|
||||
- **도구 호출 후**: 결과 변환, 출력 정제, 실행 세부사항 로깅
|
||||
|
||||
**사용 사례:**
|
||||
- 파괴적인 작업에 대한 안전 가드레일
|
||||
- 민감한 작업에 대한 사람의 승인
|
||||
- 입력 검증 및 정제
|
||||
- 결과 캐싱 및 속도 제한
|
||||
- 도구 사용 분석
|
||||
- 디버그 로깅 및 모니터링
|
||||
|
||||
[도구 훅 문서 보기 →](/learn/tool-hooks)
|
||||
|
||||
## 훅 등록 방법
|
||||
|
||||
### 1. 데코레이터 기반 훅 (권장)
|
||||
|
||||
훅을 등록하는 가장 깔끔하고 파이썬스러운 방법:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call, before_tool_call, after_tool_call
|
||||
|
||||
@before_llm_call
|
||||
def limit_iterations(context):
|
||||
"""반복 횟수를 제한하여 무한 루프를 방지합니다."""
|
||||
if context.iterations > 10:
|
||||
return False # 실행 차단
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
"""LLM 응답에서 민감한 데이터를 제거합니다."""
|
||||
if "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[수정됨]")
|
||||
return None
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
"""파괴적인 작업을 차단합니다."""
|
||||
if context.tool_name == "delete_database":
|
||||
return False # 실행 차단
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def log_tool_result(context):
|
||||
"""도구 실행을 로깅합니다."""
|
||||
print(f"도구 {context.tool_name} 완료")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. 크루 범위 훅
|
||||
|
||||
특정 크루 인스턴스에만 훅을 적용합니다:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# 이 크루에만 적용됩니다
|
||||
print(f"{self.__class__.__name__}에서 LLM 호출")
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_results(self, context):
|
||||
# 크루별 로깅
|
||||
print(f"도구 결과: {context.tool_result[:50]}...")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential
|
||||
)
|
||||
```
|
||||
|
||||
## 훅 실행 흐름
|
||||
|
||||
### LLM 호출 흐름
|
||||
|
||||
```
|
||||
에이전트가 LLM을 호출해야 함
|
||||
↓
|
||||
[LLM 호출 전 훅 실행]
|
||||
├→ 훅 1: 반복 횟수 검증
|
||||
├→ 훅 2: 안전 컨텍스트 추가
|
||||
└→ 훅 3: 요청 로깅
|
||||
↓
|
||||
훅이 False를 반환하는 경우:
|
||||
├→ LLM 호출 차단
|
||||
└→ ValueError 발생
|
||||
↓
|
||||
모든 훅이 True/None을 반환하는 경우:
|
||||
├→ LLM 호출 진행
|
||||
└→ 응답 생성
|
||||
↓
|
||||
[LLM 호출 후 훅 실행]
|
||||
├→ 훅 1: 응답 정제
|
||||
├→ 훅 2: 응답 로깅
|
||||
└→ 훅 3: 메트릭 업데이트
|
||||
↓
|
||||
최종 응답 반환
|
||||
```
|
||||
|
||||
### 도구 호출 흐름
|
||||
|
||||
```
|
||||
에이전트가 도구를 실행해야 함
|
||||
↓
|
||||
[도구 호출 전 훅 실행]
|
||||
├→ 훅 1: 도구 허용 여부 확인
|
||||
├→ 훅 2: 입력 검증
|
||||
└→ 훅 3: 필요시 승인 요청
|
||||
↓
|
||||
훅이 False를 반환하는 경우:
|
||||
├→ 도구 실행 차단
|
||||
└→ 오류 메시지 반환
|
||||
↓
|
||||
모든 훅이 True/None을 반환하는 경우:
|
||||
├→ 도구 실행 진행
|
||||
└→ 결과 생성
|
||||
↓
|
||||
[도구 호출 후 훅 실행]
|
||||
├→ 훅 1: 결과 정제
|
||||
├→ 훅 2: 결과 캐싱
|
||||
└→ 훅 3: 메트릭 로깅
|
||||
↓
|
||||
최종 결과 반환
|
||||
```
|
||||
|
||||
## 훅 컨텍스트 객체
|
||||
|
||||
### LLMCallHookContext
|
||||
|
||||
LLM 실행 상태에 대한 액세스를 제공합니다:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # 전체 실행자 액세스
|
||||
messages: list # 변경 가능한 메시지 목록
|
||||
agent: Agent # 현재 에이전트
|
||||
task: Task # 현재 작업
|
||||
crew: Crew # 크루 인스턴스
|
||||
llm: BaseLLM # LLM 인스턴스
|
||||
iterations: int # 현재 반복 횟수
|
||||
response: str | None # LLM 응답 (후 훅용)
|
||||
```
|
||||
|
||||
### ToolCallHookContext
|
||||
|
||||
도구 실행 상태에 대한 액세스를 제공합니다:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # 호출되는 도구
|
||||
tool_input: dict # 변경 가능한 입력 매개변수
|
||||
tool: CrewStructuredTool # 도구 인스턴스
|
||||
agent: Agent | None # 실행 중인 에이전트
|
||||
task: Task | None # 현재 작업
|
||||
crew: Crew | None # 크루 인스턴스
|
||||
tool_result: str | None # 도구 결과 (후 훅용)
|
||||
```
|
||||
|
||||
## 일반적인 패턴
|
||||
|
||||
### 안전 및 검증
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context):
|
||||
"""파괴적인 작업을 차단합니다."""
|
||||
dangerous = ['delete_file', 'drop_table', 'system_shutdown']
|
||||
if context.tool_name in dangerous:
|
||||
print(f"🛑 차단됨: {context.tool_name}")
|
||||
return False
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def iteration_limit(context):
|
||||
"""무한 루프를 방지합니다."""
|
||||
if context.iterations > 15:
|
||||
print("⛔ 최대 반복 횟수 초과")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### 사람의 개입
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval(context):
|
||||
"""민감한 작업에 대한 승인을 요구합니다."""
|
||||
sensitive = ['send_email', 'make_payment', 'post_message']
|
||||
|
||||
if context.tool_name in sensitive:
|
||||
response = context.request_human_input(
|
||||
prompt=f"{context.tool_name} 승인하시겠습니까?",
|
||||
default_message="승인하려면 'yes'를 입력하세요:"
|
||||
)
|
||||
|
||||
if response.lower() != 'yes':
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 모니터링 및 분석
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
metrics = defaultdict(lambda: {'count': 0, 'total_time': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context):
|
||||
context.tool_input['_start'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_metrics(context):
|
||||
start = context.tool_input.get('_start', time.time())
|
||||
duration = time.time() - start
|
||||
|
||||
metrics[context.tool_name]['count'] += 1
|
||||
metrics[context.tool_name]['total_time'] += duration
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
## 훅 관리
|
||||
|
||||
### 모든 훅 지우기
|
||||
|
||||
```python
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
# 모든 훅을 한 번에 지웁니다
|
||||
result = clear_all_global_hooks()
|
||||
print(f"{result['total']} 훅이 지워졌습니다")
|
||||
```
|
||||
|
||||
### 특정 훅 유형 지우기
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks
|
||||
)
|
||||
|
||||
# 특정 유형 지우기
|
||||
llm_before_count = clear_before_llm_call_hooks()
|
||||
tool_after_count = clear_after_tool_call_hooks()
|
||||
```
|
||||
|
||||
## 모범 사례
|
||||
|
||||
### 1. 훅을 집중적으로 유지
|
||||
각 훅은 단일하고 명확한 책임을 가져야 합니다.
|
||||
|
||||
### 2. 오류를 우아하게 처리
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context):
|
||||
try:
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"훅 오류: {e}")
|
||||
return None # 오류에도 불구하고 실행 허용
|
||||
```
|
||||
|
||||
### 3. 컨텍스트를 제자리에서 수정
|
||||
```python
|
||||
# ✅ 올바름 - 제자리에서 수정
|
||||
@before_llm_call
|
||||
def add_context(context):
|
||||
context.messages.append({"role": "system", "content": "간결하게"})
|
||||
|
||||
# ❌ 잘못됨 - 참조를 교체
|
||||
@before_llm_call
|
||||
def wrong_approach(context):
|
||||
context.messages = [{"role": "system", "content": "간결하게"}]
|
||||
```
|
||||
|
||||
### 4. 타입 힌트 사용
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, ToolCallHookContext
|
||||
|
||||
def my_llm_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_tool_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
```
|
||||
|
||||
### 5. 테스트에서 정리
|
||||
```python
|
||||
import pytest
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_hooks():
|
||||
"""각 테스트 전에 훅을 재설정합니다."""
|
||||
yield
|
||||
clear_all_global_hooks()
|
||||
```
|
||||
|
||||
## 어떤 훅을 사용해야 할까요
|
||||
|
||||
### LLM 훅을 사용하는 경우:
|
||||
- 반복 제한 구현
|
||||
- 프롬프트에 컨텍스트 또는 안전 가이드라인 추가
|
||||
- 토큰 사용량 및 비용 추적
|
||||
- 응답 정제 또는 변환
|
||||
- LLM 호출에 대한 승인 게이트 구현
|
||||
- 프롬프트/응답 상호작용 디버깅
|
||||
|
||||
### 도구 훅을 사용하는 경우:
|
||||
- 위험하거나 파괴적인 작업 차단
|
||||
- 실행 전 도구 입력 검증
|
||||
- 민감한 작업에 대한 승인 게이트 구현
|
||||
- 도구 결과 캐싱
|
||||
- 도구 사용 및 성능 추적
|
||||
- 도구 출력 정제
|
||||
- 도구 호출 속도 제한
|
||||
|
||||
### 둘 다 사용하는 경우:
|
||||
모든 에이전트 작업을 모니터링해야 하는 포괄적인 관찰성, 안전 또는 승인 시스템을 구축하는 경우.
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [LLM 호출 훅 →](/learn/llm-hooks) - 상세한 LLM 훅 문서
|
||||
- [도구 호출 훅 →](/learn/tool-hooks) - 상세한 도구 훅 문서
|
||||
- [킥오프 전후 훅 →](/learn/before-and-after-kickoff-hooks) - 크루 생명주기 훅
|
||||
- [사람의 개입 →](/learn/human-in-the-loop) - 사람 입력 패턴
|
||||
|
||||
## 결론
|
||||
|
||||
실행 훅은 에이전트 런타임 동작에 대한 강력한 제어를 제공합니다. 이를 사용하여 안전 가드레일, 승인 워크플로우, 포괄적인 모니터링 및 사용자 정의 비즈니스 로직을 구현하세요. 적절한 오류 처리, 타입 안전성 및 성능 고려사항과 결합하면, 훅을 통해 프로덕션 준비가 된 안전하고 관찰 가능한 에이전트 시스템을 구축할 수 있습니다.
|
||||
412
docs/ko/learn/llm-hooks.mdx
Normal file
412
docs/ko/learn/llm-hooks.mdx
Normal file
@@ -0,0 +1,412 @@
|
||||
---
|
||||
title: LLM 호출 훅
|
||||
description: CrewAI에서 언어 모델 상호작용을 가로채고, 수정하고, 제어하는 LLM 호출 훅 사용 방법 배우기
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
LLM 호출 훅(LLM Call Hooks)은 에이전트 실행 중 언어 모델 상호작용에 대한 세밀한 제어를 제공합니다. 이러한 훅을 사용하면 LLM 호출을 가로채고, 프롬프트를 수정하고, 응답을 변환하고, 승인 게이트를 구현하고, 사용자 정의 로깅 또는 모니터링을 추가할 수 있습니다.
|
||||
|
||||
## 개요
|
||||
|
||||
LLM 훅은 두 가지 중요한 시점에 실행됩니다:
|
||||
- **LLM 호출 전**: 메시지 수정, 입력 검증 또는 실행 차단
|
||||
- **LLM 호출 후**: 응답 변환, 출력 정제 또는 대화 기록 수정
|
||||
|
||||
## 훅 타입
|
||||
|
||||
### LLM 호출 전 훅
|
||||
|
||||
모든 LLM 호출 전에 실행되며, 다음을 수행할 수 있습니다:
|
||||
- LLM에 전송되는 메시지 검사 및 수정
|
||||
- 조건에 따라 LLM 실행 차단
|
||||
- 속도 제한 또는 승인 게이트 구현
|
||||
- 컨텍스트 또는 시스템 메시지 추가
|
||||
- 요청 세부사항 로깅
|
||||
|
||||
**시그니처:**
|
||||
```python
|
||||
def before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# 실행을 차단하려면 False 반환
|
||||
# 실행을 허용하려면 True 또는 None 반환
|
||||
...
|
||||
```
|
||||
|
||||
### LLM 호출 후 훅
|
||||
|
||||
모든 LLM 호출 후에 실행되며, 다음을 수행할 수 있습니다:
|
||||
- LLM 응답 수정 또는 정제
|
||||
- 메타데이터 또는 서식 추가
|
||||
- 응답 세부사항 로깅
|
||||
- 대화 기록 업데이트
|
||||
- 콘텐츠 필터링 구현
|
||||
|
||||
**시그니처:**
|
||||
```python
|
||||
def after_hook(context: LLMCallHookContext) -> str | None:
|
||||
# 수정된 응답 문자열 반환
|
||||
# 원본 응답을 유지하려면 None 반환
|
||||
...
|
||||
```
|
||||
|
||||
## LLM 훅 컨텍스트
|
||||
|
||||
`LLMCallHookContext` 객체는 실행 상태에 대한 포괄적인 액세스를 제공합니다:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # 전체 실행자 참조
|
||||
messages: list # 변경 가능한 메시지 목록
|
||||
agent: Agent # 현재 에이전트
|
||||
task: Task # 현재 작업
|
||||
crew: Crew # 크루 인스턴스
|
||||
llm: BaseLLM # LLM 인스턴스
|
||||
iterations: int # 현재 반복 횟수
|
||||
response: str | None # LLM 응답 (후 훅용)
|
||||
```
|
||||
|
||||
### 메시지 수정
|
||||
|
||||
**중요:** 항상 메시지를 제자리에서 수정하세요:
|
||||
|
||||
```python
|
||||
# ✅ 올바름 - 제자리에서 수정
|
||||
def add_context(context: LLMCallHookContext) -> None:
|
||||
context.messages.append({"role": "system", "content": "간결하게 작성하세요"})
|
||||
|
||||
# ❌ 잘못됨 - 리스트 참조를 교체
|
||||
def wrong_approach(context: LLMCallHookContext) -> None:
|
||||
context.messages = [{"role": "system", "content": "간결하게 작성하세요"}]
|
||||
```
|
||||
|
||||
## 등록 방법
|
||||
|
||||
### 1. 데코레이터 기반 등록 (권장)
|
||||
|
||||
더 깔끔한 구문을 위해 데코레이터를 사용합니다:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call
|
||||
|
||||
@before_llm_call
|
||||
def validate_iteration_count(context):
|
||||
"""반복 횟수를 검증합니다."""
|
||||
if context.iterations > 10:
|
||||
print("⚠️ 최대 반복 횟수 초과")
|
||||
return False # 실행 차단
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
"""민감한 데이터를 제거합니다."""
|
||||
if context.response and "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[수정됨]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. 크루 범위 훅
|
||||
|
||||
특정 크루 인스턴스에 대한 훅을 등록합니다:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_llm_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# 이 크루에만 적용됩니다
|
||||
if context.iterations == 0:
|
||||
print(f"작업 시작: {context.task.description}")
|
||||
return None
|
||||
|
||||
@after_llm_call_crew
|
||||
def log_responses(self, context):
|
||||
# 크루별 응답 로깅
|
||||
print(f"응답 길이: {len(context.response)}")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## 일반적인 사용 사례
|
||||
|
||||
### 1. 반복 제한
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def limit_iterations(context: LLMCallHookContext) -> bool | None:
|
||||
"""무한 루프를 방지하기 위해 반복을 제한합니다."""
|
||||
max_iterations = 15
|
||||
if context.iterations > max_iterations:
|
||||
print(f"⛔ 차단됨: {max_iterations}회 반복 초과")
|
||||
return False # 실행 차단
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. 사람의 승인 게이트
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def require_approval(context: LLMCallHookContext) -> bool | None:
|
||||
"""특정 반복 후 승인을 요구합니다."""
|
||||
if context.iterations > 5:
|
||||
response = context.request_human_input(
|
||||
prompt=f"반복 {context.iterations}: LLM 호출을 승인하시겠습니까?",
|
||||
default_message="승인하려면 Enter를 누르고, 차단하려면 'no'를 입력하세요:"
|
||||
)
|
||||
if response.lower() == "no":
|
||||
print("🚫 사용자에 의해 LLM 호출이 차단되었습니다")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. 시스템 컨텍스트 추가
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def add_guardrails(context: LLMCallHookContext) -> None:
|
||||
"""모든 LLM 호출에 안전 가이드라인을 추가합니다."""
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "응답이 사실에 기반하고 가능한 경우 출처를 인용하도록 하세요."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. 응답 정제
|
||||
|
||||
```python
|
||||
@after_llm_call
|
||||
def sanitize_sensitive_data(context: LLMCallHookContext) -> str | None:
|
||||
"""민감한 데이터 패턴을 제거합니다."""
|
||||
if not context.response:
|
||||
return None
|
||||
|
||||
import re
|
||||
sanitized = context.response
|
||||
sanitized = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[주민번호-수정됨]', sanitized)
|
||||
sanitized = re.sub(r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b', '[카드번호-수정됨]', sanitized)
|
||||
|
||||
return sanitized
|
||||
```
|
||||
|
||||
### 5. 비용 추적
|
||||
|
||||
```python
|
||||
import tiktoken
|
||||
|
||||
@before_llm_call
|
||||
def track_token_usage(context: LLMCallHookContext) -> None:
|
||||
"""입력 토큰을 추적합니다."""
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
total_tokens = sum(
|
||||
len(encoding.encode(msg.get("content", "")))
|
||||
for msg in context.messages
|
||||
)
|
||||
print(f"📊 입력 토큰: ~{total_tokens}")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def track_response_tokens(context: LLMCallHookContext) -> None:
|
||||
"""응답 토큰을 추적합니다."""
|
||||
if context.response:
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
tokens = len(encoding.encode(context.response))
|
||||
print(f"📊 응답 토큰: ~{tokens}")
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. 디버그 로깅
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def debug_request(context: LLMCallHookContext) -> None:
|
||||
"""LLM 요청을 디버그합니다."""
|
||||
print(f"""
|
||||
🔍 LLM 호출 디버그:
|
||||
- 에이전트: {context.agent.role}
|
||||
- 작업: {context.task.description[:50]}...
|
||||
- 반복: {context.iterations}
|
||||
- 메시지 수: {len(context.messages)}
|
||||
- 마지막 메시지: {context.messages[-1] if context.messages else 'None'}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def debug_response(context: LLMCallHookContext) -> None:
|
||||
"""LLM 응답을 디버그합니다."""
|
||||
if context.response:
|
||||
print(f"✅ 응답 미리보기: {context.response[:100]}...")
|
||||
return None
|
||||
```
|
||||
|
||||
## 훅 관리
|
||||
|
||||
### 훅 등록 해제
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_llm_call_hook
|
||||
)
|
||||
|
||||
# 특정 훅 등록 해제
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_llm_call_hook(my_hook)
|
||||
# 나중에...
|
||||
unregister_before_llm_call_hook(my_hook) # 찾으면 True 반환
|
||||
```
|
||||
|
||||
### 훅 지우기
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_all_llm_call_hooks
|
||||
)
|
||||
|
||||
# 특정 훅 타입 지우기
|
||||
count = clear_before_llm_call_hooks()
|
||||
print(f"{count}개의 전(before) 훅이 지워졌습니다")
|
||||
|
||||
# 모든 LLM 훅 지우기
|
||||
before_count, after_count = clear_all_llm_call_hooks()
|
||||
print(f"{before_count}개의 전(before) 훅과 {after_count}개의 후(after) 훅이 지워졌습니다")
|
||||
```
|
||||
|
||||
## 고급 패턴
|
||||
|
||||
### 조건부 훅 실행
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def conditional_blocking(context: LLMCallHookContext) -> bool | None:
|
||||
"""특정 조건에서만 차단합니다."""
|
||||
# 특정 에이전트에 대해서만 차단
|
||||
if context.agent.role == "researcher" and context.iterations > 10:
|
||||
return False
|
||||
|
||||
# 특정 작업에 대해서만 차단
|
||||
if "민감한" in context.task.description.lower() and context.iterations > 5:
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 컨텍스트 인식 수정
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def adaptive_prompting(context: LLMCallHookContext) -> None:
|
||||
"""반복에 따라 다른 컨텍스트를 추가합니다."""
|
||||
if context.iterations == 0:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "높은 수준의 개요부터 시작하세요."
|
||||
})
|
||||
elif context.iterations > 3:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "구체적인 세부사항에 집중하고 예제를 제공하세요."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### 훅 체이닝
|
||||
|
||||
```python
|
||||
# 여러 훅은 등록 순서대로 실행됩니다
|
||||
|
||||
@before_llm_call
|
||||
def first_hook(context):
|
||||
print("1. 첫 번째 훅 실행됨")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def second_hook(context):
|
||||
print("2. 두 번째 훅 실행됨")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def blocking_hook(context):
|
||||
if context.iterations > 10:
|
||||
print("3. 차단 훅 - 실행 중지")
|
||||
return False # 후속 훅은 실행되지 않습니다
|
||||
print("3. 차단 훅 - 실행 허용")
|
||||
return None
|
||||
```
|
||||
|
||||
## 모범 사례
|
||||
|
||||
1. **훅을 집중적으로 유지**: 각 훅은 단일 책임을 가져야 합니다
|
||||
2. **무거운 계산 피하기**: 훅은 모든 LLM 호출마다 실행됩니다
|
||||
3. **오류를 우아하게 처리**: try-except를 사용하여 훅 실패로 인한 실행 중단 방지
|
||||
4. **타입 힌트 사용**: 더 나은 IDE 지원을 위해 `LLMCallHookContext` 활용
|
||||
5. **훅 동작 문서화**: 특히 차단 조건에 대해
|
||||
6. **훅을 독립적으로 테스트**: 프로덕션에서 사용하기 전에 단위 테스트
|
||||
7. **테스트에서 훅 지우기**: 테스트 실행 간 `clear_all_llm_call_hooks()` 사용
|
||||
8. **제자리에서 수정**: 항상 `context.messages`를 제자리에서 수정하고 교체하지 마세요
|
||||
|
||||
## 오류 처리
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context: LLMCallHookContext) -> bool | None:
|
||||
try:
|
||||
# 훅 로직
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ 훅 오류: {e}")
|
||||
# 결정: 오류 발생 시 허용 또는 차단
|
||||
return None # 오류에도 불구하고 실행 허용
|
||||
```
|
||||
|
||||
## 타입 안전성
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, BeforeLLMCallHookType, AfterLLMCallHookType
|
||||
|
||||
# 명시적 타입 주석
|
||||
def my_before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: LLMCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# 타입 안전 등록
|
||||
register_before_llm_call_hook(my_before_hook)
|
||||
register_after_llm_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## 문제 해결
|
||||
|
||||
### 훅이 실행되지 않음
|
||||
- 크루 실행 전에 훅이 등록되었는지 확인
|
||||
- 이전 훅이 `False`를 반환했는지 확인 (후속 훅 차단)
|
||||
- 훅 시그니처가 예상 타입과 일치하는지 확인
|
||||
|
||||
### 메시지 수정이 지속되지 않음
|
||||
- 제자리 수정 사용: `context.messages.append()`
|
||||
- 리스트를 교체하지 마세요: `context.messages = []`
|
||||
|
||||
### 응답 수정이 작동하지 않음
|
||||
- 후 훅에서 수정된 문자열을 반환
|
||||
- `None`을 반환하면 원본 응답이 유지됩니다
|
||||
|
||||
## 결론
|
||||
|
||||
LLM 호출 훅은 CrewAI에서 언어 모델 상호작용을 제어하고 모니터링하는 강력한 기능을 제공합니다. 이를 사용하여 안전 가드레일, 승인 게이트, 로깅, 비용 추적 및 응답 정제를 구현하세요. 적절한 오류 처리 및 타입 안전성과 결합하면, 훅을 통해 강력하고 프로덕션 준비가 된 에이전트 시스템을 구축할 수 있습니다.
|
||||
|
||||
498
docs/ko/learn/tool-hooks.mdx
Normal file
498
docs/ko/learn/tool-hooks.mdx
Normal file
@@ -0,0 +1,498 @@
|
||||
---
|
||||
title: 도구 호출 훅
|
||||
description: CrewAI에서 도구 실행을 가로채고, 수정하고, 제어하는 도구 호출 훅 사용 방법 배우기
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
도구 호출 훅(Tool Call Hooks)은 에이전트 작업 중 도구 실행에 대한 세밀한 제어를 제공합니다. 이러한 훅을 사용하면 도구 호출을 가로채고, 입력을 수정하고, 출력을 변환하고, 안전 검사를 구현하고, 포괄적인 로깅 또는 모니터링을 추가할 수 있습니다.
|
||||
|
||||
## 개요
|
||||
|
||||
도구 훅은 두 가지 중요한 시점에 실행됩니다:
|
||||
- **도구 호출 전**: 입력 수정, 매개변수 검증 또는 실행 차단
|
||||
- **도구 호출 후**: 결과 변환, 출력 정제 또는 실행 세부사항 로깅
|
||||
|
||||
## 훅 타입
|
||||
|
||||
### 도구 호출 전 훅
|
||||
|
||||
모든 도구 실행 전에 실행되며, 다음을 수행할 수 있습니다:
|
||||
- 도구 입력 검사 및 수정
|
||||
- 조건에 따라 도구 실행 차단
|
||||
- 위험한 작업에 대한 승인 게이트 구현
|
||||
- 매개변수 검증
|
||||
- 도구 호출 로깅
|
||||
|
||||
**시그니처:**
|
||||
```python
|
||||
def before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
# 실행을 차단하려면 False 반환
|
||||
# 실행을 허용하려면 True 또는 None 반환
|
||||
...
|
||||
```
|
||||
|
||||
### 도구 호출 후 훅
|
||||
|
||||
모든 도구 실행 후에 실행되며, 다음을 수행할 수 있습니다:
|
||||
- 도구 결과 수정 또는 정제
|
||||
- 메타데이터 또는 서식 추가
|
||||
- 실행 결과 로깅
|
||||
- 결과 검증 구현
|
||||
- 출력 형식 변환
|
||||
|
||||
**시그니처:**
|
||||
```python
|
||||
def after_hook(context: ToolCallHookContext) -> str | None:
|
||||
# 수정된 결과 문자열 반환
|
||||
# 원본 결과를 유지하려면 None 반환
|
||||
...
|
||||
```
|
||||
|
||||
## 도구 훅 컨텍스트
|
||||
|
||||
`ToolCallHookContext` 객체는 도구 실행 상태에 대한 포괄적인 액세스를 제공합니다:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # 호출되는 도구의 이름
|
||||
tool_input: dict[str, Any] # 변경 가능한 도구 입력 매개변수
|
||||
tool: CrewStructuredTool # 도구 인스턴스 참조
|
||||
agent: Agent | BaseAgent | None # 도구를 실행하는 에이전트
|
||||
task: Task | None # 현재 작업
|
||||
crew: Crew | None # 크루 인스턴스
|
||||
tool_result: str | None # 도구 결과 (후 훅용)
|
||||
```
|
||||
|
||||
### 도구 입력 수정
|
||||
|
||||
**중요:** 항상 도구 입력을 제자리에서 수정하세요:
|
||||
|
||||
```python
|
||||
# ✅ 올바름 - 제자리에서 수정
|
||||
def sanitize_input(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['query'] = context.tool_input['query'].lower()
|
||||
|
||||
# ❌ 잘못됨 - 딕셔너리 참조를 교체
|
||||
def wrong_approach(context: ToolCallHookContext) -> None:
|
||||
context.tool_input = {'query': 'new query'}
|
||||
```
|
||||
|
||||
## 등록 방법
|
||||
|
||||
### 1. 데코레이터 기반 등록 (권장)
|
||||
|
||||
더 깔끔한 구문을 위해 데코레이터를 사용합니다:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_tool_call, after_tool_call
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
"""위험한 도구를 차단합니다."""
|
||||
dangerous_tools = ['delete_database', 'drop_table', 'rm_rf']
|
||||
if context.tool_name in dangerous_tools:
|
||||
print(f"⛔ 위험한 도구 차단됨: {context.tool_name}")
|
||||
return False # 실행 차단
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def sanitize_results(context):
|
||||
"""결과를 정제합니다."""
|
||||
if context.tool_result and "password" in context.tool_result.lower():
|
||||
return context.tool_result.replace("password", "[수정됨]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. 크루 범위 훅
|
||||
|
||||
특정 크루 인스턴스에 대한 훅을 등록합니다:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_tool_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_tool_call_crew
|
||||
def validate_tool_inputs(self, context):
|
||||
# 이 크루에만 적용됩니다
|
||||
if context.tool_name == "web_search":
|
||||
if not context.tool_input.get('query'):
|
||||
print("❌ 잘못된 검색 쿼리")
|
||||
return False
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_tool_results(self, context):
|
||||
# 크루별 도구 로깅
|
||||
print(f"✅ {context.tool_name} 완료됨")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## 일반적인 사용 사례
|
||||
|
||||
### 1. 안전 가드레일
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context: ToolCallHookContext) -> bool | None:
|
||||
"""해를 끼칠 수 있는 도구를 차단합니다."""
|
||||
destructive_tools = [
|
||||
'delete_file',
|
||||
'drop_table',
|
||||
'remove_user',
|
||||
'system_shutdown'
|
||||
]
|
||||
|
||||
if context.tool_name in destructive_tools:
|
||||
print(f"🛑 파괴적인 도구 차단됨: {context.tool_name}")
|
||||
return False
|
||||
|
||||
# 민감한 작업에 대해 경고
|
||||
sensitive_tools = ['send_email', 'post_to_social_media', 'charge_payment']
|
||||
if context.tool_name in sensitive_tools:
|
||||
print(f"⚠️ 민감한 도구 실행 중: {context.tool_name}")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. 사람의 승인 게이트
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval_for_actions(context: ToolCallHookContext) -> bool | None:
|
||||
"""특정 작업에 대한 승인을 요구합니다."""
|
||||
approval_required = [
|
||||
'send_email',
|
||||
'make_purchase',
|
||||
'delete_file',
|
||||
'post_message'
|
||||
]
|
||||
|
||||
if context.tool_name in approval_required:
|
||||
response = context.request_human_input(
|
||||
prompt=f"{context.tool_name}을(를) 승인하시겠습니까?",
|
||||
default_message=f"입력: {context.tool_input}\n승인하려면 'yes'를 입력하세요:"
|
||||
)
|
||||
|
||||
if response.lower() != 'yes':
|
||||
print(f"❌ 도구 실행 거부됨: {context.tool_name}")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. 입력 검증 및 정제
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def validate_and_sanitize_inputs(context: ToolCallHookContext) -> bool | None:
|
||||
"""입력을 검증하고 정제합니다."""
|
||||
# 검색 쿼리 검증
|
||||
if context.tool_name == 'web_search':
|
||||
query = context.tool_input.get('query', '')
|
||||
if len(query) < 3:
|
||||
print("❌ 검색 쿼리가 너무 짧습니다")
|
||||
return False
|
||||
|
||||
# 쿼리 정제
|
||||
context.tool_input['query'] = query.strip().lower()
|
||||
|
||||
# 파일 경로 검증
|
||||
if context.tool_name == 'read_file':
|
||||
path = context.tool_input.get('path', '')
|
||||
if '..' in path or path.startswith('/'):
|
||||
print("❌ 잘못된 파일 경로")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. 결과 정제
|
||||
|
||||
```python
|
||||
@after_tool_call
|
||||
def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
|
||||
"""민감한 데이터를 정제합니다."""
|
||||
if not context.tool_result:
|
||||
return None
|
||||
|
||||
import re
|
||||
result = context.tool_result
|
||||
|
||||
# API 키 제거
|
||||
result = re.sub(
|
||||
r'(api[_-]?key|token)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r'\1: [수정됨]',
|
||||
result,
|
||||
flags=re.IGNORECASE
|
||||
)
|
||||
|
||||
# 이메일 주소 제거
|
||||
result = re.sub(
|
||||
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
'[이메일-수정됨]',
|
||||
result
|
||||
)
|
||||
|
||||
# 신용카드 번호 제거
|
||||
result = re.sub(
|
||||
r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b',
|
||||
'[카드-수정됨]',
|
||||
result
|
||||
)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
### 5. 도구 사용 분석
|
||||
|
||||
```python
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0, 'failures': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['_start_time'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_tool_usage(context: ToolCallHookContext) -> None:
|
||||
start_time = context.tool_input.get('_start_time', time.time())
|
||||
duration = time.time() - start_time
|
||||
|
||||
tool_stats[context.tool_name]['count'] += 1
|
||||
tool_stats[context.tool_name]['total_time'] += duration
|
||||
|
||||
if not context.tool_result or 'error' in context.tool_result.lower():
|
||||
tool_stats[context.tool_name]['failures'] += 1
|
||||
|
||||
print(f"""
|
||||
📊 {context.tool_name} 도구 통계:
|
||||
- 실행 횟수: {tool_stats[context.tool_name]['count']}
|
||||
- 평균 시간: {tool_stats[context.tool_name]['total_time'] / tool_stats[context.tool_name]['count']:.2f}초
|
||||
- 실패: {tool_stats[context.tool_name]['failures']}
|
||||
""")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. 속도 제한
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
tool_call_history = defaultdict(list)
|
||||
|
||||
@before_tool_call
|
||||
def rate_limit_tools(context: ToolCallHookContext) -> bool | None:
|
||||
"""도구 호출 속도를 제한합니다."""
|
||||
tool_name = context.tool_name
|
||||
now = datetime.now()
|
||||
|
||||
# 오래된 항목 정리 (1분 이상 된 것)
|
||||
tool_call_history[tool_name] = [
|
||||
call_time for call_time in tool_call_history[tool_name]
|
||||
if now - call_time < timedelta(minutes=1)
|
||||
]
|
||||
|
||||
# 속도 제한 확인 (분당 최대 10회 호출)
|
||||
if len(tool_call_history[tool_name]) >= 10:
|
||||
print(f"🚫 {tool_name}에 대한 속도 제한 초과")
|
||||
return False
|
||||
|
||||
# 이 호출 기록
|
||||
tool_call_history[tool_name].append(now)
|
||||
return None
|
||||
```
|
||||
|
||||
### 7. 디버그 로깅
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def debug_tool_call(context: ToolCallHookContext) -> None:
|
||||
"""도구 호출을 디버그합니다."""
|
||||
print(f"""
|
||||
🔍 도구 호출 디버그:
|
||||
- 도구: {context.tool_name}
|
||||
- 에이전트: {context.agent.role if context.agent else '알 수 없음'}
|
||||
- 작업: {context.task.description[:50] if context.task else '알 수 없음'}...
|
||||
- 입력: {context.tool_input}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def debug_tool_result(context: ToolCallHookContext) -> None:
|
||||
"""도구 결과를 디버그합니다."""
|
||||
if context.tool_result:
|
||||
result_preview = context.tool_result[:200]
|
||||
print(f"✅ 결과 미리보기: {result_preview}...")
|
||||
else:
|
||||
print("⚠️ 반환된 결과 없음")
|
||||
return None
|
||||
```
|
||||
|
||||
## 훅 관리
|
||||
|
||||
### 훅 등록 해제
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_tool_call_hook,
|
||||
unregister_after_tool_call_hook
|
||||
)
|
||||
|
||||
# 특정 훅 등록 해제
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_tool_call_hook(my_hook)
|
||||
# 나중에...
|
||||
success = unregister_before_tool_call_hook(my_hook)
|
||||
print(f"등록 해제됨: {success}")
|
||||
```
|
||||
|
||||
### 훅 지우기
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks,
|
||||
clear_all_tool_call_hooks
|
||||
)
|
||||
|
||||
# 특정 훅 타입 지우기
|
||||
count = clear_before_tool_call_hooks()
|
||||
print(f"{count}개의 전(before) 훅이 지워졌습니다")
|
||||
|
||||
# 모든 도구 훅 지우기
|
||||
before_count, after_count = clear_all_tool_call_hooks()
|
||||
print(f"{before_count}개의 전(before) 훅과 {after_count}개의 후(after) 훅이 지워졌습니다")
|
||||
```
|
||||
|
||||
## 고급 패턴
|
||||
|
||||
### 조건부 훅 실행
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def conditional_blocking(context: ToolCallHookContext) -> bool | None:
|
||||
"""특정 조건에서만 차단합니다."""
|
||||
# 특정 에이전트에 대해서만 차단
|
||||
if context.agent and context.agent.role == "junior_agent":
|
||||
if context.tool_name in ['delete_file', 'send_email']:
|
||||
print(f"❌ 주니어 에이전트는 {context.tool_name}을(를) 사용할 수 없습니다")
|
||||
return False
|
||||
|
||||
# 특정 작업 중에만 차단
|
||||
if context.task and "민감한" in context.task.description.lower():
|
||||
if context.tool_name == 'web_search':
|
||||
print("❌ 민감한 작업에서는 웹 검색이 차단됩니다")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 컨텍스트 인식 입력 수정
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def enhance_tool_inputs(context: ToolCallHookContext) -> None:
|
||||
"""에이전트 역할에 따라 컨텍스트를 추가합니다."""
|
||||
# 에이전트 역할에 따라 컨텍스트 추가
|
||||
if context.agent and context.agent.role == "researcher":
|
||||
if context.tool_name == 'web_search':
|
||||
# 연구원에 대한 도메인 제한 추가
|
||||
context.tool_input['domains'] = ['edu', 'gov', 'org']
|
||||
|
||||
# 작업에 따라 컨텍스트 추가
|
||||
if context.task and "긴급" in context.task.description.lower():
|
||||
if context.tool_name == 'send_email':
|
||||
context.tool_input['priority'] = 'high'
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
## 모범 사례
|
||||
|
||||
1. **훅을 집중적으로 유지**: 각 훅은 단일 책임을 가져야 합니다
|
||||
2. **무거운 계산 피하기**: 훅은 모든 도구 호출마다 실행됩니다
|
||||
3. **오류를 우아하게 처리**: try-except를 사용하여 훅 실패 방지
|
||||
4. **타입 힌트 사용**: 더 나은 IDE 지원을 위해 `ToolCallHookContext` 활용
|
||||
5. **차단 조건 문서화**: 도구가 차단되는 시기/이유를 명확히 하세요
|
||||
6. **훅을 독립적으로 테스트**: 프로덕션에서 사용하기 전에 단위 테스트
|
||||
7. **테스트에서 훅 지우기**: 테스트 실행 간 `clear_all_tool_call_hooks()` 사용
|
||||
8. **제자리에서 수정**: 항상 `context.tool_input`을 제자리에서 수정하고 교체하지 마세요
|
||||
9. **중요한 결정 로깅**: 특히 도구 실행을 차단할 때
|
||||
10. **성능 고려**: 가능한 경우 비용이 많이 드는 검증을 캐시
|
||||
|
||||
## 오류 처리
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safe_validation(context: ToolCallHookContext) -> bool | None:
|
||||
try:
|
||||
# 검증 로직
|
||||
if not validate_input(context.tool_input):
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ 훅 오류: {e}")
|
||||
# 결정: 오류 발생 시 허용 또는 차단
|
||||
return None # 오류에도 불구하고 실행 허용
|
||||
```
|
||||
|
||||
## 타입 안전성
|
||||
|
||||
```python
|
||||
from crewai.hooks import ToolCallHookContext, BeforeToolCallHookType, AfterToolCallHookType
|
||||
|
||||
# 명시적 타입 주석
|
||||
def my_before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# 타입 안전 등록
|
||||
register_before_tool_call_hook(my_before_hook)
|
||||
register_after_tool_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## 문제 해결
|
||||
|
||||
### 훅이 실행되지 않음
|
||||
- 크루 실행 전에 훅이 등록되었는지 확인
|
||||
- 이전 훅이 `False`를 반환했는지 확인 (실행 및 후속 훅 차단)
|
||||
- 훅 시그니처가 예상 타입과 일치하는지 확인
|
||||
|
||||
### 입력 수정이 작동하지 않음
|
||||
- 제자리 수정 사용: `context.tool_input['key'] = value`
|
||||
- 딕셔너리를 교체하지 마세요: `context.tool_input = {}`
|
||||
|
||||
### 결과 수정이 작동하지 않음
|
||||
- 후 훅에서 수정된 문자열을 반환
|
||||
- `None`을 반환하면 원본 결과가 유지됩니다
|
||||
- 도구가 실제로 결과를 반환했는지 확인
|
||||
|
||||
### 도구가 예기치 않게 차단됨
|
||||
- 차단 조건에 대한 모든 전(before) 훅 확인
|
||||
- 훅 실행 순서 확인
|
||||
- 어떤 훅이 차단하는지 식별하기 위해 디버그 로깅 추가
|
||||
|
||||
## 결론
|
||||
|
||||
도구 호출 훅은 CrewAI에서 도구 실행을 제어하고 모니터링하는 강력한 기능을 제공합니다. 이를 사용하여 안전 가드레일, 승인 게이트, 입력 검증, 결과 정제, 로깅 및 분석을 구현하세요. 적절한 오류 처리 및 타입 안전성과 결합하면, 훅을 통해 포괄적인 관찰성을 갖춘 안전하고 프로덕션 준비가 된 에이전트 시스템을 구축할 수 있습니다.
|
||||
|
||||
379
docs/pt-BR/learn/execution-hooks.mdx
Normal file
379
docs/pt-BR/learn/execution-hooks.mdx
Normal file
@@ -0,0 +1,379 @@
|
||||
---
|
||||
title: Visão Geral dos Hooks de Execução
|
||||
description: Entendendo e usando hooks de execução no CrewAI para controle fino sobre operações de agentes
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Os Hooks de Execução fornecem controle fino sobre o comportamento em tempo de execução dos seus agentes CrewAI. Diferentemente dos hooks de kickoff que são executados antes e depois da execução da crew, os hooks de execução interceptam operações específicas durante a execução do agente, permitindo que você modifique comportamentos, implemente verificações de segurança e adicione monitoramento abrangente.
|
||||
|
||||
## Tipos de Hooks de Execução
|
||||
|
||||
O CrewAI fornece duas categorias principais de hooks de execução:
|
||||
|
||||
### 1. [Hooks de Chamada LLM](/learn/llm-hooks)
|
||||
|
||||
Controle e monitore interações com o modelo de linguagem:
|
||||
- **Antes da Chamada LLM**: Modifique prompts, valide entradas, implemente gates de aprovação
|
||||
- **Depois da Chamada LLM**: Transforme respostas, sanitize saídas, atualize histórico de conversação
|
||||
|
||||
**Casos de Uso:**
|
||||
- Limitação de iterações
|
||||
- Rastreamento de custos e monitoramento de uso de tokens
|
||||
- Sanitização de respostas e filtragem de conteúdo
|
||||
- Aprovação humana para chamadas LLM
|
||||
- Adição de diretrizes de segurança ou contexto
|
||||
- Logging de debug e inspeção de requisição/resposta
|
||||
|
||||
[Ver Documentação de Hooks LLM →](/learn/llm-hooks)
|
||||
|
||||
### 2. [Hooks de Chamada de Ferramenta](/learn/tool-hooks)
|
||||
|
||||
Controle e monitore execução de ferramentas:
|
||||
- **Antes da Chamada de Ferramenta**: Modifique entradas, valide parâmetros, bloqueie operações perigosas
|
||||
- **Depois da Chamada de Ferramenta**: Transforme resultados, sanitize saídas, registre detalhes de execução
|
||||
|
||||
**Casos de Uso:**
|
||||
- Guardrails de segurança para operações destrutivas
|
||||
- Aprovação humana para ações sensíveis
|
||||
- Validação e sanitização de entrada
|
||||
- Cache de resultados e limitação de taxa
|
||||
- Análise de uso de ferramentas
|
||||
- Logging de debug e monitoramento
|
||||
|
||||
[Ver Documentação de Hooks de Ferramenta →](/learn/tool-hooks)
|
||||
|
||||
## Métodos de Registro
|
||||
|
||||
### 1. Hooks Baseados em Decoradores (Recomendado)
|
||||
|
||||
A maneira mais limpa e pythônica de registrar hooks:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call, before_tool_call, after_tool_call
|
||||
|
||||
@before_llm_call
|
||||
def limit_iterations(context):
|
||||
"""Previne loops infinitos limitando iterações."""
|
||||
if context.iterations > 10:
|
||||
return False # Bloquear execução
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
"""Remove dados sensíveis das respostas do LLM."""
|
||||
if "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[CENSURADO]")
|
||||
return None
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
"""Bloqueia operações destrutivas."""
|
||||
if context.tool_name == "delete_database":
|
||||
return False # Bloquear execução
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def log_tool_result(context):
|
||||
"""Registra execução de ferramenta."""
|
||||
print(f"Ferramenta {context.tool_name} concluída")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Hooks com Escopo de Crew
|
||||
|
||||
Aplica hooks apenas a instâncias específicas de crew:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# Aplica-se apenas a esta crew
|
||||
print(f"Chamada LLM em {self.__class__.__name__}")
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_results(self, context):
|
||||
# Logging específico da crew
|
||||
print(f"Resultado da ferramenta: {context.tool_result[:50]}...")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential
|
||||
)
|
||||
```
|
||||
|
||||
## Fluxo de Execução de Hooks
|
||||
|
||||
### Fluxo de Chamada LLM
|
||||
|
||||
```
|
||||
Agente precisa chamar LLM
|
||||
↓
|
||||
[Hooks Antes da Chamada LLM Executam]
|
||||
├→ Hook 1: Validar contagem de iterações
|
||||
├→ Hook 2: Adicionar contexto de segurança
|
||||
└→ Hook 3: Registrar requisição
|
||||
↓
|
||||
Se algum hook retornar False:
|
||||
├→ Bloquear chamada LLM
|
||||
└→ Lançar ValueError
|
||||
↓
|
||||
Se todos os hooks retornarem True/None:
|
||||
├→ Chamada LLM prossegue
|
||||
└→ Resposta gerada
|
||||
↓
|
||||
[Hooks Depois da Chamada LLM Executam]
|
||||
├→ Hook 1: Sanitizar resposta
|
||||
├→ Hook 2: Registrar resposta
|
||||
└→ Hook 3: Atualizar métricas
|
||||
↓
|
||||
Resposta final retornada
|
||||
```
|
||||
|
||||
### Fluxo de Chamada de Ferramenta
|
||||
|
||||
```
|
||||
Agente precisa executar ferramenta
|
||||
↓
|
||||
[Hooks Antes da Chamada de Ferramenta Executam]
|
||||
├→ Hook 1: Verificar se ferramenta é permitida
|
||||
├→ Hook 2: Validar entradas
|
||||
└→ Hook 3: Solicitar aprovação se necessário
|
||||
↓
|
||||
Se algum hook retornar False:
|
||||
├→ Bloquear execução da ferramenta
|
||||
└→ Retornar mensagem de erro
|
||||
↓
|
||||
Se todos os hooks retornarem True/None:
|
||||
├→ Execução da ferramenta prossegue
|
||||
└→ Resultado gerado
|
||||
↓
|
||||
[Hooks Depois da Chamada de Ferramenta Executam]
|
||||
├→ Hook 1: Sanitizar resultado
|
||||
├→ Hook 2: Fazer cache do resultado
|
||||
└→ Hook 3: Registrar métricas
|
||||
↓
|
||||
Resultado final retornado
|
||||
```
|
||||
|
||||
## Objetos de Contexto de Hook
|
||||
|
||||
### LLMCallHookContext
|
||||
|
||||
Fornece acesso ao estado de execução do LLM:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # Acesso completo ao executor
|
||||
messages: list # Lista de mensagens mutável
|
||||
agent: Agent # Agente atual
|
||||
task: Task # Tarefa atual
|
||||
crew: Crew # Instância da crew
|
||||
llm: BaseLLM # Instância do LLM
|
||||
iterations: int # Iteração atual
|
||||
response: str | None # Resposta do LLM (hooks posteriores)
|
||||
```
|
||||
|
||||
### ToolCallHookContext
|
||||
|
||||
Fornece acesso ao estado de execução da ferramenta:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # Ferramenta sendo chamada
|
||||
tool_input: dict # Parâmetros de entrada mutáveis
|
||||
tool: CrewStructuredTool # Instância da ferramenta
|
||||
agent: Agent | None # Agente executando
|
||||
task: Task | None # Tarefa atual
|
||||
crew: Crew | None # Instância da crew
|
||||
tool_result: str | None # Resultado da ferramenta (hooks posteriores)
|
||||
```
|
||||
|
||||
## Padrões Comuns
|
||||
|
||||
### Segurança e Validação
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context):
|
||||
"""Bloqueia operações destrutivas."""
|
||||
dangerous = ['delete_file', 'drop_table', 'system_shutdown']
|
||||
if context.tool_name in dangerous:
|
||||
print(f"🛑 Bloqueado: {context.tool_name}")
|
||||
return False
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def iteration_limit(context):
|
||||
"""Previne loops infinitos."""
|
||||
if context.iterations > 15:
|
||||
print("⛔ Máximo de iterações excedido")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### Humano no Loop
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval(context):
|
||||
"""Requer aprovação para operações sensíveis."""
|
||||
sensitive = ['send_email', 'make_payment', 'post_message']
|
||||
|
||||
if context.tool_name in sensitive:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Aprovar {context.tool_name}?",
|
||||
default_message="Digite 'sim' para aprovar:"
|
||||
)
|
||||
|
||||
if response.lower() != 'sim':
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Monitoramento e Análise
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
metrics = defaultdict(lambda: {'count': 0, 'total_time': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context):
|
||||
context.tool_input['_start'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_metrics(context):
|
||||
start = context.tool_input.get('_start', time.time())
|
||||
duration = time.time() - start
|
||||
|
||||
metrics[context.tool_name]['count'] += 1
|
||||
metrics[context.tool_name]['total_time'] += duration
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
## Gerenciamento de Hooks
|
||||
|
||||
### Limpar Todos os Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
# Limpa todos os hooks de uma vez
|
||||
result = clear_all_global_hooks()
|
||||
print(f"Limpou {result['total']} hooks")
|
||||
```
|
||||
|
||||
### Limpar Tipos Específicos de Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks
|
||||
)
|
||||
|
||||
# Limpar tipos específicos
|
||||
llm_before_count = clear_before_llm_call_hooks()
|
||||
tool_after_count = clear_after_tool_call_hooks()
|
||||
```
|
||||
|
||||
## Melhores Práticas
|
||||
|
||||
### 1. Mantenha os Hooks Focados
|
||||
Cada hook deve ter uma responsabilidade única e clara.
|
||||
|
||||
### 2. Trate Erros Graciosamente
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context):
|
||||
try:
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Erro no hook: {e}")
|
||||
return None # Permitir execução apesar do erro
|
||||
```
|
||||
|
||||
### 3. Modifique o Contexto In-Place
|
||||
```python
|
||||
# ✅ Correto - modificar in-place
|
||||
@before_llm_call
|
||||
def add_context(context):
|
||||
context.messages.append({"role": "system", "content": "Seja conciso"})
|
||||
|
||||
# ❌ Errado - substitui referência
|
||||
@before_llm_call
|
||||
def wrong_approach(context):
|
||||
context.messages = [{"role": "system", "content": "Seja conciso"}]
|
||||
```
|
||||
|
||||
### 4. Use Type Hints
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, ToolCallHookContext
|
||||
|
||||
def my_llm_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_tool_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
```
|
||||
|
||||
### 5. Limpe em Testes
|
||||
```python
|
||||
import pytest
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_hooks():
|
||||
"""Reseta hooks antes de cada teste."""
|
||||
yield
|
||||
clear_all_global_hooks()
|
||||
```
|
||||
|
||||
## Quando Usar Qual Hook
|
||||
|
||||
### Use Hooks LLM Quando:
|
||||
- Implementar limites de iteração
|
||||
- Adicionar contexto ou diretrizes de segurança aos prompts
|
||||
- Rastrear uso de tokens e custos
|
||||
- Sanitizar ou transformar respostas
|
||||
- Implementar gates de aprovação para chamadas LLM
|
||||
- Fazer debug de interações de prompt/resposta
|
||||
|
||||
### Use Hooks de Ferramenta Quando:
|
||||
- Bloquear operações perigosas ou destrutivas
|
||||
- Validar entradas de ferramenta antes da execução
|
||||
- Implementar gates de aprovação para ações sensíveis
|
||||
- Fazer cache de resultados de ferramenta
|
||||
- Rastrear uso e performance de ferramentas
|
||||
- Sanitizar saídas de ferramenta
|
||||
- Limitar taxa de chamadas de ferramenta
|
||||
|
||||
### Use Ambos Quando:
|
||||
Construir sistemas abrangentes de observabilidade, segurança ou aprovação que precisam monitorar todas as operações do agente.
|
||||
|
||||
## Documentação Relacionada
|
||||
|
||||
- [Hooks de Chamada LLM →](/learn/llm-hooks) - Documentação detalhada de hooks LLM
|
||||
- [Hooks de Chamada de Ferramenta →](/learn/tool-hooks) - Documentação detalhada de hooks de ferramenta
|
||||
- [Hooks Antes e Depois do Kickoff →](/learn/before-and-after-kickoff-hooks) - Hooks do ciclo de vida da crew
|
||||
- [Humano no Loop →](/learn/human-in-the-loop) - Padrões de entrada humana
|
||||
|
||||
## Conclusão
|
||||
|
||||
Os Hooks de Execução fornecem controle poderoso sobre o comportamento em tempo de execução do agente. Use-os para implementar guardrails de segurança, fluxos de trabalho de aprovação, monitoramento abrangente e lógica de negócio personalizada. Combinados com tratamento adequado de erros, segurança de tipos e considerações de performance, os hooks permitem sistemas de agentes seguros, prontos para produção e observáveis.
|
||||
388
docs/pt-BR/learn/llm-hooks.mdx
Normal file
388
docs/pt-BR/learn/llm-hooks.mdx
Normal file
@@ -0,0 +1,388 @@
|
||||
---
|
||||
title: Hooks de Chamada LLM
|
||||
description: Aprenda a usar hooks de chamada LLM para interceptar, modificar e controlar interações com modelos de linguagem no CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Os Hooks de Chamada LLM fornecem controle fino sobre interações com modelos de linguagem durante a execução do agente. Esses hooks permitem interceptar chamadas LLM, modificar prompts, transformar respostas, implementar gates de aprovação e adicionar logging ou monitoramento personalizado.
|
||||
|
||||
## Visão Geral
|
||||
|
||||
Os hooks LLM são executados em dois pontos críticos:
|
||||
- **Antes da Chamada LLM**: Modificar mensagens, validar entradas ou bloquear execução
|
||||
- **Depois da Chamada LLM**: Transformar respostas, sanitizar saídas ou modificar histórico de conversação
|
||||
|
||||
## Tipos de Hook
|
||||
|
||||
### Hooks Antes da Chamada LLM
|
||||
|
||||
Executados antes de cada chamada LLM, esses hooks podem:
|
||||
- Inspecionar e modificar mensagens enviadas ao LLM
|
||||
- Bloquear execução LLM com base em condições
|
||||
- Implementar limitação de taxa ou gates de aprovação
|
||||
- Adicionar contexto ou mensagens do sistema
|
||||
- Registrar detalhes da requisição
|
||||
|
||||
**Assinatura:**
|
||||
```python
|
||||
def before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# Retorne False para bloquear execução
|
||||
# Retorne True ou None para permitir execução
|
||||
...
|
||||
```
|
||||
|
||||
### Hooks Depois da Chamada LLM
|
||||
|
||||
Executados depois de cada chamada LLM, esses hooks podem:
|
||||
- Modificar ou sanitizar respostas do LLM
|
||||
- Adicionar metadados ou formatação
|
||||
- Registrar detalhes da resposta
|
||||
- Atualizar histórico de conversação
|
||||
- Implementar filtragem de conteúdo
|
||||
|
||||
**Assinatura:**
|
||||
```python
|
||||
def after_hook(context: LLMCallHookContext) -> str | None:
|
||||
# Retorne string de resposta modificada
|
||||
# Retorne None para manter resposta original
|
||||
...
|
||||
```
|
||||
|
||||
## Contexto do Hook LLM
|
||||
|
||||
O objeto `LLMCallHookContext` fornece acesso abrangente ao estado de execução:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # Referência completa ao executor
|
||||
messages: list # Lista de mensagens mutável
|
||||
agent: Agent # Agente atual
|
||||
task: Task # Tarefa atual
|
||||
crew: Crew # Instância da crew
|
||||
llm: BaseLLM # Instância do LLM
|
||||
iterations: int # Contagem de iteração atual
|
||||
response: str | None # Resposta do LLM (apenas hooks posteriores)
|
||||
```
|
||||
|
||||
### Modificando Mensagens
|
||||
|
||||
**Importante:** Sempre modifique mensagens in-place:
|
||||
|
||||
```python
|
||||
# ✅ Correto - modificar in-place
|
||||
def add_context(context: LLMCallHookContext) -> None:
|
||||
context.messages.append({"role": "system", "content": "Seja conciso"})
|
||||
|
||||
# ❌ Errado - substitui referência da lista
|
||||
def wrong_approach(context: LLMCallHookContext) -> None:
|
||||
context.messages = [{"role": "system", "content": "Seja conciso"}]
|
||||
```
|
||||
|
||||
## Métodos de Registro
|
||||
|
||||
### 1. Registro Baseado em Decoradores (Recomendado)
|
||||
|
||||
Use decoradores para sintaxe mais limpa:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call
|
||||
|
||||
@before_llm_call
|
||||
def validate_iteration_count(context):
|
||||
"""Valida a contagem de iterações."""
|
||||
if context.iterations > 10:
|
||||
print("⚠️ Máximo de iterações excedido")
|
||||
return False # Bloquear execução
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
"""Remove dados sensíveis."""
|
||||
if context.response and "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[CENSURADO]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Hooks com Escopo de Crew
|
||||
|
||||
Registre hooks para uma instância específica de crew:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_llm_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# Aplica-se apenas a esta crew
|
||||
if context.iterations == 0:
|
||||
print(f"Iniciando tarefa: {context.task.description}")
|
||||
return None
|
||||
|
||||
@after_llm_call_crew
|
||||
def log_responses(self, context):
|
||||
# Logging específico da crew
|
||||
print(f"Comprimento da resposta: {len(context.response)}")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## Casos de Uso Comuns
|
||||
|
||||
### 1. Limitação de Iterações
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def limit_iterations(context: LLMCallHookContext) -> bool | None:
|
||||
"""Previne loops infinitos limitando iterações."""
|
||||
max_iterations = 15
|
||||
if context.iterations > max_iterations:
|
||||
print(f"⛔ Bloqueado: Excedeu {max_iterations} iterações")
|
||||
return False # Bloquear execução
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Gate de Aprovação Humana
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def require_approval(context: LLMCallHookContext) -> bool | None:
|
||||
"""Requer aprovação após certas iterações."""
|
||||
if context.iterations > 5:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Iteração {context.iterations}: Aprovar chamada LLM?",
|
||||
default_message="Pressione Enter para aprovar, ou digite 'não' para bloquear:"
|
||||
)
|
||||
if response.lower() == "não":
|
||||
print("🚫 Chamada LLM bloqueada pelo usuário")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Adicionando Contexto do Sistema
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def add_guardrails(context: LLMCallHookContext) -> None:
|
||||
"""Adiciona diretrizes de segurança a cada chamada LLM."""
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Garanta que as respostas sejam factuais e cite fontes quando possível."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. Sanitização de Resposta
|
||||
|
||||
```python
|
||||
@after_llm_call
|
||||
def sanitize_sensitive_data(context: LLMCallHookContext) -> str | None:
|
||||
"""Remove padrões sensíveis."""
|
||||
if not context.response:
|
||||
return None
|
||||
|
||||
import re
|
||||
sanitized = context.response
|
||||
sanitized = re.sub(r'\b\d{3}\.\d{3}\.\d{3}-\d{2}\b', '[CPF-CENSURADO]', sanitized)
|
||||
sanitized = re.sub(r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b', '[CARTÃO-CENSURADO]', sanitized)
|
||||
|
||||
return sanitized
|
||||
```
|
||||
|
||||
### 5. Rastreamento de Custos
|
||||
|
||||
```python
|
||||
import tiktoken
|
||||
|
||||
@before_llm_call
|
||||
def track_token_usage(context: LLMCallHookContext) -> None:
|
||||
"""Rastreia tokens de entrada."""
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
total_tokens = sum(
|
||||
len(encoding.encode(msg.get("content", "")))
|
||||
for msg in context.messages
|
||||
)
|
||||
print(f"📊 Tokens de entrada: ~{total_tokens}")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def track_response_tokens(context: LLMCallHookContext) -> None:
|
||||
"""Rastreia tokens de resposta."""
|
||||
if context.response:
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
tokens = len(encoding.encode(context.response))
|
||||
print(f"📊 Tokens de resposta: ~{tokens}")
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. Logging de Debug
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def debug_request(context: LLMCallHookContext) -> None:
|
||||
"""Debug de requisição LLM."""
|
||||
print(f"""
|
||||
🔍 Debug de Chamada LLM:
|
||||
- Agente: {context.agent.role}
|
||||
- Tarefa: {context.task.description[:50]}...
|
||||
- Iteração: {context.iterations}
|
||||
- Contagem de Mensagens: {len(context.messages)}
|
||||
- Última Mensagem: {context.messages[-1] if context.messages else 'Nenhuma'}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def debug_response(context: LLMCallHookContext) -> None:
|
||||
"""Debug de resposta LLM."""
|
||||
if context.response:
|
||||
print(f"✅ Preview da Resposta: {context.response[:100]}...")
|
||||
return None
|
||||
```
|
||||
|
||||
## Gerenciamento de Hooks
|
||||
|
||||
### Desregistrando Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_llm_call_hook
|
||||
)
|
||||
|
||||
# Desregistrar hook específico
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_llm_call_hook(my_hook)
|
||||
# Mais tarde...
|
||||
unregister_before_llm_call_hook(my_hook) # Retorna True se encontrado
|
||||
```
|
||||
|
||||
### Limpando Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_all_llm_call_hooks
|
||||
)
|
||||
|
||||
# Limpar tipo específico de hook
|
||||
count = clear_before_llm_call_hooks()
|
||||
print(f"Limpou {count} hooks antes")
|
||||
|
||||
# Limpar todos os hooks LLM
|
||||
before_count, after_count = clear_all_llm_call_hooks()
|
||||
print(f"Limpou {before_count} hooks antes e {after_count} hooks depois")
|
||||
```
|
||||
|
||||
## Padrões Avançados
|
||||
|
||||
### Execução Condicional de Hook
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def conditional_blocking(context: LLMCallHookContext) -> bool | None:
|
||||
"""Bloqueia apenas em condições específicas."""
|
||||
# Bloquear apenas para agentes específicos
|
||||
if context.agent.role == "researcher" and context.iterations > 10:
|
||||
return False
|
||||
|
||||
# Bloquear apenas para tarefas específicas
|
||||
if "sensível" in context.task.description.lower() and context.iterations > 5:
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Modificações com Consciência de Contexto
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def adaptive_prompting(context: LLMCallHookContext) -> None:
|
||||
"""Adiciona contexto diferente baseado na iteração."""
|
||||
if context.iterations == 0:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Comece com uma visão geral de alto nível."
|
||||
})
|
||||
elif context.iterations > 3:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Foque em detalhes específicos e forneça exemplos."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
## Melhores Práticas
|
||||
|
||||
1. **Mantenha Hooks Focados**: Cada hook deve ter uma responsabilidade única
|
||||
2. **Evite Computação Pesada**: Hooks executam em cada chamada LLM
|
||||
3. **Trate Erros Graciosamente**: Use try-except para prevenir falhas de hooks
|
||||
4. **Use Type Hints**: Aproveite `LLMCallHookContext` para melhor suporte IDE
|
||||
5. **Documente Comportamento do Hook**: Especialmente para condições de bloqueio
|
||||
6. **Teste Hooks Independentemente**: Teste unitário de hooks antes de usar em produção
|
||||
7. **Limpe Hooks em Testes**: Use `clear_all_llm_call_hooks()` entre execuções de teste
|
||||
8. **Modifique In-Place**: Sempre modifique `context.messages` in-place, nunca substitua
|
||||
|
||||
## Tratamento de Erros
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context: LLMCallHookContext) -> bool | None:
|
||||
try:
|
||||
# Sua lógica de hook
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Erro no hook: {e}")
|
||||
# Decida: permitir ou bloquear em erro
|
||||
return None # Permitir execução apesar do erro
|
||||
```
|
||||
|
||||
## Segurança de Tipos
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, BeforeLLMCallHookType, AfterLLMCallHookType
|
||||
|
||||
# Anotações de tipo explícitas
|
||||
def my_before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: LLMCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Registro type-safe
|
||||
register_before_llm_call_hook(my_before_hook)
|
||||
register_after_llm_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## Solução de Problemas
|
||||
|
||||
### Hook Não Está Executando
|
||||
- Verifique se o hook está registrado antes da execução da crew
|
||||
- Verifique se hook anterior retornou `False` (bloqueia hooks subsequentes)
|
||||
- Garanta que assinatura do hook corresponda ao tipo esperado
|
||||
|
||||
### Modificações de Mensagem Não Persistem
|
||||
- Use modificações in-place: `context.messages.append()`
|
||||
- Não substitua a lista: `context.messages = []`
|
||||
|
||||
### Modificações de Resposta Não Funcionam
|
||||
- Retorne a string modificada dos hooks posteriores
|
||||
- Retornar `None` mantém a resposta original
|
||||
|
||||
## Conclusão
|
||||
|
||||
Os Hooks de Chamada LLM fornecem capacidades poderosas para controlar e monitorar interações com modelos de linguagem no CrewAI. Use-os para implementar guardrails de segurança, gates de aprovação, logging, rastreamento de custos e sanitização de respostas. Combinados com tratamento adequado de erros e segurança de tipos, os hooks permitem sistemas de agentes robustos e prontos para produção.
|
||||
|
||||
498
docs/pt-BR/learn/tool-hooks.mdx
Normal file
498
docs/pt-BR/learn/tool-hooks.mdx
Normal file
@@ -0,0 +1,498 @@
|
||||
---
|
||||
title: Hooks de Chamada de Ferramenta
|
||||
description: Aprenda a usar hooks de chamada de ferramenta para interceptar, modificar e controlar execução de ferramentas no CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Os Hooks de Chamada de Ferramenta fornecem controle fino sobre a execução de ferramentas durante operações do agente. Esses hooks permitem interceptar chamadas de ferramenta, modificar entradas, transformar saídas, implementar verificações de segurança e adicionar logging ou monitoramento abrangente.
|
||||
|
||||
## Visão Geral
|
||||
|
||||
Os hooks de ferramenta são executados em dois pontos críticos:
|
||||
- **Antes da Chamada de Ferramenta**: Modificar entradas, validar parâmetros ou bloquear execução
|
||||
- **Depois da Chamada de Ferramenta**: Transformar resultados, sanitizar saídas ou registrar detalhes de execução
|
||||
|
||||
## Tipos de Hook
|
||||
|
||||
### Hooks Antes da Chamada de Ferramenta
|
||||
|
||||
Executados antes de cada execução de ferramenta, esses hooks podem:
|
||||
- Inspecionar e modificar entradas de ferramenta
|
||||
- Bloquear execução de ferramenta com base em condições
|
||||
- Implementar gates de aprovação para operações perigosas
|
||||
- Validar parâmetros
|
||||
- Registrar invocações de ferramenta
|
||||
|
||||
**Assinatura:**
|
||||
```python
|
||||
def before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
# Retorne False para bloquear execução
|
||||
# Retorne True ou None para permitir execução
|
||||
...
|
||||
```
|
||||
|
||||
### Hooks Depois da Chamada de Ferramenta
|
||||
|
||||
Executados depois de cada execução de ferramenta, esses hooks podem:
|
||||
- Modificar ou sanitizar resultados de ferramenta
|
||||
- Adicionar metadados ou formatação
|
||||
- Registrar resultados de execução
|
||||
- Implementar validação de resultado
|
||||
- Transformar formatos de saída
|
||||
|
||||
**Assinatura:**
|
||||
```python
|
||||
def after_hook(context: ToolCallHookContext) -> str | None:
|
||||
# Retorne string de resultado modificado
|
||||
# Retorne None para manter resultado original
|
||||
...
|
||||
```
|
||||
|
||||
## Contexto do Hook de Ferramenta
|
||||
|
||||
O objeto `ToolCallHookContext` fornece acesso abrangente ao estado de execução da ferramenta:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # Nome da ferramenta sendo chamada
|
||||
tool_input: dict[str, Any] # Parâmetros de entrada mutáveis da ferramenta
|
||||
tool: CrewStructuredTool # Referência da instância da ferramenta
|
||||
agent: Agent | BaseAgent | None # Agente executando a ferramenta
|
||||
task: Task | None # Tarefa atual
|
||||
crew: Crew | None # Instância da crew
|
||||
tool_result: str | None # Resultado da ferramenta (apenas hooks posteriores)
|
||||
```
|
||||
|
||||
### Modificando Entradas de Ferramenta
|
||||
|
||||
**Importante:** Sempre modifique entradas de ferramenta in-place:
|
||||
|
||||
```python
|
||||
# ✅ Correto - modificar in-place
|
||||
def sanitize_input(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['query'] = context.tool_input['query'].lower()
|
||||
|
||||
# ❌ Errado - substitui referência do dict
|
||||
def wrong_approach(context: ToolCallHookContext) -> None:
|
||||
context.tool_input = {'query': 'nova consulta'}
|
||||
```
|
||||
|
||||
## Métodos de Registro
|
||||
|
||||
### 1. Registro Baseado em Decoradores (Recomendado)
|
||||
|
||||
Use decoradores para sintaxe mais limpa:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_tool_call, after_tool_call
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
"""Bloqueia ferramentas perigosas."""
|
||||
dangerous_tools = ['delete_database', 'drop_table', 'rm_rf']
|
||||
if context.tool_name in dangerous_tools:
|
||||
print(f"⛔ Ferramenta perigosa bloqueada: {context.tool_name}")
|
||||
return False # Bloquear execução
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def sanitize_results(context):
|
||||
"""Sanitiza resultados."""
|
||||
if context.tool_result and "password" in context.tool_result.lower():
|
||||
return context.tool_result.replace("password", "[CENSURADO]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Hooks com Escopo de Crew
|
||||
|
||||
Registre hooks para uma instância específica de crew:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_tool_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_tool_call_crew
|
||||
def validate_tool_inputs(self, context):
|
||||
# Aplica-se apenas a esta crew
|
||||
if context.tool_name == "web_search":
|
||||
if not context.tool_input.get('query'):
|
||||
print("❌ Consulta de busca inválida")
|
||||
return False
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_tool_results(self, context):
|
||||
# Logging de ferramenta específico da crew
|
||||
print(f"✅ {context.tool_name} concluída")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## Casos de Uso Comuns
|
||||
|
||||
### 1. Guardrails de Segurança
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context: ToolCallHookContext) -> bool | None:
|
||||
"""Bloqueia ferramentas que podem causar danos."""
|
||||
destructive_tools = [
|
||||
'delete_file',
|
||||
'drop_table',
|
||||
'remove_user',
|
||||
'system_shutdown'
|
||||
]
|
||||
|
||||
if context.tool_name in destructive_tools:
|
||||
print(f"🛑 Ferramenta destrutiva bloqueada: {context.tool_name}")
|
||||
return False
|
||||
|
||||
# Avisar em operações sensíveis
|
||||
sensitive_tools = ['send_email', 'post_to_social_media', 'charge_payment']
|
||||
if context.tool_name in sensitive_tools:
|
||||
print(f"⚠️ Executando ferramenta sensível: {context.tool_name}")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Gate de Aprovação Humana
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval_for_actions(context: ToolCallHookContext) -> bool | None:
|
||||
"""Requer aprovação para ações específicas."""
|
||||
approval_required = [
|
||||
'send_email',
|
||||
'make_purchase',
|
||||
'delete_file',
|
||||
'post_message'
|
||||
]
|
||||
|
||||
if context.tool_name in approval_required:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Aprovar {context.tool_name}?",
|
||||
default_message=f"Entrada: {context.tool_input}\nDigite 'sim' para aprovar:"
|
||||
)
|
||||
|
||||
if response.lower() != 'sim':
|
||||
print(f"❌ Execução de ferramenta negada: {context.tool_name}")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Validação e Sanitização de Entrada
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def validate_and_sanitize_inputs(context: ToolCallHookContext) -> bool | None:
|
||||
"""Valida e sanitiza entradas."""
|
||||
# Validar consultas de busca
|
||||
if context.tool_name == 'web_search':
|
||||
query = context.tool_input.get('query', '')
|
||||
if len(query) < 3:
|
||||
print("❌ Consulta de busca muito curta")
|
||||
return False
|
||||
|
||||
# Sanitizar consulta
|
||||
context.tool_input['query'] = query.strip().lower()
|
||||
|
||||
# Validar caminhos de arquivo
|
||||
if context.tool_name == 'read_file':
|
||||
path = context.tool_input.get('path', '')
|
||||
if '..' in path or path.startswith('/'):
|
||||
print("❌ Caminho de arquivo inválido")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. Sanitização de Resultado
|
||||
|
||||
```python
|
||||
@after_tool_call
|
||||
def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
|
||||
"""Sanitiza dados sensíveis."""
|
||||
if not context.tool_result:
|
||||
return None
|
||||
|
||||
import re
|
||||
result = context.tool_result
|
||||
|
||||
# Remover chaves de API
|
||||
result = re.sub(
|
||||
r'(api[_-]?key|token)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r'\1: [CENSURADO]',
|
||||
result,
|
||||
flags=re.IGNORECASE
|
||||
)
|
||||
|
||||
# Remover endereços de email
|
||||
result = re.sub(
|
||||
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
'[EMAIL-CENSURADO]',
|
||||
result
|
||||
)
|
||||
|
||||
# Remover números de cartão de crédito
|
||||
result = re.sub(
|
||||
r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b',
|
||||
'[CARTÃO-CENSURADO]',
|
||||
result
|
||||
)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
### 5. Análise de Uso de Ferramenta
|
||||
|
||||
```python
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0, 'failures': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['_start_time'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_tool_usage(context: ToolCallHookContext) -> None:
|
||||
start_time = context.tool_input.get('_start_time', time.time())
|
||||
duration = time.time() - start_time
|
||||
|
||||
tool_stats[context.tool_name]['count'] += 1
|
||||
tool_stats[context.tool_name]['total_time'] += duration
|
||||
|
||||
if not context.tool_result or 'error' in context.tool_result.lower():
|
||||
tool_stats[context.tool_name]['failures'] += 1
|
||||
|
||||
print(f"""
|
||||
📊 Estatísticas da Ferramenta {context.tool_name}:
|
||||
- Execuções: {tool_stats[context.tool_name]['count']}
|
||||
- Tempo Médio: {tool_stats[context.tool_name]['total_time'] / tool_stats[context.tool_name]['count']:.2f}s
|
||||
- Falhas: {tool_stats[context.tool_name]['failures']}
|
||||
""")
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. Limitação de Taxa
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
tool_call_history = defaultdict(list)
|
||||
|
||||
@before_tool_call
|
||||
def rate_limit_tools(context: ToolCallHookContext) -> bool | None:
|
||||
"""Limita taxa de chamadas de ferramenta."""
|
||||
tool_name = context.tool_name
|
||||
now = datetime.now()
|
||||
|
||||
# Limpar entradas antigas (mais antigas que 1 minuto)
|
||||
tool_call_history[tool_name] = [
|
||||
call_time for call_time in tool_call_history[tool_name]
|
||||
if now - call_time < timedelta(minutes=1)
|
||||
]
|
||||
|
||||
# Verificar limite de taxa (máximo 10 chamadas por minuto)
|
||||
if len(tool_call_history[tool_name]) >= 10:
|
||||
print(f"🚫 Limite de taxa excedido para {tool_name}")
|
||||
return False
|
||||
|
||||
# Registrar esta chamada
|
||||
tool_call_history[tool_name].append(now)
|
||||
return None
|
||||
```
|
||||
|
||||
### 7. Logging de Debug
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def debug_tool_call(context: ToolCallHookContext) -> None:
|
||||
"""Debug de chamada de ferramenta."""
|
||||
print(f"""
|
||||
🔍 Debug de Chamada de Ferramenta:
|
||||
- Ferramenta: {context.tool_name}
|
||||
- Agente: {context.agent.role if context.agent else 'Desconhecido'}
|
||||
- Tarefa: {context.task.description[:50] if context.task else 'Desconhecida'}...
|
||||
- Entrada: {context.tool_input}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def debug_tool_result(context: ToolCallHookContext) -> None:
|
||||
"""Debug de resultado de ferramenta."""
|
||||
if context.tool_result:
|
||||
result_preview = context.tool_result[:200]
|
||||
print(f"✅ Preview do Resultado: {result_preview}...")
|
||||
else:
|
||||
print("⚠️ Nenhum resultado retornado")
|
||||
return None
|
||||
```
|
||||
|
||||
## Gerenciamento de Hooks
|
||||
|
||||
### Desregistrando Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_tool_call_hook,
|
||||
unregister_after_tool_call_hook
|
||||
)
|
||||
|
||||
# Desregistrar hook específico
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_tool_call_hook(my_hook)
|
||||
# Mais tarde...
|
||||
success = unregister_before_tool_call_hook(my_hook)
|
||||
print(f"Desregistrado: {success}")
|
||||
```
|
||||
|
||||
### Limpando Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks,
|
||||
clear_all_tool_call_hooks
|
||||
)
|
||||
|
||||
# Limpar tipo específico de hook
|
||||
count = clear_before_tool_call_hooks()
|
||||
print(f"Limpou {count} hooks antes")
|
||||
|
||||
# Limpar todos os hooks de ferramenta
|
||||
before_count, after_count = clear_all_tool_call_hooks()
|
||||
print(f"Limpou {before_count} hooks antes e {after_count} hooks depois")
|
||||
```
|
||||
|
||||
## Padrões Avançados
|
||||
|
||||
### Execução Condicional de Hook
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def conditional_blocking(context: ToolCallHookContext) -> bool | None:
|
||||
"""Bloqueia apenas em condições específicas."""
|
||||
# Bloquear apenas para agentes específicos
|
||||
if context.agent and context.agent.role == "junior_agent":
|
||||
if context.tool_name in ['delete_file', 'send_email']:
|
||||
print(f"❌ Agentes júnior não podem usar {context.tool_name}")
|
||||
return False
|
||||
|
||||
# Bloquear apenas durante tarefas específicas
|
||||
if context.task and "sensível" in context.task.description.lower():
|
||||
if context.tool_name == 'web_search':
|
||||
print("❌ Busca na web bloqueada para tarefas sensíveis")
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Modificação de Entrada com Consciência de Contexto
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def enhance_tool_inputs(context: ToolCallHookContext) -> None:
|
||||
"""Adiciona contexto baseado no papel do agente."""
|
||||
# Adicionar contexto baseado no papel do agente
|
||||
if context.agent and context.agent.role == "researcher":
|
||||
if context.tool_name == 'web_search':
|
||||
# Adicionar restrições de domínio para pesquisadores
|
||||
context.tool_input['domains'] = ['edu', 'gov', 'org']
|
||||
|
||||
# Adicionar contexto baseado na tarefa
|
||||
if context.task and "urgente" in context.task.description.lower():
|
||||
if context.tool_name == 'send_email':
|
||||
context.tool_input['priority'] = 'high'
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
## Melhores Práticas
|
||||
|
||||
1. **Mantenha Hooks Focados**: Cada hook deve ter uma responsabilidade única
|
||||
2. **Evite Computação Pesada**: Hooks executam em cada chamada de ferramenta
|
||||
3. **Trate Erros Graciosamente**: Use try-except para prevenir falhas de hooks
|
||||
4. **Use Type Hints**: Aproveite `ToolCallHookContext` para melhor suporte IDE
|
||||
5. **Documente Condições de Bloqueio**: Deixe claro quando/por que ferramentas são bloqueadas
|
||||
6. **Teste Hooks Independentemente**: Teste unitário de hooks antes de usar em produção
|
||||
7. **Limpe Hooks em Testes**: Use `clear_all_tool_call_hooks()` entre execuções de teste
|
||||
8. **Modifique In-Place**: Sempre modifique `context.tool_input` in-place, nunca substitua
|
||||
9. **Registre Decisões Importantes**: Especialmente ao bloquear execução de ferramenta
|
||||
10. **Considere Performance**: Cache validações caras quando possível
|
||||
|
||||
## Tratamento de Erros
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safe_validation(context: ToolCallHookContext) -> bool | None:
|
||||
try:
|
||||
# Sua lógica de validação
|
||||
if not validate_input(context.tool_input):
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Erro no hook: {e}")
|
||||
# Decida: permitir ou bloquear em erro
|
||||
return None # Permitir execução apesar do erro
|
||||
```
|
||||
|
||||
## Segurança de Tipos
|
||||
|
||||
```python
|
||||
from crewai.hooks import ToolCallHookContext, BeforeToolCallHookType, AfterToolCallHookType
|
||||
|
||||
# Anotações de tipo explícitas
|
||||
def my_before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Registro type-safe
|
||||
register_before_tool_call_hook(my_before_hook)
|
||||
register_after_tool_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## Solução de Problemas
|
||||
|
||||
### Hook Não Está Executando
|
||||
- Verifique se hook está registrado antes da execução da crew
|
||||
- Verifique se hook anterior retornou `False` (bloqueia execução e hooks subsequentes)
|
||||
- Garanta que assinatura do hook corresponda ao tipo esperado
|
||||
|
||||
### Modificações de Entrada Não Funcionam
|
||||
- Use modificações in-place: `context.tool_input['key'] = value`
|
||||
- Não substitua o dict: `context.tool_input = {}`
|
||||
|
||||
### Modificações de Resultado Não Funcionam
|
||||
- Retorne a string modificada dos hooks posteriores
|
||||
- Retornar `None` mantém o resultado original
|
||||
- Garanta que a ferramenta realmente retornou um resultado
|
||||
|
||||
### Ferramenta Bloqueada Inesperadamente
|
||||
- Verifique todos os hooks antes por condições de bloqueio
|
||||
- Verifique ordem de execução do hook
|
||||
- Adicione logging de debug para identificar qual hook está bloqueando
|
||||
|
||||
## Conclusão
|
||||
|
||||
Os Hooks de Chamada de Ferramenta fornecem capacidades poderosas para controlar e monitorar execução de ferramentas no CrewAI. Use-os para implementar guardrails de segurança, gates de aprovação, validação de entrada, sanitização de resultado, logging e análise. Combinados com tratamento adequado de erros e segurança de tipos, os hooks permitem sistemas de agentes seguros e prontos para produção com observabilidade abrangente.
|
||||
|
||||
Reference in New Issue
Block a user