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.
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
- For your research agent, choose max steps, max cost and a timeout.
- Write what the user sees when each is hit.
Use it in code
A guard object checked on every step.
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 NoneWire 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.