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.
Last updated
Analogy
A retry loop needs a max attempts value, or one flaky API turns into an infinite bill.
Code example
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 stopIn 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.