HooksConfig

Configure callbacks and middleware for agent lifecycle events

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

Diagram

Hook System

🤖 Agent

📍 on_step

🔧 on_tool_call

🔗 middleware

Quick Start

  1. 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)
    )
  2. 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

python
from praisonaiagents.config import HooksConfig

config = HooksConfig(
    # Step callback
    on_step=None,

    # Tool call callback
    on_tool_call=None,

    # Middleware list
    middleware=[]
)
ParameterTypeDefaultDescription
on_step`Callable \None`NoneCalled on each agent step
on_tool_call`Callable \None`NoneCalled on tool execution
middlewareList[Any][]Middleware chain

Common Patterns

Pattern 1: Logging All Events

python
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

python
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.


Related