# Agent Loop

**Also known as:** Perceive–decide–act cycle · ReAct loop  
**Category:** AI Patterns (Model in the loop)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/ai/agent-loop

*A model, some tools, and a loop that runs until the work is done.*

One model call is a function: prompt in, text out. That is enough when you know every step in advance. It is not enough when step four depends on what step three found, because you cannot write the prompt for step four yet.

The agent loop solves this. Call the model with the conversation so far. It returns either an answer or a request to use a tool. Run the tool, add the result to the conversation, and call again. The loop itself is easy. The work is in its limits: the cost of each turn, a transcript that keeps growing, and a clear way to stop.

> **In one sentence.** An agent is a loop that calls a model with the result of its last action. The hard design work is deciding how the loop stops.

## Origin (2022)

Named by the ReAct paper (Yao et al.), which mixed a model's reasoning with real actions and often beat either one alone. The shape is older: sense–plan–act in robotics, and the read–eval–print loop of every REPL.

## The parts of one turn

### The transcript (Message history)

The list of everything so far: the system prompt, the user's request, each model reply and each tool result. It is the loop's only state. The model remembers nothing between calls.

- Sent in full on every call, so it is also the cost of each turn
- Grows every turn until something compacts it

> [system, user, assistant(tool_use), tool_result, assistant(tool_use), …]

### The model call (The decide step)

One request with the transcript and the tool schemas. It returns text for the user or a structured request to run a tool. It is the only non-deterministic step; the rest of the loop exists to contain it.

- The same input can give a different output
- Returns a stop reason, and that is what the loop branches on

### The tool call and its result (The act step)

The model names a function and its arguments. Your code checks them, runs the function, and adds the result to the transcript. The model only asks; your code decides.

- Arguments are model output, so treat them as untrusted input
- Cap the size of a result before you add it

### The stop condition (The governor)

Every reason the loop may exit: the model says it is done, the budget is spent, it keeps repeating itself, or an action needs a person. Only the first is the happy path.

- “Done” from the model is a claim, not a proof
- A turn limit is the cheapest exit, and the one most often missing
- Every exit needs a defined result

## Design rules

### Set the limits before you write the loop

Set a maximum number of turns, a token budget and a deadline, and enforce them in code. An unbounded loop does not crash. It quietly bills you for forty turns of rereading the same file.

### Send tool errors back into the loop

When a tool fails, return the error as a result the model can read. It often fixes its own arguments on the next turn. Exit only for what it cannot fix: no budget left, a blocked action, the provider down.

### Detect repeats, not just missing answers

The typical failure is not stopping too early. It is calling the same tool with the same arguments again and again, sure that it is making progress. Track the last few calls and stop when they repeat.

### Save the transcript after every turn

If the transcript lives only in memory, a crash or a deploy loses the work and hides what already happened. Save it, and the loop can resume. It can also pause for an approval that takes an hour.

## Diagrams

Rendered as geometry on the guide page; not reproducible as text.

- `agent-turn` — see https://layra4.dev/architectures/ai/agent-loop

## One agent, laid out

```
src/agent/
loop.ts                         # the driver: turns, dispatch, exits. No domain logic
budget.ts                       # turn cap, tokens, deadline, repeats
transcript.ts                   # append, save, resume
tools/                          # one file per tool: schema + handler + tests
  index.ts                      # the list the model is shown
  searchOrders.ts               # read-only
  issueRefund.ts                # changes data, so needs approval
guards.ts                       # argument checks and the approval gate
prompts/                        # system prompt + tool descriptions
```

Only the driver knows what a turn is. Tools are ordinary functions you can test with no model.

## Examples

### The whole loop

```typescript
type Stop = "answered" | "out-of-turns" | "no-progress" | "needs-human";

export async function run(task: string, budget: Budget): Promise<Result> {
  const messages: Message[] = [{ role: "user", content: task }];

  for (let turn = 0; turn < budget.maxTurns; turn++) {
    const reply = await model.call({ system, tools: registry.schemas, messages });
    messages.push(reply);

    // Exit 1: the model says it is finished. A claim, not a guarantee.
    if (reply.stopReason !== "tool_use") {
      return { stop: "answered", text: reply.text, messages };
    }

    // Exit 2: it wants to do something that needs a person.
    if (registry.needsApproval(reply.toolCalls)) {
      return { stop: "needs-human", pending: reply.toolCalls, messages };
    }

    // Exit 3: the same call for the third time. It is stuck.
    if (budget.isRepeating(reply.toolCalls)) {
      return { stop: "no-progress", messages };
    }

    // Act, and write the result back, failures too, so the model can correct itself.
    for (const call of reply.toolCalls) {
      messages.push(await registry.run(call));
    }
  }

  // Exit 4: the budget ran out. Always reachable, and often left undefined.
  return { stop: "out-of-turns", messages };
}
```

About thirty lines, and the interesting half is the exits.

## When to use

- The next step depends on what the last step found
- The number of steps is unknown: investigate, debug, research
- A wrong step can be seen and corrected on the next turn

## When not to use

- You know the steps in advance — write a pipeline instead
- One model call would do the job
- Cost or latency per request must be fixed and predictable

## Benefits

- Handles tasks whose shape you only learn while doing them
- A failed tool call becomes input the model can fix, not a crash
- A new ability is a new tool; the loop itself does not change

## Costs

- Cost varies a lot: the worst 1% of runs can cost many times the median
- Each turn resends the whole transcript, so long runs get expensive fast
- You debug by reading a transcript, not by stepping through code

## Pitfalls

- No turn limit. The only exit is the model deciding it is finished, so a confused run never stops.
- Throwing on a tool error. The model never sees the error, so it cannot correct itself.
- Adding one huge tool result to the transcript, then paying for it on every later turn.
- Adding more agents to fix a loop whose real problem is vague tool descriptions.

## Similar patterns, compared

The loop is confused with every pattern that runs steps in order. The question is always who decides the next step, and when.

### Agent Loop vs Planner–Executor

Same parts, opposite commitment: the loop decides one step at a time; the planner writes the whole list first. — [Planner–Executor](https://layra4.dev/architectures/ai/planner-executor)

**What is genuinely the same**

- Both call a model many times, with the same tools and a budget

**What actually differs**

- A plan can be priced before the first side effect; the loop's route exists only afterwards
- The loop adapts on the next turn; a plan must re-plan

**Pick Agent Loop when:** What you find in step two really changes what step three should be.

### Agent Loop vs Pipes & Filters

You fix a pipeline's order when you build it; the model picks the loop's order at run time. — [Pipes & Filters](https://layra4.dev/architectures/application/pipes-and-filters)

**What is genuinely the same**

- Both pass work through steps, each using what the last one produced

**What actually differs**

- A pipeline's route is fixed and testable; the loop's is new on every run
- A pipeline always ends; a loop ends only because you made it

**Pick Agent Loop when:** You cannot write the sequence down, because it depends on what earlier steps find.

### Agent Loop vs Saga / Process Manager

A saga knows every step and its undo in advance; a loop cannot. — [Saga / Process Manager](https://layra4.dev/architectures/architectural/saga)

**What is genuinely the same**

- Both coordinate side effects that can fail in the middle, and need saved state

**What actually differs**

- A saga lists its steps and compensations up front; the loop finds its steps as it goes
- A saga can promise to undo what it did; a loop can only ask the model to try

**Pick Agent Loop when:** The sequence cannot be known in advance. If it could, use the saga.

### Agent Loop vs Agent Harness

The algorithm and the program that runs it: the loop is one turn; the harness makes the turn possible and limits it. — [Agent Harness](https://layra4.dev/architectures/ai/agent-harness)

**What is genuinely the same**

- Both get called “the agent”, and in a small codebase they are one file

**What actually differs**

- The loop decides what to do next; the harness decides what is possible and allowed
- The loop's exits are conditions; the harness enforces them

**Pick Agent Loop when:** You are thinking about how a turn runs and why it stops, not about what the agent may touch.

## Related patterns

- [Agent Harness](https://layra4.dev/architectures/ai/agent-harness) — the program this runs inside: workspace, tools, permissions, budgets
- [Tool Use](https://layra4.dev/architectures/ai/tool-use) — the act step: how the loop reaches anything outside itself
- [Context Compaction](https://layra4.dev/architectures/ai/context-compaction) — what to do when the transcript outgrows the window
- [Human in the Loop](https://layra4.dev/architectures/ai/human-in-the-loop) — the exit for actions a person must approve
- [Planner–Executor](https://layra4.dev/architectures/ai/planner-executor) — the alternative: decide the whole route before acting

## Further reading

- *ReAct: Synergizing Reasoning and Acting in Language Models* — Yao et al. (2022)
- *Building effective agents* — Anthropic (2024) — Argues most “agents” should be fixed workflows, and says when a loop is worth it.
- *LLM Powered Autonomous Agents* — Lilian Weng (2023) — A survey of planning, memory and tool use.
