Kolkata ·  
AI engineering
agents
deep · 6 min

Agent loop

A model calls tools in a loop, choosing its own next step, until it decides it's done.

updated 29 Sept 2026

Let's give a coding agent one line: "Fix the failing tests in auth.ts". Then let's watch what actually goes back and forth.

First the model asks to run npm test. Our code runs it and sends back the output: three failures. Next it asks to read auth.ts and auth.test.ts. We send both files. Then it asks to edit auth.ts and run the tests again. All three pass. Finally it replies with plain text and no tool request: "Fixed the auth bug, all three tests pass now."

That's the whole agent. Each of those exchanges is a tool call round trip: the model asks for a function, our code runs it, the result goes back. An agent just keeps doing that round trip until the model stops asking. Each round trip is called a turn, so this run took four turns: three with tool calls and a last one with only text.

Notice what nobody wrote down. There's no script saying "run the tests, then read the files, then edit". The model picked each step after seeing the result of the one before. If the first test run had shown a missing package instead, it would have gone somewhere else.

It's a while loop

Take away any framework and here's what's left:

messages = [system_prompt, user_task]
while True:
    response = model(messages, tools)
    messages.append(response)
    if not response.tool_calls:
        break                      # the model says it's done
    for call in response.tool_calls:
        result = run_tool(call)    # our code, our permissions
        messages.append(result)

Anthropic's and OpenAI's agent SDKs both run this shape. OpenAI's adds one more way out: the model can call a special "final output" tool that hands back a structured answer. Frameworks wrap limits, hooks and logging around it, but the core is a few lines. That's why a common piece of advice is to write it yourself against the API once. Frameworks tend to hide the actual prompts and responses, and those are what you need to see when a run goes wrong.

Who picks the next step?

This is the line between an agent and an LLM workflow. In a workflow our code fixes the path: classify, then draft, then check. The model fills in each step but never chooses what comes next. In the loop, the model chooses which tool and when. Our code only decides whether it's allowed to keep going.

Why give that up? Because some problems don't have a path you can write down ahead of time. Debugging is the usual example. You don't know whether the fix is one edit or ten until you look. That's where the loop earns its cost, and it's also why you shouldn't reach for it when a fixed path would do (more on that in when not to use agents).

So what keeps a model that picks its own steps from wandering off? The tool results. The test output is what the code really does, not what the model guessed it does. Every turn, the model checks its progress against something real. That idea is older than native tool calling. The ReAct prompting pattern from 2022 had the model write a thought, take an action, read what came back, and repeat. Models now do the same thing through tool calls instead of parsed text.

There's a one-line definition that a lot of people have settled on: an LLM agent runs tools in a loop to achieve a goal. Tools, because it acts on something outside itself. A loop, because results feed back in. A goal, because at some point it stops.

The pile that grows every turn

Here's the part people miss at first. The context doesn't reset between turns. The system prompt, the tool definitions, every message, every tool call and every result stay in and get sent again. When the auth.ts run reaches its third turn, the model is reading the first test output and both full files all over again.

That pile is two things at once.

It's the agent's short-term memory. The model knows what it already tried because the earlier turns are sitting right there. For a lot of tasks that's all the memory it needs.

It's also the bill. Every turn pays for the whole history again as input. A big file read early on gets paid for on every turn after it. The parts that never change, like the system prompt and tool definitions, can be reused through prompt caching, which helps. And when the pile gets close to the window's limit, the Claude Agent SDK summarizes older turns to make room. That's compaction, and it has a catch: an instruction you gave only in the first message can get summarized away. Rules that must hold for the whole run should live somewhere that's sent every turn, like the system prompt or a project file the SDK loads back in.

Who decides it's done?

The model does. The loop ends when it answers without a tool call. Should that be the only way out? Probably not. If you give it something open like "improve this codebase", it can keep going a long time.

So real systems add their own exits. In the Claude Agent SDK, max_turns caps the number of tool-use turns and max_budget_usd stops the run once spend hits a cap. Both default to no limit, and the docs call a budget a good default for production. The budget also counts any sub-agents the run starts. OpenAI's guide lists much the same set of exits: a final output, a reply with no tool call, an error, or a maximum number of turns.

When a limit trips, the result says so (error_max_turns, error_max_budget_usd) instead of looking like a success. That matters. Your code needs to tell "finished" apart from "gave up", and they look alike if you only read the last message.

You can also stop it from the inside. A hook that runs before each tool call can look at the arguments and block the call. The model gets a rejection back as the tool result and usually tries a different approach or says it couldn't continue. That's the spot to ask a person first on risky actions (human in the loop) and to keep actions inside a sandbox. Doing it in a hook beats writing "please don't delete anything" in the prompt, because the hook runs in our code and the model can't talk its way past it.

How it goes wrong

Each step builds on the last one, so mistakes stack up. Misread one tool result and the next action is wrong, which produces another confusing result, and so on. That's why Anthropic's advice is to test agents in sandboxed environments with guardrails before trusting them.

There's a failure that only loops have, too. The model repeats its last thought and action and can't get out. ReAct ran into this back in 2022. A turn limit is the blunt fix.

And the loop hands the model every tool you gave it, on every turn. Hand it more than the task needs and you've widened what can go wrong, which has its own name: excessive agency.

If one loop's pile gets too big for its context, one way out is to let it start a fresh loop for a subtask and take back only the answer. A sub-agent begins with an empty conversation and returns just its final reply as a tool result. That's where multi-agent systems begin.

Back to auth.ts for a second, because there's one thing about that run that's easy to miss. We trusted the model's "done" because the tests passed, and the tests are an outside check. Most tasks don't come with one. For those, you have to build the check yourself, which is what agent evals are for.

Further reading