Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 59/ 160
03. AI Agents

Stop Conditions

Hard limits on steps, tokens, time, and tool calls to prevent runaway agents.

IntermediateMax Steps · Budgets3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Rules that make the AI stop after too many steps, too much time or too much money, so it can't run forever.

Think of it like…

A car with a speed limiter, a fuel gauge and an emergency brake: normally you drive until you arrive, but if something goes wrong, the limits stop the trip before it becomes dangerous or expensive.

Where you’ve seen it

A research agent's configuration: max 12 model calls, 40,000 total tokens, 90 seconds wall-clock, 6 searches, 2 retries per tool, and a detector that stops if the last three tool calls are identical. One run keeps calling search('Zentel 2019 revenue') with no results; at the third identical call the detector fires, the agent stops and returns "I found Zentel's 2021–2024 revenue but could not find 2019 data after three attempts", with the sources it did find. Without the limits, a similar run previously made 140 calls before a human noticed.

Words you’ll hear

Step limit
Maximum number of model iterations or tool rounds per run.
Budget
Caps on tokens, cost or time that end the run when reached.
Circuit breaker
A rule that stops calling a failing or repeating tool after a threshold.
Graceful termination
Ending with a useful partial result and an explanation, not a crash.

Visual diagram

Loading interactive diagram

Theory & deep dive

Which limits to set

Steps: cap model iterations (typically 5 to 25 depending on the task) so a confused agent can't loop forever. Tokens and cost: track cumulative input and output tokens or estimated cost per run and per user, and stop at a ceiling; because input tokens grow with history, budgets matter more on long runs. Time: an overall deadline and per-tool timeouts, with cancellation that actually interrupts in-flight calls. Tool caps: limit the number of calls per tool (for example 6 searches) and total tool calls, protecting rate limits and paid APIs. Repetition detection: hash (tool, arguments) and stop or intervene after N identical calls, and detect cycles in the sequence of states. Error budgets: stop after N consecutive or total errors, with retries and exponential backoff for transient failures only.

Also define success and "can't do" conditions: the model returns a final answer that passes validation; the answer is explicitly "unable", and a confidence or verification check fails closed. Per-tenant and per-day aggregate budgets add a second safety net across many runs.

A run configuration

{"max_steps": 12, "max_tokens": 40000, "timeout_s": 90, "tool_limits": {"search": 6}, "max_identical_calls": 3, "max_consecutive_errors": 3, "daily_budget_usd": 50}

Key takeaway: Steps, tokens, time, tool caps, repetition and error limits, plus daily spend caps.

Ending well and testing the limits

When a limit triggers, don't just throw an exception. Run a finalisation step: stop calling tools, then ask the model (with a small reserved budget) to summarise what was accomplished, what remains and why it stopped, or build that message from structured state. Return partial results with sources, mark them clearly as incomplete, and give users options (continue, narrow the task, hand to a human). Make sure resources are cleaned up: close sandboxes, release locks and avoid leaving multi-step writes half-applied (use transactions or compensating actions).

Test limits deliberately with adversarial scenarios: a tool that always fails, a search that returns nothing, a prompt that induces repetition, a slow tool that exceeds the timeout. Check that each limit fires, the result is useful, state is saved, and alerts are emitted. Monitor in production: the rate of runs ending by each reason (success vs step limit vs timeout vs budget) is a health metric; a rising step-limit rate means a prompt, tool or model regression. Tune limits using data: set them above the typical successful run (for example the 95th percentile) but low enough to cap damage.

Tuning from data

Successful runs take a median of 5 steps, p95 of 9. Setting max_steps = 12 stops runaway runs while rarely cutting good ones; if 8% of runs end at the step limit after a prompt change, treat it as a regression signal.

Key takeaway: Finalise gracefully, test each limit, and monitor termination reasons.

How it works, step by step

Step 1 of 4
Design

1. Choose limits from data

Measure typical successful runs and set step, token, time and tool limits above p95 but well below runaway levels.

median 5 steps · p95 9 → limit 12
Key numbers at this step
Review
regularly

When to use it & trade-offs

What it is

Stop conditions are the rules that end an agent run: a success condition (the goal is met or the model returns a final answer) and hard limits that protect you when it isn't: maximum steps, token and cost budgets, wall-clock timeouts (overall and per tool), tool-call caps, repetition detection (the same call again and again), error budgets (too many failures) and an external cancel signal. When a limit fires, a good system ends gracefully: it returns what it has, explains what's incomplete and leaves state in a clean condition.

Why it matters: Agents decide their own next step, so nothing in the model guarantees they ever finish. A stuck loop can burn hundreds of dollars, hammer an API, or run for hours, and these incidents are among the most common and costly production failures. Hard limits are cheap insurance and a basic expectation in any agent design review.

When to reach for it

  • Every production agent
  • Agents calling paid or rate-limited APIs
  • Long-running autonomous tasks

When to avoid or be careful

  • Unbounded loops "for now"
  • Throwing an error with no partial result
  • Retrying non-transient failures forever

Kinds of limits

Step / iteration cap
Best for: Stopping infinite loops

Strengths: Simple and predictable.

Watch out: Doesn't bound cost per step.

Token and cost budgets
Best for: Protecting spend

Strengths: Directly caps money.

Watch out: Needs accurate usage tracking.

Timeouts and circuit breakers
Best for: Slow or failing tools and external APIs

Strengths: Protects latency and downstream services.

Watch out: Must handle cancellation and cleanup.

Interview signals & numbers to know

When this topic comes up

  • “The agent ran up a huge bill”
  • “It keeps calling the same tool”
  • “What limits should an agent have?”
  • Circuit breakers
  • Graceful degradation

Benchmarks & rules of thumb

5 – 25 -
typical step limits
3 -
identical calls before intervening in the example
p95 -
the reference point for setting limits

Common mistakes & follow-ups

Common interview mistakes

  • Setting a step limit but no token or time budget, so ten huge steps still cost a fortune.
  • Letting a timeout fire without cancelling the in-flight tool call.
  • Ignoring the rate of limit hits instead of treating it as a regression signal.

Likely interviewer follow-ups

  • What stop conditions would you put on a production agent?
  • How do you end a run gracefully when a limit is hit?
  • How do you choose the limit values?
Interview tip: List limits in layers (steps, tokens, time, tools, repetition, errors) and finish with "graceful partial result". That structure answers the question completely.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Stop Conditions with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Context Compaction
Next topic
A2A Protocol