Loop

Repeat until good enough, or budget runs out.

One or more steps are repeated until a specific budget, quality bound, or exit condition is reached.

Level
02 · Workflow
Also known as
Control Loop, Retry Loop, Agent Loop
Trade-off
Adaptive improvement is achieved at the risk of endless or highly expensive execution loops.
Native in
LangGraph, CrewAI, Microsoft Agent Framework, Google ADK, AWS Strands
The mental model

A loop you can draw on a napkin.

A body step produces output; a check step decides whether to exit or loop again.

BodyCheckEnd
Walk it through

A real run, step by step.

TaskAn agent repairs a failing test suite. The loop has three exits: no failing tests, six rounds used, or two rounds without progress.
Illustrative run. Rounds 5 and 6 are never spent.
RoundActionFailing testsExit check
1Fixes a broken import7Continue
2Fixes the date parsing3Continue
3Changes the rounding3Continue, one round without progress
4Changes the rounding again3Stop: no progress in two rounds
What this shows: the goal alone is not an exit condition, because the goal may never be reached. Without the progress check this run would have spent two more rounds on the same three tests. A loop needs at least one exit that does not depend on success.
In code

The pattern in code.

Plain Pythonpython
def run_until_green(task, max_rounds=6, patience=2):
    best, stale = float("inf"), 0
    for _ in range(max_rounds):  # exit 1: the budget
        apply_fix(task)
        failing = run_tests()
        if failing == 0:  # exit 2: the goal
            return "done"
        stale = stale + 1 if failing >= best else 0
        best = min(best, failing)
        if stale >= patience:  # exit 3: no progress
            return "stopped: no progress"
    return "stopped: budget used up"
Fit

Use it, or not.

When to reach for it

  • The result can be iteratively improved.
  • External validation triggers a retry.
  • Tool results necessitate new iterations.

When it backfires

  • There is no stable exit condition.
  • Costs can spiral out of control.
  • Errors amplify through repetition.
Pitfalls

Two ways this pattern will hurt you.

No exit condition — the loop spins forever

The check step always returns 'retry' because the quality threshold is set impossibly high.

Countermeasure

Combine quality gate with a hard iteration cap. Treat cap exhaustion as a normal outcome, not an error.

Errors amplify through repetition

Each loop appends to the same context. A bad intermediate gets baked in and the model compounds it rather than fixing it.

Countermeasure

Keep only the latest iteration in context, or use a scratchpad that the model must explicitly update.

Framework support

Where Loop is native.

LangGraphNative
CrewAICrewAI FlowsNative

Search

Search patterns, frameworks, and pages.