Skip to main content
Attach callbacks to agent lifecycle events for monitoring, logging, and custom behavior.

Quick Start

1

Step Callback

Monitor each agent step:
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)
)
2

Tool Call Callback

Monitor tool executions:
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=[]
)
ParameterTypeDefaultDescription
on_stepCallable | NoneNoneCalled on each agent step
on_tool_callCallable | NoneNoneCalled on tool execution
middlewareList[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

Callbacks run synchronously. Keep them fast to avoid slowing down the agent.
Middleware is ideal for logging, metrics, authentication, etc.
Wrap callback logic in try/except to prevent callback errors from crashing the agent.