What Is an Agent Loop in AI? Explained in Code
An agent loop is the cycle of think, act, observe that turns a language model into an agent. See it in 25 lines of code, with its stop rules and costs.
An agent loop is the repeating cycle that turns a language model into an agent. The model decides what to do next, a tool carries it out, the result goes back to the model, and the cycle repeats until the model says it is finished or a limit stops it. Everything else in an agent framework is packaging around that loop. The same loop can be split across helpers, which is the idea behind a subagent.
Anthropic's engineering guide, Building effective agents, describes agents in much the same terms, as models using tools based on feedback from their environment in a loop. The research pattern behind it, ReAct, interleaves reasoning steps with actions so each result informs the next decision.
The loop in code
This is a complete agent loop in plain Python. The call_model function stands in for any model API that can return either a tool request or a final answer.
def run_agent(task, tools, call_model): messages = [{"role": "user", "content": task}] for step in range(MAX_STEPS): reply = call_model(messages, tools) messages.append({"role": "assistant", "content": reply["content"]}) if reply["tool_call"] is None: return reply["content"] name = reply["tool_call"]["name"] args = reply["tool_call"]["args"] try: result = toolsname except Exception as error: result = f"Tool failed: {error}" messages.append({"role": "tool", "content": str(result)}) return "Stopped: step limit reached" ```
Read it in four parts. The messages list is the agent's entire memory, and nothing persists outside it. The call_model line is the thinking step, where the model chooses between answering and calling a tool. The tools line is the acting step, which runs real code. Appending the result is the observation step, which is how the model learns what happened.
The loop ends in two ways. The model can return a reply with no tool call, which means it considers the task done. Or the step counter runs out. Without that second exit, a confused model can run forever.
What each lap costs
Every lap sends the whole transcript again. The model does not remember earlier laps, so it must be shown them. That makes cost grow faster than the number of steps.
Take an illustration with made-up round numbers. The starting prompt is 2,000 tokens, and each lap adds 1,000 tokens from the tool call and its result.
Lap | Tokens sent to the model |
|---|---|
1 | 2,000 |
5 | 6,000 |
10 | 11,000 |
Across ten laps the model reads 65,000 input tokens in total, even though the final transcript is only 11,000 tokens long. That is 10 times 2,000, plus 1,000 times the sum of 0 through 9. Real numbers depend on the task, but the shape holds: doubling the steps more than doubles the input. Providers that support prompt caching reduce the price of the repeated part, and the transcript also has to fit in the context window, which puts a hard ceiling on how long a run can be.
How loops fail
Repetition. The model calls the same tool with the same arguments, gets the same result, and calls it again. The post on an AI coding agent stuck in a loop shows what this looks like in practice.
No stop condition. The model never decides it is done and keeps polishing.
Error spirals. A tool fails, the model retries the same failing call, and the error text fills the transcript.
Repeated side effects. A lap that sends an email or charges a card runs twice if the loop retries after a failure.
Overflow. The transcript outgrows the context window and early instructions fall out.
Four dials every real loop needs
A step cap, as in the code above, so a bad run ends.
A budget on tokens or money, checked on every lap.
A tool allowlist, so the model can only call what the task needs. See tool calling in AI agents for how the model requests a tool.
A human approval step before anything that cannot be undone, such as sending, deleting, or paying.
A framework gives you these settings under other names. The overview of what an AI agent framework is covers what they add, and the background on models themselves is in how AI models work.
FAQ
What is the difference between an agent and a chatbot?
A chatbot answers one message at a time. An agent can take actions through tools and use the results to decide what to do next, across several steps, without a new message from you at each step.
How many steps should an agent loop allow?
Set the cap just above what a normal successful run needs. If typical tasks take four to six steps, a cap of ten is reasonable. A higher cap mostly pays for runs that are already lost.
Is an agent loop the same as ReAct?
ReAct is one pattern for the loop, in which the model writes its reasoning before each action. The loop itself is more general. Modern tool-calling APIs run it without requiring the model to narrate.
Why does my agent repeat itself?
Usually because the tool result did not change what the model believes, or an error message gave it no new path. Add a repeat check that stops a call identical to the last one, and return clearer error messages from tools.
How did this land?
About the author

Staff Engineer, Platform
Carlo works on the platform that turns prompts into running apps. He writes the engineering deep dives and the changelog notes worth reading.


