Skip to main content
This page is about the core model/tool loop used by generate_text() and stream_text(). It is not about the Agent class. For persistent stateful agents, read Stateful Agents.

What Is A Tool Loop?

When you pass tools to a model call, the model can ask to call a tool. ai-query executes the tool, sends the result back to the model, and continues until the model produces a final answer or a stop condition fires. The loop is:
  1. send messages and tool definitions to the model
  2. receive text and/or tool calls
  3. execute requested tools
  4. append tool results
  5. call the model again
  6. stop when there are no tool calls or a stop condition is met

Minimal Example

Stop Conditions

Stop conditions prevent runaway loops.

Stop after N steps

Stop when a tool is called

Combine conditions

The loop stops when any condition returns True.

Step Results

The result contains every step.
Use step history for debugging, logs, tests, and observability.

Step Callbacks

Callbacks let you observe or steer the loop at step boundaries.

Observe start

Observe finish

Inject at a boundary

This is a low-level primitive. If you are building an interactive runtime, prefer Live Turns.

Streaming Tool Loops

Tool loops work with streaming too.

When To Use This Layer

Use core tool loops when:
  • you do not need persistent agent state
  • you are writing a script or background job
  • you want direct control over callbacks and stop conditions
  • you are building a custom abstraction above core generation
Use Agent instead when:
  • you need message history
  • you need durable state
  • you need server routes
  • you need live turn events or steering