Blog
My agents kept looping forever, so I gave them curfews
- AI agents
- Architecture
- Engineering
An agent loop is the most boring exciting idea in our industry. The agent looks at the current state, decides what to do, does it, looks at what happened, and repeats until it is done or something stops it. The Atlan loop guide calls it a perceive plan act cycle and I have not found a shorter true version. The loop part takes an afternoon to build. Everything around the loop is the actual job.
I learned this the way everyone learns it, by watching a demo agent turn into a billing incident. A slow tool, a confusing input, a model that retries instead of asking. The loop did exactly what I told it to do, which was the problem. This post is what I do differently now.
Key takeaways
- If you can write the steps down, use a graph. If you genuinely cannot, use a loop. Most systems need one loop surrounded by fixed steps.
- ReAct explores, plan and execute audits, reflection catches errors. I usually compose two of the three instead of picking sides.
- Every loop gets max steps, max tokens, and max wall time. A loop without caps is not autonomous, it is just unsupervised spending.
- Log task id, tool result, retry reason, and a final success flag, or you can never tell a loop from progress.
- Judge the end state, not the transcript. A beautiful trace that wrote the wrong row is still wrong.
The loop is three parts and a curfew
Strip away the framework marketing and every agent I run has the same three pieces. A planner that decides the next move, an executor that calls tools, and a reflector that checks whether the result is any good. Plan, execute, reflect, replan. The Callsphere pattern guide describes this as the spine of every reliable production agent in 2026, and my experience matches, with one addition they also make: explicit budget caps on everything.
Around that spine there are four shapes I keep seeing, named well in the Noqta loop engineering guide. Heartbeat loops that watch things continuously, cron loops on a schedule, hook loops that fire on events, and goal loops that chase open targets. Most of the horror stories I hear are someone running a goal loop with the discipline of a cron loop. None. No caps, no checks, just vibes and a credit card.
The decision rule I stole from the Simi Studio pattern note and now repeat to founders: if the steps can be written down, pick a graph. If they cannot, pick a loop. A refund flow is a graph. Debugging a failed deploy at 2am is a loop. Anyone selling you full autonomy for the refund flow is selling you latency and cost for no reason.
Three patterns that cover almost everything
ReAct is the original and still the one I reach for when I do not know the shape of the work. Think, act, observe, repeat, one reasoning step per action, straight out of the Yao et al paper from 2022. It is flexible and great for troubleshooting or research, and it is the hardest to audit because nobody wrote down the plan, because there was no plan. I keep it where the step count is unknown and tool output is the ground truth.
Plan and execute is the responsible sibling. The model writes a plan once, runs it, and only replans when an observation breaks the plan. Cheaper, easier to audit, easier to show a customer who asks what the agent is doing. I use it for anything that decomposes into three to eight known substeps, which turns out to be most business work.
Reflection is the one people underrate. A second pass checks the output against criteria before anything ships, and the self critique style costs one or two extra model calls per iteration for real accuracy gains. I insist on it anywhere a wrong answer beats a slow one on damage: customer facing text, money movement, anything that writes to somebody else's system. Production systems end up as compositions. Plan around the outside, ReAct inside the uncertain step, reflect at the end. The Dataknobs roundup lists six shapes and my advice is to pick two, not six.
The failure modes are the design, honestly
Every loop I have operated fails the same ways, so I now design against the list instead of discovering it each time. Tool calls that error and retry forever. A planner that rewrites the plan instead of finishing the work. A reflector with no authority, so it suggests and the executor ignores it. Context that grows until the model forgets what the goal was. None of this is exotic. All of it bills by the token.
The fixes are boring and I mean that as praise. Idempotency keys on writes. A retry budget per tool, not per run. A reflector whose verdict can actually stop the run. Compaction or a fresh context window past a threshold. And a final state check that is a database query, not a vibe. I describe that check in evals that check the end state because the loop post would double in size otherwise.
My rule for juniors is one sentence: a loop that cannot say what finished is not an agent, it is a script that spends money. Name what must be true at the end and what must not have happened, then enforce it in code, not in the prompt. Prompts negotiate. Code decides.
Curfews: the caps that let me sleep
Every goal loop I ship gets three numbers: max steps, max tokens, max wall time. Per task type, written down, generous at first and tightened after a few weeks of real runs. The Callsphere guide calls plan execute reflect replan with explicit caps the 2026 production sweet spot, and I am not going to argue with the only sweet spot that ever let me sleep through the night.
I run two levels because I stole the idea from monitoring and it works. The soft cap logs a warning with the task id and lets the run continue, and I read those warnings weekly because they point at confusing inputs and slow tools. The hard cap stops the run, saves state, and marks it failed. No automatic retry. A run that needed several times the usual budget will need it again, and a person should look first.
This is the loop half of cost per successful task. When the weekly drift alert fires, the five most expensive task ids go into the alert itself so whoever picks it up opens those traces first. If the drift started right after a prompt change, I roll the prompt back first and investigate second. Every single time, the prompt did it.
My take: graphs where possible, loops where necessary
Teams reach for full autonomy first and I push the other way, every time. Fixed pipelines where latency and cost must be predictable. A router in front when one agent holds too many tools, because past eight or ten tools a single model chooses badly and slowly. A loop only around the step that is genuinely unknown. Deterministic shell, agentic core: a fixed workflow where one or two steps are allowed to think.
It is the cheapest way to get reliability and the easiest thing to explain to a customer, and those two facts are related. Autonomy is a budget you spend, not a default you keep. Each step up in autonomy gets its own caps and its own success check, which is how loops finish instead of just stopping when the money runs out.
If you are starting from zero, here is my order. Plan and execute plus a reflector. Add ReAct inside the step that needs it. Add subagents when one context window stops being enough. And read the why agents fail post for the organizational half, because half of all loop incidents are really scope incidents wearing a trench coat.
Use cases: where each pattern runs in my systems
Patterns are easier to pick when you see them on real work. Here is where each shape shows up in systems I have written about on this blog. Most of them are not loops at all, and that is the point.
- A fixed pipeline: sending in our outreach tool. A worker claims a message, sends it once with an idempotency key, and the send log accepts exactly one entry per message. Nothing in it thinks, so nothing in it can wander. The details are in a message must never go out twice.
- Plan and execute with a human gate: invoicing from chat. One sentence from me becomes a known chain: find the customer, create the invoice, preview it, send on my confirmation. The steps never change, only the inputs. That is the QuickBilling MCP setup.
- A hook loop: the expense logger in my personal brain. It runs when I send a receipt, files it, and is done. One receipt never needs a long think. See my personal AI brain.
- A cron loop: the company brain's journal. A digest skill writes the daily, weekly and monthly journal from what changed. It is described in part 6 of the company brain series.
- A fixed shell with a thinking core: creative reports. The report builder runs a fixed sequence with one or two agentic steps inside, under caps and a success check that can stop the run. A judge model grades the briefs, and a second model or a human sample checks the judge. That is in creative reports that hold up.
Use cases: how you could use the same patterns
You do not need my systems to use these shapes. Here are five common jobs, the pattern I would pick for each, and the cap that matters most.
- Support inbox triage, a hook loop. Each new email fires one run: classify it, pull the order or account, draft a reply, stop. It is a graph with one thinking step in the middle. The cap that matters is steps, because a confusing email should go to a person, not into a long debate with itself.
- Weekly market or competitor research, a goal loop. ReAct inside, because you do not know which pages will matter. Hard caps on wall time and tokens, a fixed report format at the end, and a reflector that rejects any claim without a source.
- Chasing unpaid invoices, a cron loop. Once a week: list what is overdue, draft a polite reminder per customer, and queue the drafts for your approval. Nothing sends itself. The cap that matters is the approval gate, not the tokens.
- Debugging a failed deploy, ReAct. The steps are unknown until you read the logs, so let it explore. Cap the wall time, and when the cap hits, have it hand over its notes and best guess instead of trying one more thing.
- Onboarding a new client, plan and execute. The substeps are known: create the folder, send the welcome mail, book the kickoff, add the client to billing. Write the plan once, run it every time, and replan only when a step fails.
Try it this week: give one agent its curfew
Pick one agent you already run, or one you are about to build. Do not change the model or the framework. Write down which steps are fixed and which step needs to think, then set the three caps and the one check that proves the run finished. If you have recent runs, paste their step counts, tokens and times, so the caps start from real numbers and not guesses.
Goal: design the caps and the finish check for the agent described below.
Inputs: what the agent does, the tools it calls, and the step count, tokens and wall time of recent runs if I pasted them.
Constraints: do not suggest a new framework or a bigger model. Mark each step as fixed or thinking. If a number you need is missing, ask me instead of guessing.
Definition of done: a list of steps marked fixed or thinking, a soft and a hard cap for steps, tokens and wall time, the one check on the end state that proves the run finished, and what happens when the hard cap hits.Frequently asked questions
ReAct or plan and execute?
Unknown steps and exploratory work: ReAct. Known substeps and auditability: plan and execute. Most real systems use both, a plan around the outside and ReAct inside the uncertain step.
How many tools is too many for one loop?
Past eight to ten, split. Add a router or a supervisor with specialists. One model choosing between twenty tools chooses badly and slowly, and pays for the privilege.
What caps does every loop need?
Max steps, max tokens, and max wall time per run, plus a per tool retry budget. Soft cap warns, hard cap stops and marks failed. Read the warnings weekly or do not bother having them.
How do I test a loop at all?
Check the end state, not the transcript. Define what must exist and what must not have happened, run the loop, query the state. Same checks for every variant you compare, or the comparison is fiction.
Which agent pattern should I use for my use case?
Fixed steps you can write down: a pipeline or plan and execute. Events such as a new email: a hook loop. Scheduled work: a cron loop. Open questions such as research or debugging: ReAct with hard caps. Add reflection wherever a wrong answer costs more than a slow one.
Sources
- Yao et al: ReAct, Synergizing Reasoning and Acting in Language Models arxiv.org
- Atlan: The AI Agent Loop (2026) atlan.com
- Callsphere: Agent Loop Design Patterns (2026) callsphere.ai
- Simi Studio: AI Agent Architecture Patterns simi.studio
- Noqta: Loop Engineering (2026) noqta.tn
Talk to me
Building an AI product and need someone senior to own the technical side? Book a free 30-minute call.