Skip to main content

Loop Hooks

Loop hooks provide 5 intercept points inside the LLM tool-calling loop, enabling per-roundtrip control over messages, tool execution, and cost management.

Hook Interface

interface LoopHooks {
  beforeLLMCall?: (messages: ChatMessage[], roundtrip: number) => Promise<ChatMessage[] | void>;
  afterLLMCall?: (response: { finishReason: string; usage: TokenUsage }, roundtrip: number) => Promise<void>;
  beforeToolExec?: (toolName: string, args: unknown) => Promise<{ skip?: boolean; result?: string } | void>;
  afterToolExec?: (toolName: string, result: string) => Promise<string | void>;
  onRoundtripComplete?: (roundtrip: number, tokensSoFar: TokenUsage) => Promise<{ stop?: boolean } | void>;
}

Usage

import { Agent, openai } from "@radaros/core";

const agent = new Agent({
  name: "monitored-agent",
  model: openai("gpt-4o"),
  loopHooks: {
    beforeLLMCall: async (messages, roundtrip) => {
      console.log(`Roundtrip ${roundtrip}: ${messages.length} messages`);
    },
    afterToolExec: async (toolName, result) => {
      console.log(`Tool ${toolName} returned ${result.length} chars`);
    },
    onRoundtripComplete: async (roundtrip, tokens) => {
      if (tokens.totalTokens > 50000) {
        return { stop: true }; // graceful early exit
      }
    },
  },
});

Hook Points

HookWhenCan Modify
beforeLLMCallBefore each LLM API callReturn new messages array
afterLLMCallAfter LLM responseRead-only
beforeToolExecBefore each tool executionSkip tool, provide mock result
afterToolExecAfter each tool executionTransform the result string
onRoundtripCompleteAfter all tools in a roundtripStop the loop early
These hooks are the foundation for context compaction, cost auto-stop, PII scrubbing, and checkpointing.