AgentForge

Hooks

React to agent lifecycle events with hooks — onStart, onStep, onToolCall, onError, and more.

AgentHooks

Hooks are callbacks that fire at specific points in the agent lifecycle:

interface AgentHooks {
  onStart?: (runId: string, task: string) => void | Promise<void>;
  onStep?: (step: StepRecord) => void | Promise<void>;
  onToolCall?: (toolName: string, input: unknown) => void | Promise<void>;
  onError?: (error: Error, source: ErrorSource) => void | Promise<void>;
  onApprovalRequired?: (approval: PendingApproval) => void | Promise<void>;
  onComplete?: (result: RunResult) => void | Promise<void>;
}

Usage

const agent = defineAgent({
  name: 'monitored-agent',
  description: 'Agent with hooks',
  tools: [myTool],
  llm,
  systemPrompt: '...',
  hooks: {
    onStart: (runId, task) => {
      console.log(`Starting run ${runId}: ${task}`);
    },
    onStep: (step) => {
      console.log(`Step ${step.index}: ${step.type} (${step.duration}ms)`);
    },
    onToolCall: (toolName, input) => {
      console.log(`Tool call: ${toolName}`, input);
    },
    onError: (error, source) => {
      console.error(`${source} error:`, error.message);
    },
    onComplete: (result) => {
      console.log(`Completed: ${result.status}`);
    },
  },
});
agent = define_agent(
    name="monitored-agent",
    description="Agent with hooks",
    tools=[my_tool],
    llm=llm,
    system_prompt="...",
    hooks={
        "on_start": lambda run_id, task: print(f"Starting {run_id}: {task}"),
        "on_step": lambda step: print(f"Step {step.index}: {step.type}"),
        "on_tool_call": lambda name, input: print(f"Tool: {name}", input),
        "on_error": lambda err, source: print(f"{source} error: {err}"),
        "on_complete": lambda result: print(f"Done: {result.status}"),
    },
)

Hook Lifecycle

onStart → [onStep → (onToolCall)* ]* → onComplete
                                    ↘ onError
  1. onStart — fires once when run() or stream() is called
  2. onStep — fires after each step completes (LLM response or tool execution)
  3. onToolCall — fires before each tool execution
  4. onError — fires when any error occurs (tool, LLM, or framework)
  5. onApprovalRequired — fires when the autonomy policy requires human approval
  6. onComplete — fires once when the run finishes (regardless of status)

Async Hooks

Hooks can be async — AgentForge awaits them before continuing:

hooks: {
  onToolCall: async (toolName, input) => {
    await logToDatabase({ toolName, input, timestamp: Date.now() });
  },
},

Next Steps