Skip to main content
AI & Automation — updated 2026

What is Loop Engineering? The Complete 2026 Guide

Loop engineering is designing the repeatable cycle that drives an AI agent toward a goal — the trigger, the steps, the tools, the verification, and above all the conditions under which it stops. This guide covers where the term came from, how it sits above prompt and context engineering, and what separates a loop that survives production from one that burns money at three in the morning.

Short answer: loop engineering is designing the repeatable cycle that drives an AI agent toward a goal — the trigger, the steps, the tools it may use, how the result gets verified, and the conditions under which the run stops. Prompt engineering designs one message. Loop engineering designs the whole run.

Here is the version I learned the hard way. The first agent loop I put in front of real inputs worked beautifully in testing and then, on an input it had never seen, went around the same three steps over and over. It was not broken, exactly. It was doing precisely what I had told it: keep working until the goal is met. I had never told it what to do when the goal could not be met.

That is the whole discipline in one sentence. Everyone writing about loop engineering talks about planning, memory and tools. The part that decides whether your loop is a product or an incident is the far less glamorous question: when does it stop, and how does it know?

In one line: a loop without a halt condition is not an agent, it is a `while true` with an API bill attached.

What loop engineering actually is

Loop engineering is the practice of designing agentic workflows — loops — that repeatedly guide an AI model toward a defined goal with minimal human intervention. Instead of you prompting, reading, correcting and prompting again, you build the system that does that cycle on its own, and you decide where it is allowed to act and where it must stop and ask.

Three definitions are worth quoting directly, because they come at it from different angles and together they cover the idea:

"Loop engineering is the practice of designing agentic workflows, or loops, that iteratively guide AI agents toward completing user-defined goals with minimal human intervention."

— IBM Think

"Loop engineering is replacing yourself as the person who prompts the agent. You design the system that does it instead."

— Addy Osmani, O'Reilly Radar, June 2026

Designing repeatable cycles that let an agent build, test, revise and keep going with less direct intervention.

— Andrew Ng's framing, paraphrased

Notice what all three have in common: the shift is in who runs the cycle. In 2024 you were the loop — you read the output, judged it, and fed the next instruction. In 2026 the loop is a thing you build, and your job moves up a level to designing it, bounding it and watching it.

Where the term came from

This matters more than the usual etymology section, because the term is genuinely new and most of what you will read about it was written in a three-month window.

How "loop engineering" went from a few posts to a named discipline, mid-2026.
WhenWhat happened
Early June 2026Posts from Boris Cherny (creator of Claude Code, at Anthropic) and Peter Steinberger about running coding agents in continuous cycles spread widely; Steinberger's reached millions of views within days.
22 June 2026Addy Osmani, an engineering lead at Google Chrome, published the article that gave the practice its name and its components. O'Reilly Radar republished it.
Late June – July 2026Andrew Ng framed it as three nested loops. IBM published a topic page with a formal definition and enterprise case studies.

Two practical consequences. First, anything written before mid-2026 that claims to explain loop engineering is describing something else, usually generic agent architecture. Second, the framing is specifically about coding agents, and that is not an accident — coding is the domain where verification is fast, cheap and automatic. Tests either pass or they do not. Most of what makes loops work in other domains is about recreating that property.

Osmani's five components

Osmani's list is worth learning as-is, because it is concrete rather than architectural:

  • Automations — scheduled discovery and triage that runs without being asked.
  • Worktrees — isolated parallel workspaces so concurrent runs do not collide.
  • Skills — documented project knowledge and conventions the agent reads before acting.
  • Plugins and connectors — the integration points that give the agent real tools, increasingly over MCP.
  • Subagents — separate agents for distinct roles, especially the one that reviews the work.

He adds a sixth that I would argue is the most important: persistent external state, usually a markdown file or a task tracker. Models have no continuity between runs. If the loop is going to remember anything, you have to store it somewhere you control.

Ng's three nested loops

The other framing worth carrying around: the agentic coding loop runs in minutes, the developer feedback loop in hours, and the external feedback loop — real users, real outcomes — in days or weeks. Speeding up the innermost loop feels like progress but is capped by the two outer ones. I have watched teams make the inner loop ten times faster and ship nothing sooner, because the review step never moved.

The four-layer stack: prompt, context, harness, loop

The fastest way to understand loop engineering is to see what it is not. Four related disciplines get confused constantly, and they sit at different levels of granularity.

Each layer owns a different unit of work.
LayerUnit of workWhat it controlsEmerged
Prompt engineeringOne messageWording, format, examples, role2022–2024
Context engineeringOne model callRetrieval, project memory, history pruning2025
Harness engineeringThe environmentTools, sandbox, retries, hooks, loggingEarly 2026
Loop engineeringThe whole runTrigger, goal, verification, halt condition, state2026
The four layers of working with AI models Four stacked bars. From the bottom: prompt engineering governs one message, context engineering governs one model call, harness engineering governs the execution environment, and loop engineering, at the top, governs the whole run including the halt condition. Prompt engineering one message Context engineering one model call Harness engineering the environment Loop engineering the whole run wider scope ↑
Each layer contains the ones below it. A loop is only as good as the harness it runs in, and the harness only as good as the context each call receives.
Key takeawayThese are not competing skills and none of them replaced another. You still write prompts inside a loop. What changed is that the prompt stopped being the unit you optimise, because a loop that runs fifty times is not made good by one beautiful sentence.

Loop engineering versus prompt engineering

The clearest way to see the difference is to look at what fails and who notices.

Same models, different discipline.
DimensionPrompt engineeringLoop engineering
ScopeOne interactionA complete run, many steps
Human involvementEvery stepThe trigger and the exceptions
ToolsThe model aloneModel plus APIs, databases, code execution
OutputA response you judgeA finished task, or an explained failure
When it failsYou see it immediatelyYou see it in the logs, tomorrow, at scale
Main riskA weak answerConfident wrong action, repeated automatically

That last row is the one to sit with. A bad prompt wastes thirty seconds. A bad loop does the wrong thing a thousand times before anyone checks, which is why so much of this article is about brakes rather than engines. If you are not solid on the layer below, start with the prompt engineering guide first — a loop multiplies whatever your prompt does, including its mistakes.

Anatomy of a loop

Every working loop I have built has the same six parts, whatever the framework.

1. Trigger

What starts the run: a message, a schedule, a webhook, a row appearing in a table.

2. Perceive

Read the input and the carried-over state. What is being asked, and what happened last time?

3. Plan

The model picks the next action from the tools available. One step, not a twelve-step plan it cannot revise.

4. Act

Execute the tool call. Queries, API writes, file operations, messages.

5. Verify

Check the result against something outside the model. This is the gate, and it is usually missing.

6. Halt or continue

Loop again, finish, or stop and report why. Never only the first two.

A detail that sounds small and is not: plan one step at a time. Asking a model for a complete plan up front produces a document that reads well and survives contact with reality for about two steps. Planning the next action with the results of the previous one in hand is the actual insight behind ReAct, the 2022 paper that nearly every modern agent loop descends from.

Halt conditions: the part everyone skips

A halt condition is the rule that ends a run. It is the single most important thing you design, and in most tutorials it gets one line at the end.

The reason is simple: success is not a reliable exit. An agent that can finish will finish. An agent that cannot finish, for any reason you did not anticipate, will keep going — and the more capable the model, the more inventive its attempts and the longer it stays plausible while getting nowhere.

A mature loop stops on a composite signal, not one condition:

Four independent brakes. Any one of them ends the run.
SignalCatchesTypical setting
Step capWandering, endless refinement6–12 steps for most business tasks
Time limitSlow tools, hung callsWhatever your user is willing to wait, minus a margin
Budget capExpensive spiralsA hard token or cost ceiling per run
Stall detectionThe same action repeating with no state changeThree identical actions in a row

Alongside halt conditions, two companion primitives deserve the same attention: state carryover — what survives between steps and between runs — and recovery paths — what happens after a halt. A loop that stops is fine. A loop that stops silently, having half-finished a database write, is a much worse problem than the one you were automating.

The rule I now apply without exception: write the halt condition before you write the loop body. If you cannot state what "give up" looks like, you do not understand the task well enough to automate it yet.

Why verification has to come from outside the model

The most common design I see — and one I used to write myself — is a reflection step where the model reviews its own output and scores it. It feels rigorous. It largely does not work.

Research on self-correction has found that language models frequently fail to reliably fix their own reasoning errors without external feedback, and in some settings the "corrected" answer is worse than the first one. The intuition is easy once you see it: the same process that produced the error is being asked to notice it. If the model knew the answer was wrong, it would not have written it.

What does work is verification with information the generating model does not have:

  • A test suite or a compiler — the reason coding agents got good first. The feedback is objective and free.
  • A schema or validator — does the JSON parse, are the required fields present, is the date real?
  • A database or API lookup — does this order number actually exist, is the price what the agent claimed?
  • A rule engine — hard business constraints the model is not allowed to negotiate with.
  • A second model with different inputs — genuinely useful, but only when it sees the source material and the criteria, not just the answer.
  • A human — on the small subset the other gates flagged, not on everything.

This is also the honest answer to "where can I use loops?" You can automate anything you can check. Where verification is slow, expensive or subjective, a loop mostly gives you a faster way to produce work nobody can approve. The Reflexion paper is worth reading here, but note what makes it work: the agent reflects on external feedback signals, not on its own opinion of itself.

Loop patterns that actually get used

Four shapes cover the overwhelming majority of business loops. Learn these before reaching for anything exotic.

Classify and route

Incoming request → classify the intent → hand off to the right handler → escalate if confidence is low. Boring, cheap, and probably the highest return on effort of anything on this list. Most support automation is this and nothing more.

Research and synthesise

A topic → several searches → read and extract → synthesise → check the claims against the sources → output. This is the loop behind most content and analysis tooling. The verification step is what separates a useful one from a plausible-sounding one.

Generate and verify

Draft → check against rules or tests → if it fails, feed the specific failure back and retry, up to N times → accept or escalate. Feeding back the specific failure is the whole trick; "try again" achieves nothing.

Monitor and alert

Poll a source on a schedule → compare against a threshold or a pattern → if the condition is met, judge whether it is worth reporting → alert the right person. I run a signal bot on this shape as a systemd service; the AI step is small and the value is almost entirely in the thresholds and the deduplication.

A note on ambition: the loops that earn their keep in real businesses are narrow. The one that classifies a message and looks up an order runs ten thousand times a month and never makes the news. The autonomous everything-agent demos beautifully and quietly gets switched off.

A minimal loop in code

Frameworks hide this, so it is worth seeing once in plain Python. Notice how much of it is brakes rather than intelligence — in a production loop, that ratio is normal.

import time

MAX_STEPS = 8
MAX_SECONDS = 120


def stalled(history, window=3):
    """Same action three times in a row means we are going nowhere."""
    recent = [h["action"] for h in history][-window:]
    return len(recent) == window and len(set(recent)) == 1


def run_loop(goal, tools, model, verify):
    state = {"goal": goal, "history": []}
    started = time.monotonic()

    for step in range(MAX_STEPS):
        if time.monotonic() - started > MAX_SECONDS:
            return {"status": "halted", "reason": "timeout", "state": state}

        action = model.decide(state)                     # plan one step

        if action.kind == "finish":
            ok, why = verify(action.result, goal)        # external check
            if ok:
                return {"status": "done", "result": action.result}
            state["history"].append({"action": "rejected", "detail": why})
            continue                                     # retry with the reason

        result = tools[action.name](**action.args)       # act
        state["history"].append({"action": action.name, "result": result})

        if stalled(state["history"]):
            return {"status": "halted", "reason": "stall", "state": state}

    return {"status": "halted", "reason": "step_cap", "state": state}

Three things in there are the difference between a demo and a system: the loop returns why it stopped, a rejected result is retried with the specific reason attached, and every exit path returns state you can inspect afterwards. If you are building this tooling yourself it will almost certainly be Python — here is why Python became the default language of AI work.

Tools in 2026

My honest advice: start with the smallest thing that works, and let the pain tell you when to upgrade.

A plain script

Three model calls in sequence with a for-loop and a cap. Genuinely enough for a surprising number of real tasks, and you can read the whole thing.

n8n / Make

Visual automation with AI nodes. Good when the loop is mostly integration and the branching is simple. I run a self-hosted n8n stack talking to a local Ollama model for exactly this.

LangGraph

Worth it when you need real branching, persistent state across runs and resumable execution. The graph model fits how loops actually behave.

CrewAI / multi-agent frameworks

Role-based agents collaborating. Powerful, and the easiest way to build something impressive that you cannot debug. See the next section.

Underneath all of them sit the model APIs and the tool-calling capability that makes agents possible at all, increasingly exposed through MCP so a tool written once can serve several agents. Anthropic's Building Effective Agents is still the most level-headed thing written on choosing between these, and its core advice has aged well: use the simplest pattern that solves the problem, and only add agency where you need it.

One research finding worth knowing when you pick tools: Princeton's SWE-agent work showed that the same underlying model performs dramatically differently depending on how its interface to the environment is designed. The harness is not plumbing. It is a large part of the result.

One agent or many?

This is a live argument, not a settled question, and anyone telling you otherwise is selling a framework.

The multi-agent case: split the work by role — a researcher, a writer, a critic — and each one stays focused, with a smaller context and a clearer job.

The single-agent case, which has gained considerable ground through 2026: every handoff between agents is a place where context gets dropped, and the failures that result are extremely hard to trace. The position associated with Walden Yan at Cognition is that a single-threaded linear agent with compacted context should be the production default, and that reaching for multiple agents is usually premature optimisation.

My own rule, from building both: use multiple agents when the subtasks are genuinely independent and each has its own verification. Use one when the work is a chain where each step depends on the last — which is most work. The moment you find yourself writing a protocol so two agents can agree on what happened, you have rebuilt distributed systems without the tooling.

Common failure modes

IBM names four debts that agentic development accumulates, and they are uncomfortably recognisable:

  • Unverified code — output that shipped because it looked right and nothing checked it.
  • Comprehension debt — a working system nobody on the team can explain.
  • Intent debt — the loop does something subtly different from what was wanted, and the gap widens with each iteration.
  • Cognitive surrender — the team stops evaluating the output and starts approving it.

To which I would add three of my own, from loops I have had to fix:

No exit but success

Already covered, and still the most expensive one. Write the halt condition first.

Retry storms

A tool fails, the loop retries, the retry fails, and now you are hammering an API that is down and paying for every attempt. Retries need backoff and a cap, same as any other distributed system.

No observability

If you cannot see every step, every tool call and every halt reason, you are not debugging, you are guessing. I put a logging proxy in front of my local model server precisely so that every call lands in a database I can query later. Loops fail in ways you will never reproduce by hand.

Key takeawayNearly every loop failure is an operations problem wearing an AI costume: no limits, no retries with backoff, no logging, no defined failure path. The model is rarely the weakest component.

How to become a loop engineer

  1. Get reliable at single prompts first. A loop multiplies whatever your prompt does. If one call is unreliable, ten in sequence are unusable.
  2. Learn tool calling properly. Build three real tools — a search, a database query, an API write — and handle the failure path of each. That path is where loops actually break.
  3. Ship a three-step loop with a hard halt condition. Input, decision, action, output, plus a step cap and a timeout from version one. Something small and real beats a tutorial.
  4. Add external verification and escalation. Decide what "wrong" means mechanically, and what happens when the check fails. Define when a human gets called.
  5. Add observability, then run it on real traffic. Log every step and every halt reason. The distribution of halt reasons is the most useful backlog you will ever have.

Expect the gap between understanding this and shipping it to be wider than it looks. That gap is almost entirely operational, and it closes with practice rather than reading.

Want a loop that actually runs in your business?

Filtori builds Bale and Telegram bots, websites and AI automation — including the parts that do not demo well: halt conditions, verification gates, escalation paths, logging and the guardrails that keep an automated system from confidently doing the wrong thing.

Soroush Moghaddami
Written by

Software engineer since 2012, working in Python, Java and Oracle, and head of the database department at a national mobile operator. He founded Filtori, where he builds bots, agent loops and AI automation for businesses. The loops described here come from systems he runs himself, including a self-hosted n8n stack, a local model server behind a logging proxy, and a trading signal bot running as a service.

· LinkedIn


Glossary

Loop engineering
Designing the repeatable cycle that drives an AI agent toward a goal: the trigger, the steps, the tools, the verification and the conditions under which it stops.
Halt condition
The rule that ends a run. A mature loop uses a composite signal: a step cap, a time limit, a budget cap and stall detection, not just success.
Harness engineering
Designing the environment the agent runs inside: the tools it can call, the sandbox, retries, hooks and logs. The layer directly beneath the loop.
Context engineering
Deciding what goes into a single model call: retrieved documents, project memory, pruned history. It governs one call, where loop engineering governs the whole run.
Tool calling
The mechanism that lets a model invoke a function you defined — a search, a query, an API write — and receive the result as part of the conversation.
ReAct
A pattern from a 2022 paper in which the model alternates between reasoning about what to do and acting through a tool. It is the ancestor of nearly every agent loop in use today.
Reflection
A step where the output is criticised and revised before it is accepted. It works when the critique comes from outside the model; self-grading alone is unreliable.
Stall detection
Noticing that the agent is repeating the same action without changing state, and ending the run instead of letting it spin.
State carryover
What the loop remembers between steps and between runs. Models have no continuity of their own, so persistent state has to be designed and stored somewhere you control.
MCP (Model Context Protocol)
An open protocol for connecting models to external tools and data sources through a common interface, so a tool written once can be used by different agents.

Frequently asked questions

What is loop engineering?
Loop engineering is the practice of designing the repeatable cycle that drives an AI agent toward a goal: the trigger, the steps, the tools it may use, how the result is verified, and the conditions under which the run stops. IBM defines it as designing agentic workflows that iteratively guide AI agents toward user-defined goals with minimal human intervention.
Where did the term loop engineering come from?
It emerged in June 2026 around AI coding agents. Posts from Boris Cherny and Peter Steinberger spread the idea, Addy Osmani gave it its name and shape in an article on 22 June 2026 that O'Reilly Radar republished, Andrew Ng framed it as three nested loops, and IBM published a topic page in July 2026. That is why almost nothing written before mid-2026 uses the term.
How is loop engineering different from prompt engineering?
Prompt engineering designs one message and gets one response. Loop engineering designs a whole run: several steps, real tools, a verification gate and an exit condition. The unit of work is different — one call versus one completed task — so the failure modes and the skills are different too.
What is a halt condition and why does it matter so much?
The halt condition is the rule that ends a run. It matters because success is not a reliable exit: an agent that cannot finish will keep trying. A mature loop stops on a composite signal — a step cap, a time limit, a budget cap and stall detection — and reports why it stopped.
Should the agent check its own work?
Not on its own. Research on self-correction found that models often fail to reliably fix their own reasoning errors without external feedback, and sometimes make answers worse. Verification should come from outside the model: a test suite, a schema validator, a database lookup, a rule engine, or a second system with different information.
Is loop engineering only for coding agents?
It started there, because coding has fast, cheap, automatic verification in the form of tests and compilers. The ideas transfer to any task where you can check the result — support triage, data enrichment, report generation, monitoring. Where verification is hard or subjective, loops are much weaker.
Do I need a framework like LangGraph, or is n8n enough?
Start with the smallest thing that works. A scripted sequence of three model calls is a loop, and for many business tasks n8n or a similar automation tool is enough. Reach for LangGraph or a comparable framework when you genuinely need branching, persistent state across runs and resumable execution.
Should I use multiple agents or one?
One, until one demonstrably fails. The position that has gained ground through 2026 is that a single-threaded agent with compacted context should be the production default, because multiple agents multiply the ways context gets lost between them. Multi-agent designs earn their keep when subtasks are genuinely independent and each has its own verification.
Can loop engineering be applied to Telegram or Bale bots?
Yes, and it is one of the most practical applications. A bot that classifies an incoming message, looks up the order, drafts a reply, checks it against business rules and escalates to a human when it is unsure is already a loop with a verification gate. The value is in the gate and the escalation path, not in the reply generation.

Sources

  1. IBM Think — What Is Loop Engineering? (definition, named failure modes and enterprise case studies). 2026
  2. Addy Osmani — Loop Engineering, O'Reilly Radar. June 22, 2026
  3. Adaline Labs — What Is Loop Engineering, and Who Owns It? (halt conditions, state carryover, recovery paths). 2026
  4. Yao, S. et al. — ReAct: Synergizing Reasoning and Acting in Language Models. October 2022
  5. Shinn, N. et al. — Reflexion: Language Agents with Verbal Reinforcement Learning. March 2023
  6. Huang, J. et al. — Large Language Models Cannot Self-Correct Reasoning Yet. October 2023
  7. Yang, J. et al. — SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering, Princeton. May 2024
  8. Anthropic — Building Effective Agents. December 2024
  9. METR — Measuring AI Ability to Complete Long Tasks. March 2025
  10. Production examples and failure modes: the author's own agent loops and automation systems at Filtori, 2024–2026.