🚀 SaaS & AI — book a free roadmap call →
✦ AI & RAG apps that understand your business data →
⇄ Multi-marketplace order & inventory automation →
📅 Taking a limited number of new builds this quarter →
← All posts
AI / Agents

Loop engineering: stop prompting your AI, start designing the loop

For a few years the skill everyone chased was writing the perfect prompt. Then, in mid-2026, a single idea reorganised how a lot of people work with AI: stop prompting your agent by hand, and design the loop that prompts it for you. This is the full tutorial — what a loop is made of, which loop pattern to pick, the stop conditions you must define before you start, why loops quietly become expensive, and how to build one that converges instead of spinning.

The 30-second version

  • Prompt engineering optimises a message. Loop engineering optimises the cycle. You stop being the one hitting enter and become the one who designs the thing that hits enter.
  • Every loop has five parts: a trigger, a checkable goal, an action space, real verification, and memory between turns.
  • You need three exits, not one: success, failure and budget. Most broken agents are missing two of them.
  • Loops get expensive super-linearly, because every failed attempt stays in context and gets re-read on every later turn.
  • Verification must come from outside the agent — a test, an exit code, a schema. An agent grading its own homework is not a stop condition.

1. The moment the job changed

In June 2026 an engineer working on AI coding tools described how their own workflow had changed, and the sentence spread everywhere:

"I don't prompt the model any more. I have loops running. They are the ones prompting it and figuring out what to do."

The remark, from an engineer behind a widely-used coding agent, that named the shift

Within weeks the practice had a name. Essays by Addy Osmani, a viral one-liner from Peter Steinberger, and a wave of developers putting their coding agents on repeat turned loop engineering into the phrase of the season — the same treadmill that ran from prompt engineering (2023) to context engineering (2025) and on to graph engineering a month later.

Underneath the branding is a genuine change in what the work is. The question stops being "what should I type?" and becomes:

The loop engineer's question

What system should I build so the agent finds the work, does it, checks it, and remembers what it did — without me in the loop at all?

↑ back to top

2. Prompt, context, loop, harness — how the layers fit

These four terms get argued about as if they compete. They don't. They are nested layers, and knowing which one you are actually working on saves a lot of wasted effort.

HARNESS · the whole system that runs it — tools, sandbox, retries, logging LOOP · the cycle that decides what happens next turn CONTEXT · everything the model sees on this turn PROMPT · the words in this one message
Each layer contains the one below it. Most teams that are "bad at agents" are working two layers too low — polishing prompts when the loop is what is broken.
SYMPTOM

You keep rewording the prompt

and it works on the example you are testing, then fails on the next one. That is almost never a wording problem. The loop has no feedback, so nothing corrects.

SYMPTOM

It works for three turns then drifts

The loop is fine; the context is. What the model sees on turn four no longer contains what it needed from turn one.

↑ back to top

3. The five parts of every loop

A loop is not "call the model again". Strip any working agent down and you find the same five components. Leave one out and it fails in a way you can predict from which one is missing.

  1. Trigger — what starts it A schedule, an event, a webhook, a human instruction, or another agent finishing. If a person has to start it every time, you have automation with extra steps, not a loop.
  2. Goal — a state you can check Not "improve the code" but "the test suite passes and no new lint errors". If you cannot write the success condition in one sentence, the task is not scoped yet — rescope it before writing any code.
  3. Actions — what it may do The tools available on each turn: read a file, run a command, call an API, spawn a sub-agent. A wider action space is not better; it is more ways to go wrong.
  4. Verification — how you know Genuine evidence from outside the agent: an exit code, a test result, a schema validation, a diff review, a supervisor. This is the component people skip, and skipping it is why their loop never terminates correctly.
  5. Memory — what carries across turns What the next iteration knows about the last one. Too little and it repeats failed attempts; too much and it drowns in its own history. Both failure modes are common and they look nothing alike.
TRIGGER DECIDEACT OBSERVEVERIFY memory carries across turns EVERY TURN, CHECK: EXIT · goal verified EXIT · unrecoverable EXIT · budget spent
The cycle, and the three ways out of it — all three evaluated on every turn. A loop with only the green exit is the single most common shape of a failed agent.
↑ back to top

4. ReAct, and the four loop patterns worth knowing

The intellectual ancestor is ReAct (Reason + Act), from research at Princeton and Google, which interleaved reasoning steps with action steps. It showed something that now feels obvious: a model that observes the result of each action before taking the next one behaves completely differently from one that answers in a single shot.

ReAct is not the only shape, though, and picking the wrong one is expensive. Here are the four you will actually meet:

PatternHow it worksBest forWeakness
ReActThink → act → observe, one model call per step, next step decided from what just happenedExploratory work where you genuinely cannot plan aheadCost grows fast on long chains; no global view
Plan-and-ExecutePlan all steps up front, execute them, replan only on failurePredictable multi-step work; inspectable before it runsA bad plan executes confidently to the end
ReWOOPlan with placeholders, run the tool calls, fill in the results afterwardsCutting model calls when steps don't depend on each otherFalls apart when steps genuinely are dependent
ReflexionOn failure, write a natural-language post-mortem and carry it into the next attemptRetry-friendly tasks with a real verifier, e.g. testsWithout ground truth, it reflects confidently and wrongly

Reported comparisons: Plan-and-Execute has been measured around 92% task completion against ReAct's 85% on the same suite, while ReAct runs roughly 3–5 model calls and 2,000–3,000 tokens per task. Reflexion's headline result was a jump from 67% to 91% pass@1 on a coding benchmark across three attempts — the gain coming entirely from the self-reflection step.

The honest caveat on Reflexion

That 91% is real, but it came with a test suite as the judge. In evaluations without a hard verifier, Reflexion has been reported as the worst performer of the group — reflection with nothing to check against just produces eloquent self-deception. Reflection is an amplifier of your verifier, not a substitute for one.

Choosing, in one line each

Can you write the steps in advance? Plan-and-Execute. Does each step depend on the last result? ReAct. Do you have a test suite that says pass or fail? Add Reflexion on top. Are the steps independent? ReWOO, or just run them in parallel.

↑ back to top

5. The three exits you must define before you write the loop

This is the highest-value section of this tutorial. Nearly every agent horror story is a loop with one exit where it needed three.

EXIT 1 · SUCCESS

The goal is verifiably met

Tests pass, the schema validates, the file exists with the right shape. Checked by something outside the agent — never by asking the agent whether it is finished.

EXIT 2 · FAILURE

It cannot get there

An unrecoverable error, a per-action retry limit exceeded, or no measurable progress across N turns. Missing this exit means thrashing forever on a broken state.

EXIT 3 · BUDGET

It has cost enough

A turn cap, a token cap, a wall-clock limit. Missing this exit is what turns a slow failure into an expensive one — the difference between a bug and an invoice.

Check limits before the call, not after

A post-flight check discovers the breach once you have already paid for it. A pre-flight check refuses the next call. That one inversion is the difference between a budget cap and a budget report.

# the loop everyone writes first — one exit, three ways to hurt you
while True:
    result = agent.run(task)
    if looks_done(result):        # the agent's own opinion. not evidence.
        break

# the loop that survives contact with production
for turn in range(MAX_TURNS):          # exit 3a: hard turn cap
    if spent >= TOKEN_BUDGET:           # exit 3b: checked BEFORE the call
        return halt("budget", turn)

    action = agent.decide(goal, context)
    result = run(action)
    spent += result.tokens

    if verify(goal, result):            # exit 1: external evidence
        return done(result)
    if result.fatal or retries(action) > 3:
        return escalate("unrecoverable")  # exit 2a
    if no_progress(context, result, window=3):
        return escalate("stuck")          # exit 2b: the one people forget

    context = compact(context, result)   # see §7 — or this gets expensive
else:
    escalate("no progress within budget")

Typical starting values people converge on: a turn cap somewhere around 15–25 for a focused task, a per-action retry limit of 2–3, and a no-progress window of 3 turns. Tune from there — but set all three on day one, not after the first incident.

↑ back to top

6. Verification: the part that decides everything

The rule

A loop can only be as good as the signal that tells it whether it is winning. If the agent is the only judge of its own output, you do not have a loop — you have a very expensive way of generating confident text.

Useful verification comes in three tiers, and mature loops run all three:

The critical property is that all three come from outside the model. "The agent reports what the script says, not what it thinks." For code work this is why test-driven loops dominate: the test suite is an oracle the agent cannot argue with, and writing the test first has been reported to roughly halve wasted retry cycles.

The one-sentence test

Before you start, write the success condition in a single sentence. If you can't, you are not ready to build the loop — you are still deciding what the task is. This single habit prevents more failed agents than any framework choice.

↑ back to top

7. Why loops get expensive (the maths nobody shows you)

Here is the thing that surprises teams. A loop does not cost N × one call. Most naive loops feed the entire growing conversation back to the model every turn, so every failed attempt is re-read on every subsequent turn. Cost grows with the square of the turn count, not linearly.

CONTEXT ON TURN 1CONTEXT ON TURN 5 system + goalthe task — room to work — system + goalthe task failed attempt 1failed attempt 2 failed attempt 3failed attempt 4 ↑ each one re-read, and re-paid for, on every later turn
The compounding problem. Failures don't just cost you once — they become permanent tax on every remaining turn, and they crowd out the room the model needs to think.

The reported scale of this is genuinely large:

MeasurementReported figureWhat it means for you
A 10-turn loop vs one linear call~50× the tokensTurn count is your primary cost dial
Agentic coding vs ordinary chat~1,000× the tokensPilot economics do not predict production
Same task, run twiceup to 30× varianceBudget for the bad run, not the average
Pilot chatbot → production agent5–30× gapThe demo bill is not the real bill
Single chat turn → multi-agent workflow~30×, up to 70×Sub-agents multiply, they don't divide

Figures collated from published 2025–2026 measurements including Stanford Digital Economy Lab work on agentic coding and Gartner's pilot-to-production token gap. Orders of magnitude are the useful signal here, not the exact multipliers.

The worked example everyone should read once

A four-agent workflow with silent retries and no budget exit ran for eleven days and cost $47,000. Nothing exotic went wrong. It simply kept retrying, and no one had written the line that says stop.

↑ back to top

8. The failure gallery

Failed agents fail in a small number of recognisable ways. Learning to name them is most of learning to fix them.

FAILURE 01

The doom loop

The agent repeats the same failing action forever because nothing measures progress. Fix: a no-progress detector over a window of turns, not just a turn cap.

FAILURE 02

Context bloat

The conversation balloons until the model is drowning in its own failed attempts, and hallucination rates climb. Fix: compact between turns; keep the lesson, drop the transcript.

FAILURE 03

Goal drift

Twelve turns in, it is solving a different, easier problem. Fix: re-state the immutable goal and the "what this does NOT do" line in every turn's system prompt.

FAILURE 04

Budget-pressure shortcuts

Near its limit, the agent stops reading files and starts guessing confidently. Fix: pre-flight budget checks that refuse a degraded attempt rather than starting one.

FAILURE 05

Silent retry

Every failure is retried invisibly, so a broken run looks identical to a slow one until the invoice arrives. Fix: log every turn; make retries visible and countable.

FAILURE 06

Retrieval thrash

A lookup misses, so it broadens the query, pulls more documents, and reconciles contradictions — repeatedly. Fix at the source: stale context is worse than none.

Notice how many of these are observability problems rather than intelligence problems. You cannot fix a loop you cannot see. Which leads directly to the next section.

↑ back to top

9. The production-safe loop: spec, breaker, ledger, gate

A pattern has settled for loops that are allowed to run unattended. Four components, none of them clever, all of them boring in the way production things should be:

  1. The spec — commitment before execution Three questions, answered and frozen before the loop runs: what does this do? What does it explicitly not do? What does done look like, in one sentence? Inject all three into every turn's system prompt so the goal cannot drift.
  2. The circuit breaker — hard ceilings, checked pre-flight A turn limit and a token limit, evaluated before each model call. No soft warnings, no grace periods. Breach raises immediately and hands off to a human.
  3. The ledger — an append-only audit trail One row per turn: turn number, tokens used, duration, pass or fail, and the breach reason if it stopped. No updates, no deletes. When something goes wrong at 3am, this file is the only reason you will be able to explain it.
  4. The review gate — the loop runs to you Nothing flows downstream until a human has seen the original promise, the acceptance criteria, what actually changed, the evidence, and the unresolved assumptions. Put the gate exactly where a mistake is expensive to reverse.
A deliberately unpopular recommendation

Consider not implementing automatic retry inside the loop. Retrying re-reads a context window that just got bigger, so each attempt costs more than the last, and silent retries are precisely how runaway bills happen. Record the failure, stop, and let a scheduled run or a human restart it. A cron job wired to a bounded loop beats a loop that never stops.

↑ back to top

10. Seven levers for cheaper loops

In rough order of how much they typically save:

  1. Reduce turns Turn count is the dominant cost term because of compounding. A better first prompt that saves three turns beats almost any other optimisation.
  2. Compact between turns Carry forward the lesson ("approach X fails because Y") instead of the full transcript of the failure. This attacks the squared term directly.
  3. Tier your models Reserve the strongest model for the decide step; run routine observation and summarisation on a cheaper one. Reported savings for the routine portion run roughly 60–80%.
  4. Isolate sub-agents Give a sub-agent a narrow task and a fresh context, and return only its conclusion. The parent never pays for the child's transcript.
  5. Verify cheaply before verifying expensively Run the fast check every turn and the full suite only when the fast check passes. Most turns fail for cheap reasons.
  6. Scope the tools Every tool definition is tokens on every turn. Fifteen tools the agent never uses is a tax paid on each iteration.
  7. Fix stale context at the source Out-of-date documents look identical to current ones in a retrieval result. The agent reads them, acts, fails, and retries — burning the budget on every cycle. Teams that fixed this reported loop lengths dropping by more than half.
↑ back to top

11. Your first loop, this weekend

Build something small and real. A good starter project is a loop that keeps your own repository tidy:

  1. Pick a goal with a machine-checkable answer. "All tests pass and lint is clean" is perfect. "Make the code nicer" is not a goal, it is a mood.
  2. Write the success condition as one shell command that exits 0 or non-zero. That command is now your oracle. Do not let the agent grade itself.
  3. Write the three exits before the loop body. Turn cap 15. Token budget you are comfortable losing. No-progress window of 3.
  4. Log every turn to a file — turn number, action taken, tokens, pass or fail. You will learn more from this file than from the agent's output.
  5. Run it and watch where it goes wrong. It will. Note which of the six failure modes you hit; that tells you which component is missing.
  6. Add compaction only after you have felt the cost. Compare tokens on turn 1 against turn 10. The compounding becomes very concrete when it is your own bill.

Every principle in this article shows up at that scale, cheaply. You will discover by turn four that "looks done" is not a stop condition, and by turn nine why compaction exists.

↑ back to top

12. Glossary

Loop
The cycle an agent runs: decide, act, observe, verify, repeat — until an exit trips.
Turn / iteration
One pass through the loop, usually one model call plus its tool calls.
Harness
The whole system around the model that runs the loop: tools, sandbox, retries, logging, limits.
ReAct
Reason + Act. Interleaves a thinking step with an action step so each move is informed by the last result.
Reflexion
Writing a natural-language post-mortem after a failure and carrying it into the next attempt.
Stop condition
Any rule that ends the loop. You need three families: success, failure and budget.
Circuit breaker
A hard pre-flight limit on turns or tokens that refuses the next call rather than reporting the overspend afterwards.
Compaction
Summarising prior turns so the context carries the lesson without the full transcript.
Doom loop
An agent repeating a failing action indefinitely because nothing measures progress.
Progress signal
Any measurable improvement between turns — fewer failures, smaller diff, a changed error.
Verifier / oracle
Something outside the agent that says pass or fail. Usually a test suite, schema or exit code.
Ledger
An append-only record of every turn, used to explain what a loop did after the fact.

Frequently asked questions

What is loop engineering, in one paragraph?
Designing the cycle that drives an AI agent, instead of typing prompts one at a time. You give the agent a goal, tools, a way to check its own work against outside evidence, and a set of stop conditions — then let it act, observe and act again until it is done or a limit trips. The shift is that a system prompts the agent rather than a person, which is what turns an assistant into an automation.
Do I need a framework like LangGraph or Temporal?
Not to learn this, and often not to ship it. A for loop with a turn cap, a token counter, an external verifier and a log file contains every idea in this tutorial. Reach for orchestration frameworks when you need durable state across restarts, human approval steps, or fan-out across many agents — not before. Frameworks make the loop easier to run; they do not make an undefined goal checkable.
How many turns should I allow?
Start around 15–25 for a focused task, with a per-action retry limit of 2–3 and a no-progress window of 3 turns. Then look at your logs: if successful runs finish in 6 turns and failures run to the cap, your cap is doing its job. If successes routinely hit the cap, the task is under-scoped rather than the cap being too low.
Can the agent decide when it is done?
It can propose it; it should not be believed. Models signalling completion is a useful hint, not evidence, and an agent under budget pressure becomes measurably more willing to declare victory. Pair any self-reported completion with an external check. If you cannot build that external check, that is the strongest signal that the task is not ready to be automated.
How is this different from a normal cron job or workflow engine?
A workflow engine executes a fixed sequence you wrote. A loop decides its next action from what just happened, which is what lets it handle work you could not fully specify in advance. That flexibility is exactly why it needs stop conditions: a workflow cannot run away, and a loop can. If your steps genuinely are fixed, use the workflow engine — it is cheaper and more predictable.
How do I know my loop is actually good?
Measure four things across real runs: success rate against the external verifier, median turns to success, tokens per successful outcome, and how often a human had to intervene. The last one matters most. A loop with a 95% success rate that needs a human to inspect every run has not saved anyone any time.

Where this leaves you

This is the quiet shift from using AI to engineering with it. The model is the smallest part of the picture — as we covered in why the model is the smallest part of an AI agent, the harness runs the loop, not the model. Loop engineering is how you make that loop converge instead of wander, and its two hardest requirements are unglamorous: a goal a machine can check, and the discipline to write the exits before the body.

If you are building an agent that has to run against a goal rather than a single prompt — a coding agent, a research agent, an automation that works unattended — loop design is where its reliability comes from. That is exactly the kind of system we build and harden for production.

Talk to us about your AI project

← Graph engineering explained simply: the tutorial for anyone who already knows RAGThe agent harness: why the model is the smallest part of an AI agent →