Agent lifecycle and where hooks fire

Understand the four phases of every agent turn

Every agent.start() call moves through four predictable phases: (1) load rules & build context, (2) call the LLM, (3) dispatch any requested tool calls, and (4) validate & return the final output.

Hooks let you plug Python code between these phases for auditing, metrics, redaction, or policy enforcement without cluttering your tool functions.

Example

from praisonai import Agent, HooksConfig

def lookup_price(sku: str) -> str:
    """Return SKU price."""
    return f'{sku}: $49'

trace = []
def on_tool(req):
    trace.append(f'TOOL -> {req.tool_name} args={req.arguments}')

agent = Agent(
    name='PricingBot',
    instructions='Always call lookup_price and reply in one sentence.',
    tools=[lookup_price],
    hooks=HooksConfig(on_tool_call=on_tool),
    output='silent',
)
print('Reply:', agent.start('What is the price for PRO-1?'))
print('Trace:', trace)

Try it Yourself

Example explained

  • req.tool_name / req.arguments — Inspects the exact tool name and structured dict arguments requested by the LLM.
  • trace.append(…) — Captures an ordered audit trail completely decoupled from business logic.

Why hooks beat putting logging inside every tool

If you have 15 tools (or external MCP tools you didn't write), adding print/logging inside each function is impossible to maintain. One HooksConfig covers every local and MCP tool uniformly.

Common pitfall: writing a 2-argument on_tool_call callback

HooksConfig(on_tool_call=fn) invokes fn(event) with ONE ToolRequest object — not (name, args). Always read event.tool_name and event.arguments from that single argument.

Reference: documentation