AG2B

The Loop

The loop is the core of AG2B's runtime — the cycle that turns a single LLM call into an agent.

Before the loop

  1. Fire onChatStart. Carries the user message and abort signal.
  2. Commit the user message to history. Fires onMessage.

One iteration explained

A pass through the loop runs in four phases.

Request

  1. Build the request — history snapshot, enabled tools, scope contexts, base system prompt.
  2. Fire preRequest. Hooks can modify the request or short-circuit with a synthetic response.
  3. Call the provider. Skipped if preRequest supplied a response.

Response

  1. Fire onResponse. Hooks can replace the response before the agent uses it.
  2. Commit the assistant message to history. Fires onMessage.

Tool handling

  1. No tool calls? The loop ends — fire onChatDone and return the response.
  2. Tool calls? Run sequentially. For each:
    • Fire preToolCall. Hooks can modify args or short-circuit with a result/error.
    • Execute the handler. Throws in handlers don't terminate the chat — they become tool messages the LLM sees on the next turn.
    • Fire onToolCallResult on success, onToolCallError on failure.
    • Commit the tool message. Fires onMessage.

Continue or stop

  1. Increment the iteration counter and start the next pass — unless the counter hits maxIterations, in which case the loop throws Ag2bMaxIterationsError.

Stop Conditions

A chat ends in one of five ways. The terminal hook depends on what stopped it:

TriggerHook
LLM returns a turn without tool callsonChatDone
AbortSignal aborts the runonChatAbort
Counter reaches maxIterationsonChatError
Provider throws (HTTP, malformed payload, network)onChatError
Any non-terminal hook throwsonChatError

On this page