The agent loop — study guide
The concept's fragments, read in order.
From one tool call to an agent
A single tool call is one round trip: the model asks for a function by name, your program runs it, and the result goes back to the model as input. An agent is what you get when that round trip goes inside a loop. The program gives the model a goal. The model replies with either a tool request or a final answer. If it is a tool request, the program runs the tool, adds the request and its result to the conversation, and calls the model again. The loop continues until the model gives a final answer or one of the program's own stop conditions trips.
The usual short name for the cycle is plan, act, observe, repeat. The model plans the next step from everything it has seen so far, the program acts by running the tool, and the result is the observation the following step is planned from. No route is fixed in advance; each step is chosen from what the last one revealed, like finding your way through an unfamiliar town by asking for directions at each corner, choosing the next street from what you just learned rather than from a route planned in full before you set out.
Two parties share the work, and it pays to keep them straight. The model makes every decision about what to do next, but it never runs anything, and it has no way to make the loop last longer than the program allows: all it ever does is return text. The program runs the loop, executes every tool, keeps the conversation, and enforces the limits. The agent's usefulness comes from the model's side of that split. Every control you have over it lives on the program's side.
The parts of the loop
Every agent loop, however it is dressed up, has four parts. The goal is the task stated at the start, usually alongside instructions about which tools exist and how to use them. The state is what carries from one turn to the next: the transcript, a growing list of messages holding the goal, every tool request the model has made and every result that came back. The decision is what the model produces each turn, either a request to call a named tool with specific arguments or a final answer. The stop conditions are the rules that end the loop.
Trace one turn. The program sends the whole transcript to the model. Suppose the model replies with a request to call read_file with the argument notes.txt. The program runs that function and appends two messages to the transcript: the request and the result. It checks its limits, then sends the now longer transcript back to the model, which reads the result and decides again. A finished turn leaves the transcript one exchange longer, and nothing else changes from the model's point of view.
The exit is a decision that contains no tool request. When the model replies with a plain answer, the program takes that as done and returns it. That is the normal way out but not the only one: the program also checks its own limits on every pass around the loop, and any of them can end the run before the model chooses to.
The transcript is the only memory
A standard model call remembers nothing. Each request is answered from the text sent with it, so an agent that seems to remember its earlier steps is really being reminded of them: the program resends the transcript on every turn. That leaves the agent like a worker who remembers nothing between shifts and knows only what is written in the log handed over at the start of each one, a log that gets longer every shift: the transcript is its entire working memory. A fact that is in it can shape the next decision. A fact that is not in it does not exist as far as the model is concerned.
Resending everything has a cost that grows as the loop runs. Each turn appends the latest tool request and result, and the next request carries all of it again, so every request is longer than the one before. With illustrative numbers: if the first request is 1,000 tokens and each turn adds 1,000 more, request 10 carries 10,000 tokens, and the ten requests together send 1,000 x (1 + 2 + ... + 10) = 55,000 tokens. Twenty turns send 1,000 x (1 + 2 + ... + 20) = 210,000. Twice the turns, almost four times the total: the size of each request grows in a straight line, so the running total grows roughly with the square of the number of turns. How close to four depends on how large the first request is compared with what each turn adds. Putting a price on that is a separate question; the shape is the point here.
The other limit is size. A model takes its input through a context window, a fixed maximum amount of text per call, and a long enough run fills it. The full transcript then cannot be sent as it is. Either the request fails, or the program shrinks the history first: dropping the oldest turns, replacing them with a summary, or pruning old tool results. Each of those trades memory for room. A dropped turn is gone unless the program saved it somewhere the agent can look it up, and a summary keeps the outline but can lose exactly the constraint that mattered.
Knowing when to stop
An agent loop ends in one of two ways, and the program has to tell them apart. The first is the model's: it replies with a final answer instead of a tool request, which is its way of saying the goal is met. The second is the program's: a step limit, a budget or a deadline runs out, a tool fails in a way that retrying will not fix, or someone cancels the run.
The model's way out is the normal one, but it rests on the model's own judgment that the job is finished, and that judgment can be wrong in either direction. The agent can keep working long after the goal was met, or stop early and report success on a task that is only partly done. A final answer is a claim that the work is finished, not proof of it. Where the program can check the goal itself (a test that passes, a file that now exists, a value back in range), checking before accepting the answer turns the claim into a fact.
The program's way out needs an honest report. When a limit ends the run, the result should say so: which limit tripped, what was done, what partial results exist and what was left undone. A run that hits its step limit and hands back its last message as though it were the answer has turned a visible failure into a quiet wrong result. Reported plainly, the stop lets whoever started the run decide what comes next: retry with a narrower task, raise the limit on purpose, or give the problem to a person.
The program holds the leash
The loop is ordinary code that you write, so its controls are ordinary code too, and they sit where the model cannot reach them. An instruction telling the model to stop after ten steps is a request it may or may not follow. A counter in the loop that ends the run at ten is a fact. Engineering guidance for agents makes the same point: put several independent limits in the program instead of trusting the model to decide it has done enough, and never let the agent raise its own ceiling.
Four controls are the place to start. A step limit caps the number of turns. A budget caps the total tokens or spend across the run, because each turn resends a longer transcript, so a run with a modest step count can still send a large amount of input. Timeouts come in two sizes: one per tool call, so a hung tool cannot stall the loop, and a wall-clock deadline for the whole run. And checkpoints pause the loop for a person. Before a consequential tool call runs (deleting data, sending a message, changing something people depend on), the program saves the run, shows a person the exact tool and arguments, and waits.
A checkpoint approves one specific call, not a general direction. If the person approves, the program executes that call, as shown or as the person edited it; if they refuse, the program skips it and hands the refusal back to the model as the result, and the model chooses again. Because the run was saved, the wait can last minutes or a day without starting over. What makes it a real control is that the program has no other route to that tool: a call that needs approval cannot be executed any other way.
Loops that never finish
The first way an agent loop goes wrong is that it does not end. Nothing obliges the model to reach a final answer. Each turn it produces the most plausible next step given the transcript, and one more tool call can always look plausible. Without a limit in the program, a run like that continues until something outside it gives way.
One shape this takes is repetition. The agent calls the same tool with the same arguments, gets the same result, and calls it again. Or it retries a failing call indefinitely, or swings between two actions that undo each other: edit the file, revert the file, edit it again. Inside the transcript each step can look like a reasonable response to the last, which is why the model cannot be relied on to notice. From outside, in the program, the pattern is plain to see.
So detect it in code. Record a fingerprint for each action, the tool name plus its arguments in a normalized form, alongside the result. The same fingerprint coming back with the same result, a recurring sequence like A, B, A, B, or a run of steps in which nothing about the task has changed are all signs of a loop. A repeat is not automatically a fault, since a retry with new information is legitimate, so the response is usually to interrupt rather than crash: tell the model the call was already made and what it returned, ask for a materially different approach, or stop with a clear stop reason and hand the run to a person. The step limit stays underneath it all, the backstop for whatever the detector misses.
Losing the goal
The second failure is quieter. The goal is stated once, near the top of the transcript, and every turn piles more tool output after it. Over a long run the agent can slide from the task it was given to a nearby one that the recent material makes more tempting. Each step looks reasonable while the run as a whole heads somewhere else. One 2025 study, which gave agents a goal and then pressured them toward a competing one, found every model it tested drifted to some degree, often gradually, and sometimes by simply failing to take a step the goal required. How much varied widely by model and setup.
In everyday work the same slide can look like fixing an error the agent happened across instead of the one it was asked about, polishing a side detail, or treating one subtask as the whole job and declaring it done. That study does not pin drift on transcript length alone: what fills the transcript matters as well as how much of it there is. That rules out a single fix, but a few habits help. The program can restate the goal at intervals, and make sure that trimming an overlong history never removes it. It can keep a short, explicit description of what done means and check the final answer against that rather than against the agent's own say-so. And on a long task it can check intermediate results along the way, so a run that has wandered is caught a few steps in rather than at the end.
One early mistake, carried forward
The third failure comes from the loop's best feature. Each step is planned from the results of the steps before it, so the agent builds on its own work, mistakes included. A wrong result early on (a misread file, a search that found the wrong record, a wrong guess about which part is broken) becomes a premise. Every later step can be perfectly sensible given that premise and still lead somewhere wrong, like one wrong turn early on a long drive: every turn after it is a sensible one from where you now are, and each takes you farther from where you meant to go.
A simple model shows why length matters. Assume each step is right with the same probability p, independently of every other step, and that the task needs every step right. Then the chance that all n steps are right is p multiplied by itself n times. At p = 0.99, ten steps all go right with probability 0.99^10, about 90.4 percent, and twenty with 0.99^20, about 81.8 percent. At p = 0.95 the same lengths give 0.95^10, about 59.9 percent, and 0.95^20, about 35.8 percent. A step that is right 19 times in 20 sounds dependable; a chain of twenty of them is more likely than not to contain a mistake.
Those assumptions are the simplification. Real steps do not share one fixed success rate, and they are not independent: an early mistake can make later steps more likely to go wrong, while a step that notices something is off and corrects it can undo the damage, which the simple model has no room for. It also counts every slip as fatal, when some are harmless. So the arithmetic illustrates a trend rather than forecasting any real agent. Measurement points the same way: one 2026 preprint that tracked success against the number of steps an agent took found it falling as tasks got longer, though how fast it falls depends on the agent and the task. The practical lesson survives the simplification: check intermediate results wherever a check is cheap, so a mistake is caught one step after it happens instead of twenty.
Where you will meet the loop
The loop looks the same wherever software keeps acting on what it just observed. An agent pipeline working through a queue of tasks runs it once per task. An assistant helping you operate your own running app runs it while it gathers context for an alert or drafts a fix for review. A robot that senses where it is, decides, and moves has a loop of the same shape, with sensors and motors where the tools would be. The details differ. The parts (goal, state, decision, stop) are the same, and so are the ways it goes wrong.
What makes any of them safe to leave running is the program around the loop, not the model inside it. A step limit and a budget mean a confused run ends instead of running on. A timeout means one hung tool does not hang everything. A repetition check catches the loop that is going nowhere, a checkable definition of done catches the answer that only claims success, and a checkpoint keeps a person in front of anything that is hard to undo.
Each of those is a few lines of ordinary code. Write them before the first unattended run, not after the first bad one.