Area 03 · AI Agents · Concept 19 of 20

Stop Conditions

Step limits, budgets, timeouts and ‘done’ checks, so the agent can’t loop forever.

11–20 · Production levelPhase 3 · Weeks 11–14≈ 45 min

The idea

Agents can loop: retrying the same failing search, oscillating between two plans, or researching forever. Without hard limits, one bad run can burn a large bill. Stop conditions end runs safely.

Use several: maximum steps, maximum tokens or cost, wall-clock timeout, repeated-action detection (same tool with the same arguments three times), and an explicit completion check (the model calls a finish tool with its result).

When a limit hits, stop gracefully: return partial results, what was tried, and why it stopped. Log every stop reason so you can see which limits trigger and tune them.

Why it matters

It is the difference between a demo and something you can leave running in production.

Words to know

  • BudgetA hard cap on steps, tokens, money or time for one run.

Try it without code

Set budgets

  1. For your research agent, choose max steps, max cost and a timeout.
  2. Write what the user sees when each is hit.

Use it in code

A guard object checked on every step.

python
import time
from collections import Counter

class Guard:
    def __init__(self, max_steps=12, max_usd=0.50, max_seconds=120):
        self.max_steps, self.max_usd, self.deadline = max_steps, max_usd, time.time() + max_seconds
        self.steps, self.usd, self.calls = 0, 0.0, Counter()

    def check(self, step_cost, tool_calls):
        self.steps += 1; self.usd += step_cost
        for c in tool_calls:
            self.calls[(c.name, str(sorted(c.input.items())))] += 1
        if self.steps >= self.max_steps:      return "step limit"
        if self.usd >= self.max_usd:          return "budget"
        if time.time() > self.deadline:       return "timeout"
        if any(n >= 3 for n in self.calls.values()): return "repeating the same call"
        return None
PRACTICE · TICK IT AFTER THIS

Wire the guard into your loop, force each condition once, and confirm the user gets a useful partial answer.

Common mistakes

  • Only a step limit, no cost limit.
  • Stopping silently with no explanation.

Go deeper