Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Agent Concepts and Loops

Stop Conditions, Budgets and Loop Guards

Keep agents from running away: step, token, time and cost budgets, repeated-action detection, success checks and graceful fallbacks, with runnable Python.

An agent without a stopping rule is a bill waiting to happen. Models sometimes repeat themselves, chase a wrong idea, or keep "improving" a finished answer. Your program must be able to end the run on its own terms. This lesson covers the guard rails every loop should have: success conditions (we are done), budget conditions (we have spent enough) and stuck conditions (we are going nowhere). It also covers what to do when the run is stopped: give a useful partial result, not a crash.

Four kinds of stopping rules

Rule Example Why
Success The model returns a final answer; the tests pass The goal is met
Step budget At most 15 model calls Bounds loops and cost
Resource budget Max tokens, seconds or dollars Protects money and latency
Stuck detection Same action 3 times in a row Catches loops early

A good loop checks all of them each iteration and records why it stopped. Knowing whether a run ended by success, budget or stuck-detection is precious data for evaluation later.

A budget object

Rather than scatter counters around the loop, collect them in one object that answers a single question: may we continue?

Python A Budget class with several limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop above stops because the token budget runs out before the step limit does. Whichever budget is hit first wins. Put the check at the top of the loop, before spending anything.

Detecting loops

Models can get stuck calling the same tool with the same arguments. A simple guard remembers recent actions and gives up (or nudges the model) when it sees too many repeats.

Python Repeated-action detector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When stuck is detected you have choices: stop with a partial answer, inject a message such as "You have already tried this. Try a different approach", or escalate to a human. The nudge is cheap and often works the first time, but it should be allowed only once or twice.

Success conditions you can verify

"The model said it is done" is the weakest success signal. Where possible, tie success to something your code can check: the file exists, the tests pass, the JSON matches the schema, the total equals the sum of the parts. When the model claims it is done but the check fails, feed the failure back as an observation and continue. This is the same verify-and-retry idea you saw in use cases and limits.

Python
# Read-only pattern: verify the model's claim before accepting it
if action["type"] == "final":
    problem = verify(action["answer"])       # your own check
    if problem is None:
        return action["answer"]
    messages.append({"role": "user", "content": f"Not accepted: {problem}"})

Graceful endings

A run that is stopped by a budget still has value. Return a structured result so callers can tell what happened:

Python A result object that says why the run ended

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second run did not finish, but the caller receives what was found and a clear status, so it can show a partial answer, retry with a bigger budget, or alert someone.

Choosing limits

Start with limits slightly above what normal successful runs use. Log the number of steps of real runs, look at the 95th percentile, and set the cap a bit higher. Too tight a cap fails good runs; too loose a cap lets bad runs burn money. Also set a per-tool timeout so one hanging call cannot consume the whole time budget, and, in production, a per-user or per-day spending cap outside the loop entirely.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where in the loop should the budget be checked?

    Checking first prevents one more costly call after the budget is already used up.
  2. 2. What does stuck detection typically look for?

    Repeating an identical action without new information is the classic sign of a loop.
  3. 3. Why record the reason a run stopped?

    The stop reason is key data. A rising share of budget endings means the agent or the limits need work.
  4. 4. The model claims it is done but your check fails. What should the loop do?

    Verification beats trust. Returning the failure gives the model a chance to fix the problem.

Summary

  • Every loop needs success, budget and stuck conditions, checked each iteration.
  • Collect limits in a Budget object: steps, tokens, time (and cost in production).
  • Detect repeated identical actions, then nudge or stop.
  • Prefer verifiable success checks over "the model said so".
  • Return a structured result with a stop reason and any partial work.

Next: Workflows versus Agents