/ examples / hooks / simple_hooks.py
simple_hooks.py
 1  #!/usr/bin/env python3
 2  """
 3  Simple Hooks Example for PraisonAI Agents.
 4  
 5  This example shows the SIMPLEST way to use hooks with the add_hook API.
 6  Just a few lines of code to intercept tool calls!
 7  
 8  No need to import HookResult - just return None/True to allow, 
 9  False to deny, or a string to deny with a reason.
10  
11  Usage:
12      python simple_hooks.py
13  """
14  
15  from praisonaiagents.hooks import add_hook, has_hook
16  
17  
18  # =============================================================================
19  # Register hooks with simple string event names
20  # =============================================================================
21  
22  @add_hook('before_tool')
23  def log_tools(event_data):
24      """Log every tool call. Return nothing (None) to allow."""
25      print(f"šŸ”§ Tool: {event_data.tool_name}")
26      # No return needed - defaults to allow
27  
28  
29  @add_hook('before_tool')
30  def block_dangerous(event_data):
31      """Block delete operations. Return False or string to deny."""
32      if 'delete' in event_data.tool_name.lower():
33          print(f"🚫 Blocked: {event_data.tool_name}")
34          return "Delete operations are not allowed"  # String = deny with reason
35      # No return = allow
36  
37  
38  @add_hook('after_tool')
39  def log_completion(event_data):
40      """Log tool completion."""
41      print(f"āœ… Done: {event_data.tool_name} ({event_data.execution_time_ms:.0f}ms)")
42  
43  
44  # =============================================================================
45  # Test the hooks
46  # =============================================================================
47  
48  if __name__ == "__main__":
49      print("=" * 50)
50      print("Simple Hooks Example")
51      print("=" * 50)
52      
53      # Check hooks are registered
54      print(f"\nHooks registered for 'before_tool': {has_hook('before_tool')}")
55      print(f"Hooks registered for 'after_tool': {has_hook('after_tool')}")
56      
57      # You can now create an Agent and the hooks will be applied
58      print("\nšŸ’” Hooks are now globally registered!")
59      print("   Any Agent will automatically use these hooks.")
60      print("\n   Example:")
61      print("   from praisonaiagents import Agent")
62      print("   agent = Agent(instructions='You are helpful')")
63      print("   agent.start('Help me with files')")
64      print("\nšŸ“ Hook returns:")
65      print("   - None or True  → Allow the operation")
66      print("   - False         → Deny the operation")
67      print("   - 'reason'      → Deny with a custom message")