The Agent Loop

How the loop around a model works: calling the model, running the tools it requests, handling errors, and deciding when to stop.

13 minLesson 3 of 6
On this page
  1. How the loop works
  2. A worked run
  3. The loop in code
  4. Handling tool errors
  5. Several tool calls in one reply and truncated replies
  6. When the loop stops
  7. What long runs cost
  8. Pitfalls in the loop code
  9. What this changes in practice
  10. What to practise next

The agent loop is the code that turns a language model into an agent. It sends the conversation to the model, runs any tool the model asks for, adds the result to the conversation, and repeats until the model gives a final answer. Almost every agent, from a small script to a large framework, is built around this loop, so how it handles errors and when it stops determine whether the agent is reliable.

The model only produces text. It cannot run a tool, retry after a failure or stop itself, so all of that is done by ordinary code. If that code lets one tool exception escape, the run crashes. If it has no limit on the number of passes, a confused model can keep calling tools for as long as you let it.

How the loop works

What Is an Agent showed the loop as pseudocode. Each pass through the loop has four parts:

  1. The loop sends the whole history to the model and gets one reply.
  2. If the reply is a final answer, the loop returns it and stops.
  3. Otherwise the reply is a tool request, and the loop runs that tool. If the tool fails, the loop turns the failure into an error message instead of crashing.
  4. The loop adds the model's reply and the tool result to the history, so the next call can see both.

The loop also has a maximum number of passes. The model decides what to do next, but the code decides whether the model is allowed to keep going.

A worked run

In this run the user asks which of two warehouses has more blue mugs. The north warehouse has 140 and the south warehouse has 95. The model's replies are scripted so that you can follow what the code does with each one, including a first tool call that fails.

A run in which the tool call fails onceUse the arrows or ← → keys
history = [goal]for step in 1..maxSteps:  reply = model(history)  history += reply  if reply is an answer: return it  try: result = run the tool  except: result = the error message  history += resultreturn "stopped: step limit"
  1. history
    #entry
    1user: Which warehouse has more blue mugs?
    step
    0
    maxSteps
    10
    entries
    1

    1The history starts with only the user's question.

  2. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    step
    1
    maxSteps
    10
    entries
    2

    2On the first pass the model asks for stockLevel with the argument "North", written with a capital N. The reply is not an answer, so the loop runs the tool.

  3. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    3error: Unknown warehouse "North". Use "north" or "south".
    step
    1
    maxSteps
    10
    entries
    3

    3The tool throws an error because it only knows the lowercase name "north". The loop catches the error and records its message in the history. Without the try block, the whole run would crash here.

  4. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    3error: Unknown warehouse "North". Use "north" or "south".
    4model: stockLevel("north")
    step
    2
    maxSteps
    10
    entries
    4

    4On the second pass the model reads the error message in the history and corrects its own input.

  5. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    3error: Unknown warehouse "North". Use "north" or "south".
    4model: stockLevel("north")
    5result: north, 140
    step
    2
    maxSteps
    10
    entries
    5

    5The corrected call succeeds, and the result says the north warehouse has 140 blue mugs.

  6. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    3error: Unknown warehouse "North". Use "north" or "south".
    4model: stockLevel("north")
    5result: north, 140
    6model: stockLevel("south")
    7result: south, 95
    step
    3
    maxSteps
    10
    entries
    7

    6On the third pass the model asks for the south warehouse, the loop runs the tool, and the result of 95 mugs is recorded.

  7. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    3error: Unknown warehouse "North". Use "north" or "south".
    4model: stockLevel("north")
    5result: north, 140
    6model: stockLevel("south")
    7result: south, 95
    8model: North has more blue mugs: 140 against 95.
    step
    4
    maxSteps
    10
    entries
    8
    stopped
    answered

    7On the fourth pass the history contains both numbers, so the model writes its answer. Line 5 returns it together with the reason the loop stopped.

  8. history
    #entry
    1user: Which warehouse has more blue mugs?
    2model: stockLevel("North")
    3error: Unknown warehouse "North". Use "north" or "south".
    4model: stockLevel("north")
    5result: north, 140
    6model: stockLevel("south")
    7result: south, 95
    8model: North has more blue mugs: 140 against 95.
    model calls
    4
    tool runs
    3
    errors
    1

    8The run used 4 model calls and 3 tool runs, and it recovered from 1 error. With maxSteps set to 2, it would have ended after the second pass with the stop reason "step limit" and no answer.

1 / 8

The loop in code

In this code, model is any function that takes the history and returns either { type: "answer", text } or { type: "tool", tool, input }. In a real application it would wrap a call to a model API, and here it is a stand-in so the code can run on its own.

function runAgent(model, tools, goal, maxSteps = 10) {
  const history = [{ role: "user", text: goal }];
  for (let step = 1; step <= maxSteps; step++) {
    const reply = model(history);
    history.push(reply);
    if (reply.type === "answer") {
      return { answer: reply.text, steps: step, stopped: "answered" };
    }
    let result;
    try {
      const tool = tools[reply.tool];
      if (!tool) throw new Error(`No tool named ${reply.tool}`);
      result = tool(reply.input);
    } catch (err) {
      result = { error: err.message }; // the model reads errors too
    }
    history.push({ role: "tool", result });
  }
  return { answer: null, steps: maxSteps, stopped: "step limit" };
}
def run_agent(model, tools, goal, max_steps=10):
    history = [{"role": "user", "text": goal}]
    for step in range(1, max_steps + 1):
        reply = model(history)
        history.append(reply)
        if reply["type"] == "answer":
            return {"answer": reply["text"], "steps": step, "stopped": "answered"}
        try:
            tool = tools.get(reply["tool"])
            if tool is None:
                raise ValueError(f"No tool named {reply['tool']}")
            result = tool(**reply["input"])
        except Exception as err:
            result = {"error": str(err)}  # the model reads errors too
        history.append({"role": "tool", "result": result})
    return {"answer": None, "steps": max_steps, "stopped": "step limit"}

The second listing runs the example from the tracer, using a fake tool and a scripted model that returns one reply per pass.

Running it
const stock = { north: 140, south: 95 };
const tools = {
  stockLevel: ({ warehouse }) => {
    if (!(warehouse in stock)) {
      throw new Error(`Unknown warehouse "${warehouse}". Use "north" or "south".`);
    }
    return { warehouse, blueMugs: stock[warehouse] };
  },
};
const script = [
  { type: "tool", tool: "stockLevel", input: { warehouse: "North" } },
  { type: "tool", tool: "stockLevel", input: { warehouse: "north" } },
  { type: "tool", tool: "stockLevel", input: { warehouse: "south" } },
  { type: "answer", text: "North has more blue mugs: 140 against 95." },
];
const fakeModel = (history) => script[(history.length - 1) / 2];
 
console.log(runAgent(fakeModel, tools, "Which warehouse has more blue mugs?"));
// { answer: 'North has more blue mugs: 140 against 95.', steps: 4, stopped: 'answered' }
console.log(runAgent(fakeModel, tools, "Which warehouse has more blue mugs?", 2));
// { answer: null, steps: 2, stopped: 'step limit' }
stock = {"north": 140, "south": 95}
 
def stock_level(warehouse):
    if warehouse not in stock:
        raise ValueError(f'Unknown warehouse "{warehouse}". Use "north" or "south".')
    return {"warehouse": warehouse, "blue_mugs": stock[warehouse]}
 
tools = {"stock_level": stock_level}
script = [
    {"type": "tool", "tool": "stock_level", "input": {"warehouse": "North"}},
    {"type": "tool", "tool": "stock_level", "input": {"warehouse": "north"}},
    {"type": "tool", "tool": "stock_level", "input": {"warehouse": "south"}},
    {"type": "answer", "text": "North has more blue mugs: 140 against 95."},
]
fake_model = lambda history: script[(len(history) - 1) // 2]
 
print(run_agent(fake_model, tools, "Which warehouse has more blue mugs?"))
# {'answer': 'North has more blue mugs: 140 against 95.', 'steps': 4, 'stopped': 'answered'}
print(run_agent(fake_model, tools, "Which warehouse has more blue mugs?", max_steps=2))
# {'answer': None, 'steps': 2, 'stopped': 'step limit'}

With a real model and real tools, the loop itself stays the same. Frameworks add streaming, logging and several tool calls in one reply, but the core is still this loop.

Handling tool errors

A tool can fail in three ways. The model can name a tool that does not exist, it can pass arguments the tool rejects, or the tool can fail for its own reasons, such as a network timeout. The loop in the previous section handles all three the same way: it catches the exception and records the message as the tool result.

The alternative is to let the exception end the run. That is correct for a bug in your own code, but it is the wrong response to a bad argument, because the model can usually fix that itself once it sees the error. The error message needs to say what was wrong and what is allowed, as in Unknown warehouse "North". Use "north" or "south". A message like Error 500 gives the model nothing to correct.

Retrying is a separate decision. Retrying a read is harmless, but retrying a tool that sends an email or charges a card can do the action twice. For tools with side effects, return the error to the model and let it decide, or have the tool refuse a second identical request.

Several tool calls in one reply and truncated replies

Real model APIs return a reply as structured data, not as text the loop has to parse, and one reply can contain several tool requests at once. Each request carries an identifier, and the result you send back must carry the same identifier, so the model knows which result answers which request. If the requests are independent reads, the loop can run them at the same time and append all the results before the next call. If one of them changes data that another reads, run them in order.

A reply can also be cut off because it reached the output limit. A cut-off reply may contain half of a tool request, and running half a request is worse than running none. Check the reason the API gave for ending the reply. If it ended because of the limit, do not run anything from it. Either ask the model to continue or count it as a failed pass.

When the loop stops

The stop you want is the model's final answer. The loop needs other conditions as well, and it should return which one fired, so the caller can tell a finished run from a cut-off one.

Step limit

The step limit is the simplest guard and should always be there. Choose it from real runs: if a task normally takes about 5 passes, a limit of 15 leaves room for retries without allowing endless wandering. When the limit fires, the history often ends in the middle of a plan, so the loop should report that the agent did not finish, not present the last message as an answer.

Budget and time limits

A step limit does not bound cost, because one pass with a large tool result costs far more than a pass with a small one. Track the total tokens used or the elapsed time as well, and stop when either passes a limit you set.

Repeat detection

If the model sends the same tool request with the same input again, it is probably stuck. Keep a set of the requests made so far. When one repeats, either stop the run or add a note to the history such as "You already tried this call. Try something different, or answer with what you have." The note is usually the better choice the first time, since the model often does change its approach.

Cancellation by a person

A long run should check a cancel flag on every pass, so that a user can stop it. Check the flag between passes and never in the middle of a tool call, because stopping halfway through a tool that writes data can leave that data inconsistent.

What long runs cost

The number of model calls grows in proportion to the number of passes. The amount of text the model reads grows faster, because every call re-reads the entire history so far. If each pass adds about the same amount of text, call 20 reads about twenty times as much as call 1, and the total read over the run grows with the square of the number of passes.

ApproachTimeSpaceWhy
Model callsO(n)One call per pass.
Tokens read in totalO(n²)O(n)Call i re-reads about i passes of history. The history itself grows linearly.

This is why short tool results matter in long runs. Systems reduce the cost by caching the unchanged start of the history, or by summarizing old passes, although a summary can drop a detail that turns out to be needed later. Long histories also lower answer quality, which Context Rot covers.

Pitfalls in the loop code

What this changes in practice

When you build or choose an agent framework, check four things. It should have a step limit and a budget limit. It should return tool errors to the model with a useful message. It should report the stop reason to your code. And it should handle tools with side effects, such as sending messages or changing records, differently from read-only tools, for example by asking a person to approve each call.

When an agent misbehaves, read the history from the top before changing the prompt. Most failures show up there as a repeated call, an unhelpful error message that the model could not act on, or a tool result so large that it pushed earlier information out of focus.

Try it: Find the bugs in this loop

This loop works in a demo and fails in production. Find at least three problems and say how to fix each one.

Show a sample answer
  1. There is no step limit. while True runs until the model answers, which may never happen. Loop up to max_steps times and return a "step limit" stop reason when the loop runs out.
  2. Tool failures crash the run. An exception inside the tool, or a misspelled tool name that raises a KeyError on tools[...], ends the program. Catch the error and put its message into the history.
  3. The model's request is never recorded. The model sees results for requests it cannot see itself making. Append the reply first and then the result.
  4. The caller cannot tell how the run ended. Return the stop reason together with the answer.

None of these problems shows up on a successful demo run, which is why they reach production.

Quick check

A tool throws an exception inside the loop because the model passed a badly formatted argument. What should the loop do?

Each pass adds about the same amount of text to the history. How does the total text the model reads grow with the number of passes n?

Why should the loop return the reason it stopped?

What to practise next

Copy the loop, script a model that repeats the same request, and add the repeat check. Then continue with Planning and Multi-Agent Systems, which covers tasks too big for a single loop to hold in its history.