# Stop conditions

The loop ends in one of two ways: the model answers without asking for a tool, or you hit a maximum number of steps.

AI developers · Part 04: Agents · Card 3 of 11 · Last updated 2026-10-13

## Analogy

A retry loop needs a max attempts value, or one flaky API turns into an infinite bill.

## Code example

`stop.ts`

```typescript
const MAX_STEPS = 10;

for (let step = 0; step < MAX_STEPS; step++) {
  // ...
  if (!message.tool_calls) return message.content; // natural stop
}
return "Stopped: step limit reached"; // safety stop
```

## In an agent

A confused agent can loop forever. The step limit is your circuit breaker.

## Practice

### Interview questions

**What is an AI agent?**

- An LLM running in a loop with access to tools.
- It decides at runtime which tool to call, looks at the result, and continues until the goal is met.
- Example: DevPilot lists open PRs on its own, then fetches reviews only for the stale ones.

**How do you stop an agent doing something harmful?**

- A maximum step limit.
- Zod validation of every tool argument.
- Least-privilege tools and human approval for write actions.
- Treat all tool output as untrusted data to defend against prompt injection.

## Questions people ask

### How does an AI agent know when to stop?

Two ways. The natural stop is when the model replies with text instead of asking for a tool, meaning it thinks the goal is done. The safety stop is a maximum number of steps that your code enforces. You need both, because a confused model can keep calling tools forever.

### What step limit should I set for an agent?

Start around 10 steps for most tasks and adjust it from real traces. Too low and good runs get cut off; too high and a stuck agent burns money before it stops. When the limit is hit, return a clear message saying the agent stopped, rather than failing silently.

## Related concepts

- [Human-in-the-loop](https://studyvisually.com/learn/tech/ai-developers/agents/human-in-the-loop)
- [Agent](https://studyvisually.com/learn/tech/ai-developers/agents/agent)
- [The agent loop](https://studyvisually.com/learn/tech/ai-developers/agents/agent-loop)
- [The model plans the steps](https://studyvisually.com/learn/tech/ai-developers/agents/model-plans-the-steps)

Web page: https://studyvisually.com/learn/tech/ai-developers/agents/stop-conditions
Study this card in the app: https://studyvisually.com/app/learn?category=ai-developers&card=stop-conditions
