# The loop

Canonical URL: https://developers.iagenify.com/sdk/agent/loop/
Language: en

One step is one model turn plus the tools it asked for. The loop runs until the model stops asking — or until a ceiling you set says otherwise.

Status: maxSteps 100 · 4 stop reasons · one turn per step

## What happens in one step {#step}

- Stop if `stop()` was called, if the step ceiling is reached, or if the budget is spent.
- Build the [system prompt](/sdk/agent/system-prompt) — workspace, mode, tools, storages, memory.
- [Clear old tool results](/sdk/agent/context/clearing) if the context is heavy, then [compact](/sdk/agent/context/compaction) if that was not enough.
- Ask for one model turn, with the tool declarations. Emit `turn`.
- If the model wrote text, emit `text`.
- If it asked for no tool, the loop ends.
- Otherwise run the calls — [in parallel or one at a time](/sdk/agent/parallelism) — and append each result as a `tool` message.

Then it starts again. Nothing else decides when to stop: the model's own silence is the normal ending.

## The four endings {#stop}

| stopReason | Means |
| --- | --- |
| `end_turn` | The model answered without calling a tool. The normal end. |
| `stopped` | `stop()` was called. The current tool finishes, nothing new starts. |
| `max_steps` | The step ceiling was reached — `maxSteps`, 100 by default. |
| `budget` | The credits spent reached `budget`. |

```javascript
const result = await agent.run({ inputs: "…" });

switch (result.stopReason) {
  case "end_turn":  break;                       // it answered
  case "max_steps": console.warn("ceiling reached — the work is unfinished"); break;
  case "budget":    console.warn("budget spent — ", result.usage.credits); break;
  case "stopped":   break;                       // you asked it to stop
}
```

> **max_steps and budget are not failures, and not successes**
>
> The run ends with whatever text the model last produced, which may be a half-finished thought. Treat either reason as « unfinished » rather than as an answer, and either raise the ceiling or narrow the task.

## What run() returns {#returns}

```javascript
{
  text: "I read the four notes. Two are unfinished: …",
  todos: [{ content: "Check the figures", status: "completed" }],
  usage: { credits: 31, turns: 6, toolCalls: 9 },
  stopReason: "end_turn",
  model: "gemini-3.5-flash"
}
```

`text` is the last thing the model wrote, which is not always the last step: a run that ends on `max_steps` returns the most recent text, even if a tool ran after it.

## The step ceiling {#ceiling}

`maxSteps` defaults to **100**, which is high on purpose — it is a runaway guard, not a budget. The thing that should normally stop a run is [budget](/sdk/agent/budget), because it is denominated in what you actually care about.

A subagent is capped at **40** steps whatever the parent's ceiling, since it is given one self-contained job.

## Stopping a run {#stopping}

```javascript
const running = agent.run({ inputs: "…" });

setTimeout(() => agent.stop(), 30_000);

const result = await running;    // stopReason: "stopped"
```

`stop()` aborts the model request in flight and sets the flag the loop reads at the top of each step. Tool calls already queued in the same turn answer « Stopped by the user. » rather than running. Children are stopped too.

## An error ends the run {#errors}

Anything a tool throws is caught and handed back to the model as a failed tool result — the model adapts. What is **not** caught is a failure of the turn itself after retries and fallbacks: an `error` event is emitted and `run()` rejects.

- [Parallelism](/sdk/agent/parallelism): Which calls run together, and why the rest do not.
- [Budget](/sdk/agent/budget): Stopping on credits rather than on steps.
- [Events](/sdk/agent/events): Everything onEvent receives.

```python
result = agent.run(inputs="…")

reason = result["stopReason"]
if reason == "max_steps":
    print("ceiling reached — the work is unfinished")
elif reason == "budget":
    print("budget spent — ", result["usage"]["credits"])
# "end_turn": it answered · "stopped": you asked it to stop
```

```python
{
    "text": "I read the four notes. Two are unfinished: …",
    "todos": [{"content": "Check the figures", "status": "completed"}],
    "usage": {"credits": 31, "turns": 6, "toolCalls": 9},
    "stopReason": "end_turn",
    "model": "gemini-3.5-flash",
}
```

```python
import threading

threading.Timer(30, agent.stop).start()

result = agent.run(inputs="…")    # stopReason: "stopped"
```
