Home › AI Skills 2027 › Loop Engineering
AI SKILLS 2027 · 02 OF 10

Loop Engineering

An agent is not one clever answer. It is a loop: decide, act, look at what happened, decide again. Whether that loop finishes the job, stops too early or runs all night is a design decision. Usually someone forgot to make it.

By Nimit Solanki, CTO of estaie14 min, interactiveBeginner friendly

Definition: Loop engineering is the work of designing the cycle an AI agent repeats (choose a step, act, observe the result, check progress) including how it plans, recovers from errors, and decides when it is done, stuck or out of budget.

1 The big idea

An agent is a loop, not an answer

Ask a chatbot a question and it answers once. An agent is different. It is given a goal, and it works towards it in small steps. Each step goes round the same cycle: the model reads what it knows so far and picks one action, the software around it runs that action, and the result is added to what the model knows. Then the model picks again.

This cycle is often called think, act, observe. A well-known research pattern called ReAct (short for "reason and act") made it popular: the model writes a short line of reasoning, asks for an action, sees the result, and repeats. Most agent frameworks today run some version of it.

Think→Act→Observe↻

Running the loop is easy. A few lines of code will do it. Loop engineering is everything that makes it finish well: a clear finish line, a check that the finish line was really reached, sensible retries, a way to change plan, and firm rules for when to stop.

Think of a satnav. It doesn't plan your route once and then go quiet. After every turn it checks where you really are. Miss a turn and it says "recalculating" instead of insisting you are on track. And it announces "you have arrived" because of where the car is, not because you have been driving for twenty minutes. A good agent loop works the same way.

2 Interactive map

The eight parts of a good agent loop

Click any part to see what it does, an example, and what goes wrong without it. Then switch to One shot to see what you get with no loop at all.

TRY IT
Goal & done Plan Next step Observe Progress check Recover Budgets Stop & hand off

A checkable definition of done

States the goal and, just as important, a test the software can run to see whether the goal has really been reached.

Read all 8 parts as text
A checkable definition of done
States the goal and, just as important, a test the software can run to see whether the goal has really been reached. Example: "Send door codes to every guest checking in tomorrow" is done when a query for tomorrow's guests without codes returns zero. Not when the model says so. Without it: The loop stops when the model feels finished, which can be after the first three guests out of ten.
Plan, or step by step
Decides whether the agent writes a short plan first and works through it, or chooses each step as it goes. Many good agents do a bit of both. Example: Extending a guest's stay: check availability, work out the price, hold the dates, confirm with the guest. Four steps, written down before starting. Without it: On long tasks the agent wanders, repeats work, and nobody can see how far through it is.
One step at a time
The model picks exactly one action per turn: a tool call, a question to the user, or "finish". Small steps are easier to check and easier to undo. Example: First turn: look up tomorrow's check-ins. Second turn: send codes to the first guest. Not "do everything at once" in one giant request. Without it: The model tries to do the whole job in one go, and one mistake ruins everything after it.
Observe the real result
Feeds the result of each action back to the model, including errors, empty results and "there are more pages". The model only learns what you show it. Example: The booking system returns 3 guests and "has_more: true". The loop shows both, so the model knows there are more to fetch. Without it: The model works from what it hoped would happen instead of what did happen.
Progress check
After each turn, asks a simple question in code: are we closer to done than last time? New facts, fewer items left, a test that now passes. Example: A lead-research agent has searched five times. The last three found nothing new about the company. That is not progress. Without it: The agent keeps busy without getting anywhere, and every busy turn costs money.
Retry and recover
Handles failures sensibly: wait and retry when a system is briefly down, try a different approach when an idea is wrong, and never repeat the exact same failing call forever. Example: The channel manager times out. Wait 2 seconds, retry. Times out again: wait 4 seconds, retry. Third failure: stop and report. Without it: The agent gives up at the first hiccup, or hammers a struggling system with instant retries.
Budgets
Sets hard limits for each task: number of turns, time, tokens and money. Limits are enforced by the loop, not suggested in the prompt. Example: Rate updates for one building: at most 20 turns, 3 minutes and a small fixed amount of model spend. Whichever runs out first ends the task. Without it: One confused task can run for hours and quietly use up a month of budget.
Stop and hand off
Defines every way the loop can end (done, stuck, out of budget, needs a decision) and what happens next in each case, usually a short summary to a person. Example: "Stopped after 3 searches with no new information. Best contact found: head of operations. Not confirmed." Sent to the sales team. Without it: The loop just ends. Nobody knows whether the work was finished, half done or never started.

Only one of these parts, Next step, is the model's job. The other seven are decisions you make in the software around it.

3 Step-by-step simulator

Watch the loop go round

Four tasks at a holiday-rental company. Each one goes round the same loop. Watch where the loop catches a problem, and what would have happened if it hadn't.

SIMULATOR
  1. Goaluser
  2. Thinkmodel
  3. Actharness
  4. Observeharness
  5. Check progressharness
  6. Continue or stopharness
Ready

Recovers from an error

A pricing agent updates rates. One update is rejected. A good loop treats the error as information, not as the end.

Read the walkthrough as text

Recovers from an error

A pricing agent updates rates. One update is rejected. A good loop treats the error as information, not as the end.

  1. A goal with a finish line. The revenue manager sets the goal. The loop also gets a test for done: all 12 flats show a new weekend rate that is either 8% higher or exactly at the cap. Why it matters: Writing the done test first is the single most useful thing you can do for a loop.
  2. The model picks one step. It doesn't try to change everything at once. It asks for the current rates and caps first.
  3. Observe the result. The rates and caps come back and are added to what the model can see.
  4. Act: update the rates. The model proposes the new rates for all 12. The loop runs the update.
  5. An error comes back. Flat M-07 was rejected: 8% would take it to AED 972, above its cap of AED 950. The loop passes the exact error back to the model in plain words. Why it matters: A vague "update failed" leaves the model guessing. A specific error lets it fix the problem on the next turn.
  6. Think again, with the new fact. The goal says "never above the cap", so the right fix is to set M-07 to exactly its cap.
  7. Check progress against the done test. The model is ready to finish. The loop runs the done test itself: it reads all 12 rates back from the system.
  8. Stop: really done. The loop stops because the test passed, not because the model said so. The revenue manager gets a short summary, including the one flat that hit its cap.

Stops too early

A guest-support agent sends door codes. The first page of results looks like the whole list. Without a done test, the job stops a third of the way through.

  1. The goal. Every guest arriving tomorrow needs their door code by 6 pm. Done means: zero guests arriving tomorrow without a code.
  2. Find the guests. The model asks for tomorrow's arrivals who have no code yet.
  3. Only the first page comes back. The booking system returns 3 guests and a note that more results exist. Easy to miss.
  4. Send three codes. The model sends codes to the three guests it can see. Each send succeeds.
  5. The model says it is finished. It reports: "All guests arriving tomorrow now have their codes." It believes it. It only ever saw three. Why it matters: Models are not lying when they stop early. They report on what they saw. The loop has to check the world.
  6. The done test fails. The loop runs the done test instead of trusting the claim. Seven guests still have no code. It tells the model exactly that, and the loop continues.
  7. Fetch the rest and finish the job. The model runs the same search again. Now it returns only the seven guests still without a code, and the model sends them.
  8. Stop: done test passes. Zero guests without a code. Now the loop stops. Without the test, seven guests would have been standing at a locked door.

Never stops

A sales-lead agent researches a company. There is always one more search it could run. Without a progress check, it never decides it has enough.

  1. An open-ended goal. Research tasks have no natural end. So the loop gets two limits: 12 turns, and stop after 3 turns with no new facts.
  2. A sensible first search. The model searches the company's public pages for its leadership team.
  3. Progress: yes. New facts appeared, so the progress counter resets.
  4. More searches, less to show. The model keeps going: searching for the name with different words, then news articles, then old press releases. Each search returns the same people.
  5. No progress for three turns. Each search was slightly different, so a simple "same call repeated" check would miss this. The progress check doesn't care about the wording. It sees three turns with no new facts. Why it matters: Agents rarely loop by repeating one call exactly. They loop by doing slightly different things that achieve nothing.
  6. Stop with the best answer so far. Stopping is not failing. The loop asks the model for its best answer from what it has, marks what is unconfirmed, and hands it to the sales team.

Plan changes

An agent writes a short plan, then works through it. Halfway through, a fact breaks the plan. A good loop notices and replans instead of pushing on.

  1. The guest asks. A guest currently staying wants two more nights.
  2. Write a short plan first. For multi-step tasks, a plan makes the work easy to follow and easy to check. The loop saves it and tracks which step is current.
  3. Step 1: check availability. The loop runs the availability check.
  4. The plan's assumption breaks. The first extra night is free. The second is already booked by another guest. Steps 2 to 4 no longer make sense as written.
  5. The loop asks for a new plan. The loop compares the result with what the plan expected. They don't match, so it asks the model to replan rather than carrying on with step 2. Why it matters: Following a plan after its key fact has changed is how agents confidently do the wrong thing.
  6. A better plan. New plan: offer one extra night in the same flat, or two nights in a similar flat in the same building.
  7. Stop and let the guest choose. The next decision belongs to the guest, so the loop stops, sends both options and waits. It does not pick for them.

The point: in every scenario the model made reasonable choices. What saved the task was the loop around it: a done test, specific errors, a progress check and a reason to replan. When an agent stops too early or never stops, look at the loop before the model.

4 Two ways to run the loop

Step by step, or plan first?

Step by step (reactive)

  • Picks each step after seeing the last result
  • Adapts quickly to surprises
  • Best for short tasks and conversations
  • Can wander on long tasks
  • Harder to predict how many steps it will take

Plan, then execute

  • Writes a short plan before acting
  • Easy for a person to read and approve
  • Best for long, multi-step jobs
  • Progress is visible: step 3 of 5
  • Must replan when a key fact changes
  • Can cost an extra model call up front

This is not either/or. A common pattern is to plan first, run each step reactively, and replan whenever a result doesn't match what the plan expected.

5 Build your own loop

Turn on loop parts. Watch the failures disappear.

These are the ways agent loops go wrong in real use. Tick the parts your loop has and see which failures you are protected from. A basic "call the model until it says finish" loop has none of them.

TRY IT
0/8failure types covered
  • Says "finished" after 3 of 10 guestsIt trusts the model's word.
  • Makes up an answer after a tool error it never sawErrors are swallowed.
  • Gives up the first time a system is slowOne timeout ends the task.
  • Hammers a struggling payment system with instant retriesNo waiting between tries.
  • Runs the same failing search all nightNothing notices the repeat.
  • Keeps "researching" without finding anything newBusy is mistaken for progress.
  • Books the original plan after the dates became unavailableThe plan is followed blindly.
  • Hits a limit and stops with half the rates changed, unnoticedThe loop just ends silently.
Read which part prevents which failure
  1. Says "finished" after 3 of 10 guests: prevented by Done test.
  2. Makes up an answer after a tool error it never saw: prevented by Errors fed back.
  3. Gives up the first time a system is slow: prevented by Retry with backoff.
  4. Hammers a struggling payment system with instant retries: prevented by Retry with backoff.
  5. Runs the same failing search all night: prevented by Repeat detection or Budgets.
  6. Keeps "researching" without finding anything new: prevented by Progress check or Budgets.
  7. Books the original plan after the dates became unavailable: prevented by Replanning.
  8. Hits a limit and stops with half the rates changed, unnoticed: prevented by Hand-off summary.

Notice that budgets cover two failures but fix neither: they stop the damage, they don't finish the job. A budget is a safety net. The progress check and the done test are what make the loop finish well.

6 Optional: what it looks like in code

A careful loop in 17 lines

You don't need to read code to follow this series. If you do, here is a loop with the parts from this page. The highlighted line is the one most loops leave out.

Python-style pseudocode
def run(goal, max_turns=15, max_cost=0.40):
    history = [goal]
    for turn in range(max_turns):             # hard turn limit
        if cost_so_far() > max_cost:
            break
        action = model.next_step(history)     # think: pick ONE step
        if action.type == "finish":
            remaining = check_done(goal)      # done is a test, not a claim
            if not remaining:
                return finish(action.reply)
            history.add("Not done yet: " + remaining)
            continue
        result = run_tool(action, retries=2, backoff=2)
        history.add(result)                   # observe: results AND errors
        if repeating(history) or no_progress(history, turns=3):
            break
    return hand_off(goal, summarise(history)) # stopped early: tell a person
check_done is the done test, run_tool retries with a growing wait, no_progress is the progress check, and hand_off makes sure every early stop reaches a person.

7 The rules I build by

Seven principles of a good agent loop

Write the done test first

Before you build the loop, write the check that proves the job is finished. If you can't write it, the task isn't clear enough for an agent yet.

Done is a test, not a claim

When the model says "finished", run the test. Models report on what they saw, and they often saw only part of the picture.

One step per turn

Small steps are easier to check, easier to undo and easier to debug. Big all-at-once actions hide mistakes.

Errors are information

"Rejected: 972 is above the cap of 950" lets the model fix it next turn. "Something went wrong" doesn't.

Measure progress, not activity

A busy agent is not a productive one. Track new facts, items left or tests passing, and stop when that number stops moving.

Every loop needs several exits

Done, stuck, out of budget and needs a decision. Each exit should end somewhere useful, usually with a short summary for a person.

Replan when the facts change

A plan is a guess made before you knew everything. When a result contradicts it, make a new one instead of pushing on.

8 Common mistakes

Things teams say about loops right before an incident

"The loop stops when the model says it's done."

That is the most common loop bug. The model can only judge from what it saw: a first page of results, a tool that silently failed, a test it didn't run. Stop on a check in code, and feed any failure back as the next turn.

"We'll set the step limit really high, just in case."

A high limit means a confused agent burns through a lot of turns before anyone notices. Set limits close to what a normal task needs, watch how often they are hit, and raise them only with evidence.

"If a call fails, just retry it."

Retrying helps when a system was briefly down. It does nothing when the request itself was wrong, and instant retries can make an outage worse. Retry with a growing wait, a small maximum, and only for errors that might pass. For anything that moves money or sends messages, make sure a retry can't do it twice.

"It's stuck, so let's give it more turns."

If an agent made no progress in its last three turns, ten more will usually look the same. Stop, summarise what was tried, and hand it to a person or change the approach.

"We don't need a plan, the model is smart."

For short tasks, that's fine. For long jobs, a written plan lets you see how far through the agent is, lets a person approve the approach, and makes it obvious when the plan needs to change.

9 Check yourself

Four quick questions

Question 1Your agent says "All 40 listings updated." What should the loop do next?

Question 2A research agent has run five slightly different searches. The last three found nothing new. What is the best rule to catch this?

Question 3A tool call fails with "price 972 is above cap 950". What should the loop do with that error?

Question 4Halfway through a plan, a key fact turns out to be different from what the plan assumed. What should a good loop do?

10 Do this today

Six steps to a better loop this week

Pick one agent you're building or running. Work down this list. Your ticks are saved in this browser.

11 Questions people ask

Loop engineering FAQ

What is an agent loop?

An agent loop is the cycle an AI agent repeats to complete a task: the model picks one action, the software runs it, the result is added to what the model can see, and the model picks again. It continues until the task is done, the agent is stuck, or a limit is reached.

What is ReAct in AI agents?

ReAct, short for "reason and act", is a well-known pattern where a model alternates between writing a short line of reasoning, requesting an action, and reading the result. Many agent frameworks use a version of this think, act, observe cycle as their basic loop.

How does an AI agent know when to stop?

A well-built agent does not rely on the model deciding it is finished. The loop runs a check in code, such as a query or a test, to confirm the goal was reached. It also stops when progress stalls, when the same action keeps failing, or when a turn, time or cost limit is hit, and hands a summary to a person.

What is the difference between plan-and-execute and ReAct?

A ReAct-style agent picks each step after seeing the last result, which adapts well to surprises. A plan-and-execute agent writes a plan first and then works through it, which is easier to review and track on long tasks. Many production agents combine them: plan first, act step by step, and replan when a result contradicts the plan.

Why do AI agents get stuck in loops?

Usually because nothing in the software checks for progress. The model retries a dead end with small variations, or keeps gathering information without deciding it has enough. A progress check, repeat detection and firm budgets stop this, and a hand-off summary makes sure a person picks it up.

How many steps should an agent loop be allowed?

There is no universal number. Measure how many turns your normal tasks take, set the limit a little above that, and watch how often it is hit. Hitting the limit often is a sign of a loop problem to fix, not a reason to raise the limit.

12 Glossary

Words you'll hear

Agent loop
The repeated cycle of choosing a step, acting, observing the result and checking progress.
Turn
One trip round the loop: one model decision and the action that follows.
ReAct
A common pattern where the model alternates short reasoning with actions and reads each result.
Plan-and-execute
An approach where the agent writes a plan first, then carries it out step by step.
Done test
A check in code that proves the goal was reached, run instead of trusting the model.
Stop condition
Any rule that ends the loop: done, stuck, out of budget, or waiting for a decision.
Backoff
Waiting a little longer before each retry, so a struggling system has time to recover.
Progress check
A test after each turn of whether the agent is closer to done than before.
Loop detection
Spotting when the agent repeats the same action or gets the same result again and again.
Replanning
Making a new plan when a result shows the old plan's assumptions were wrong.

Finished this topic? Track your progress through all ten.

For teams

Want your team to build agent loops that finish the job?

I run AI agents in production at estaie that set prices, find customers and look after guests. This page comes from building and running them.

WORKSHOP

AI Skills 2027, for your engineering team

A hands-on workshop where your engineers design the loop, stop rules and recovery paths for a real agent from your business.

  • One skill in depth, or all ten as a bootcamp
  • On site in the UAE or remote
  • Your team leaves with working code, not slides
Enquire about a workshop
REVIEW

Have your agent's loop reviewed

I check how your agent decides it is done, retries, recovers and stops, and give you a written list of what to fix first, in order of risk.

  • For teams about to launch, or just after an incident
  • Plain-English findings your board can read
Ask about a review

The series

All ten AI Skills for 2027

  1. Harness Engineering
  2. Loop Engineering
  3. Context Engineering
  4. Tool Design
  5. Memory Architecture
  6. Orchestration Patterns
  7. Guardrails & Permissions
  8. Evals for Agents
  9. Human-in-the-loop Design
  10. Observability & Tracing

Published 2 December 2026. Written by Nimit Solanki from building production agents at estaie.

Get the free Playbook by email

Seven short lessons on taking an agent from prototype to production. One a day, free. You may also hear about my course and consulting. Opt out any time.

Your email is never shared.