HooksConfig
Configure callbacks and middleware for agent lifecycle events
Attach callbacks to agent lifecycle events for monitoring, logging, and custom behavior.
Quick Start
- Step Callback
Monitor each agent step:
python from praisonaiagents import Agent from praisonaiagents.config import HooksConfig def on_step(step_info): print(f"Step: {step_info}") agent = Agent( name="Hooked Agent", instructions="Agent with callbacks", hooks=HooksConfig(on_step=on_step) ) - Tool Call Callback
Monitor tool executions:
python from praisonaiagents import Agent from praisonaiagents.config import HooksConfig def on_tool_call(tool_name, args, result): print(f"Tool: {tool_name}, Args: {args}") agent = Agent( name="Hooked Agent", instructions="Agent with tool monitoring", hooks=HooksConfig(on_tool_call=on_tool_call) )
Configuration Options
from praisonaiagents.config import HooksConfig
config = HooksConfig(
# Step callback
on_step=None,
# Tool call callback
on_tool_call=None,
# Middleware list
middleware=[]
)| Parameter | Type | Default | Description | |
|---|---|---|---|---|
on_step | `Callable \ | None` | None | Called on each agent step |
on_tool_call | `Callable \ | None` | None | Called on tool execution |
middleware | List[Any] | [] | Middleware chain |
Common Patterns
Pattern 1: Logging All Events
from praisonaiagents import Agent
from praisonaiagents.config import HooksConfig
import logging
logger = logging.getLogger(__name__)
def log_step(step_info):
logger.info(f"Step: {step_info}")
def log_tool(tool_name, args, result):
logger.info(f"Tool: {tool_name}")
agent = Agent(
name="Logged Agent",
instructions="Full logging",
hooks=HooksConfig(
on_step=log_step,
on_tool_call=log_tool
)
)Pattern 2: Custom Middleware
from praisonaiagents import Agent
from praisonaiagents.config import HooksConfig
class TimingMiddleware:
def __call__(self, next_handler):
import time
def handler(request):
start = time.time()
result = next_handler(request)
print(f"Duration: {time.time() - start:.2f}s")
return result
return handler
agent = Agent(
name="Timed Agent",
instructions="Track timing",
hooks=HooksConfig(
middleware=[TimingMiddleware()]
)
)Best Practices
Keep Callbacks Lightweight
Callbacks run synchronously. Keep them fast to avoid slowing down the agent.
Use Middleware for Cross-Cutting Concerns
Middleware is ideal for logging, metrics, authentication, etc.
Handle Errors in Callbacks
Wrap callback logic in try/except to prevent callback errors from crashing the agent.