What Is an Agent Loop?
The agent loop is the fundamental execution pattern of an AI agent. It describes the repeated cycle of perceiving input, reasoning about the next action, executing that action, and then observing the outcome — continuing until the task is done.
This loop is what separates an agent from a one-shot LLM call. Instead of producing a single response and stopping, the agent keeps running, using the results of each action to inform the next decision.
The Steps of an Agent Loop
A typical agent loop looks like this:
- Perceive — The agent reads the current state of the world. This might be the original user query, the result of a previous tool call, or updated context from memory.
- Think — The LLM reasons about the state and decides what to do next. It may produce a chain-of-thought trace, select a tool, or determine that the goal is complete.
- Act — The agent executes the chosen action: calling a web scraping API, querying a database, running code, or generating a response.
- Observe — The result of the action is fed back into the agent's context.
- Repeat or Stop — If the goal is not yet met, the loop restarts from step one. Otherwise the agent produces its final output.
Why Loops Enable Complex Tasks
A single LLM call has a fixed context window and no ability to gather new information mid-response. The agent loop removes those constraints. By iterating, an agent can:
- Break a large problem into smaller steps it solves one at a time.
- Correct mistakes discovered mid-task.
- Retrieve additional information only when needed, keeping context efficient.
A Concrete Example
An agent tasked with "Summarize the product pages of these five URLs" might loop as follows:
- Iteration 1 — Call KnowledgeSDK's
/v1/scrapefor URL #1, observe the markdown output. - Iteration 2 — Call
/v1/scrapefor URL #2, observe. - Iterations 3–5 — Repeat for remaining URLs.
- Final iteration — Synthesize all observations into a summary and stop.
Each iteration is one pass through the loop. The agent could not have done this in a single step without the loop structure.
Stopping Conditions
Loops must terminate. Common stopping conditions include:
- The agent decides the goal is achieved.
- A maximum number of iterations is reached (a safety limit).
- An error or unexpected state causes a graceful exit.
- The user explicitly cancels the task.
Without clear stopping conditions, an agent can run indefinitely — consuming tokens and API calls without making progress.
Agent Loop Frameworks
Popular frameworks like LangChain, LlamaIndex, and CrewAI all implement variations of the agent loop. Understanding the loop conceptually helps you debug agent behavior regardless of which framework you use, because the core pattern is always the same.