Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
The loop that
makes an agent.
A model that only talks is a chatbot. Put it in a loop — let it act, see the result, and decide again — and it becomes an agent that gets things done. That loop is the harness, and most of what separates a reliable agent from a runaway one lives there, not in the model. The single most important line of code you'll write isn't the clever prompt; it's the stop condition. Without a hard bound, a stuck agent doesn't fail — it loops forever, quietly spending money. This handbook is about building the loop, and building the brakes.
Talk becomes action
An LLM by itself produces text. To make it do things — search, run code, edit files, call APIs — you wrap it in a program that reads its output, executes the action it asked for, and feeds the result back so it can decide what to do next. That wrapper is the agent harness, and the repeated cycle it runs is what turns a language model into an autonomous system.
The important shift in mindset is that the harness, not the model, is the system you're engineering. The model is one component inside a loop you control — you own the prompt assembly, the tool dispatch, the result parsing, the error handling, and the termination logic. A brilliant model in a sloppy harness is an unreliable agent; a modest model in a well-built harness can be a dependable one. And the part of the harness that matters most for safety and cost is the one people skip: the stop condition.
An agent is a model in a plan-act-observe loop; the harness owns that loop, and its most important job is a hard bound — max steps and a cost budget — so a stuck agent can never run forever.
Plan, act, observe
The core of every agent is one cycle, popularized by ReAct: plan → act → observe. The model reasons about the goal and picks an action (usually a tool call). The harness executes it — runs the tool, calls the API, edits the file. The result is fed back into the model's context. Then the loop repeats, the model choosing its next action from what it just observed, until it signals the task is complete.
What makes this powerful is the observe step: the model's next plan is grounded in the real result of its last action, not in speculation. That feedback is what lets an agent recover from a failed tool call, adjust to unexpected output, and chain steps toward a goal. But it's also where the danger hides — because the loop only ends when the model chooses to end it, and a model can fail to choose. That's the problem the harness must solve.
The hard stop
Here's the failure that catches every agent builder once: the model never decides it's finished. It retries a failing tool over and over, oscillates between two actions, or chases a goal it can't reach — and because the loop only exits when the model says "done," it doesn't. It just keeps going, step after step, spending tokens and money with nothing to show. An unbounded agent loop isn't a bug that crashes; it's a bug that runs your bill up.
The fix is non-negotiable: the harness enforces hard bounds that don't depend on the model's judgment. A maximum step count caps how many loop iterations can run. A cost (or token) budget caps how much can be spent. Whichever is hit first, the loop halts — regardless of what the model wants. These bounds guarantee termination: no matter how confused the agent gets, the loop is a finite process. This is the agent-runtime version of a timeout, and it's the first thing a production harness must have, not the last.
The bounds math
Model each loop step as having some probability p of completing the task. Then finishing is a geometric process — the chance of being done within k steps, and the expected number of steps, are:
Success probability rises fast with more steps allowed, and the average run finishes in about 1/p steps — so most legitimate tasks complete well before a generous cap.
But if p = 0 (the task is impossible or the agent is stuck), no number of steps ever finishes — the geometric never terminates. That's why the loop needs a bound independent of p: stop at max_steps or when spend exceeds budget, whichever comes first:
The bound converts a possibly-infinite process into a finite, budgeted one — set max_steps from E[steps] plus headroom, and back it with a hard cost budget. The runnable version below runs a bounded loop that halts on completion, max steps, or budget.
A bounded agent loop
The agent loop is a for-loop with brakes. If each step finishes the task with probability p, the chance of finishing within k steps is 1 − (1 − p)^k (rising fast) and the expected run is 1/p steps. But a stuck task (p = 0) never finishes, so the harness enforces bounds: it halts at max_steps, or when spend would exceed the budget, or when the task completes — whichever comes first. That guarantees the loop is finite no matter what the model does. Change the step function, the max steps, or the budget and watch how the loop terminates.
What the harness owns
Beyond the loop and its bounds, a production harness carries a lot of the reliability:
| Responsibility | What it does |
|---|---|
| Bounds & termination | Max steps + cost/token budget + a done-signal — guarantees the loop halts. |
| Tool dispatch | Parse the model's tool call, validate arguments, run the tool, capture the result and errors. |
| Context assembly | Build each turn's prompt: system, goal, tool schemas, and the running history (with memory management). |
| Error handling | Retries with backoff, feeding failures back so the model can recover instead of crashing. |
| Observability | Log every step — action, result, tokens, cost — so you can trace and debug the run. |
| Guardrails | Validate tool arguments and results at the boundary (see guardrails). |
Two are worth calling out. Loop detection — if the agent repeats the same action with the same result, it's stuck; catch that and break early rather than waiting for the step cap. And a graceful halt handler — when a bound trips, return partial progress and a clear reason, not a crash. The deeper craft of designing this loop well — when to reflect, when to branch, how to keep the agent on track — is the subject of loop engineering; this handbook is about the runtime skeleton that makes any of it safe to run.
Pitfalls
The cardinal sin is shipping without bounds — a `while not done` loop with no cap. It works in the demo, then in production an edge case makes the agent loop and you discover it via the bill. Always bound both steps and cost: a step cap alone won't save you from an agent making a few very expensive calls, and a cost cap alone won't catch a fast infinite loop of cheap ones. Belt and braces.
Two more. Silent context growth: each step appends to the history, so a long run can blow the context window or quietly balloon cost per step — pair the harness with memory management. And trusting tool output blindly: a tool result flows straight back into the model's context, so a malicious or malformed result can hijack the loop — validate at the boundary. Build the harness bounds-first: get a loop that always terminates, then add the tools, then make it smart. An agent you can't stop isn't an agent — it's a liability with a prompt.
Bound both dimensions. A max-step cap won't stop an agent that makes a handful of very expensive calls; a cost budget won't stop a fast loop of cheap ones. Enforce max_steps AND a cost/token budget, halt on whichever trips first, and always handle the halt gracefully.
Worked example: sizing max_steps and the token budget together
Say a task finishes on any given step with p = 0.25, so the average run takes 1/p = 4 steps. Each step sends a 2,000-token base prompt plus the whole history so far, and every step adds 1,500 tokens to that history. These numbers are illustrative. The goal: a cap that lets 99% of honest runs finish, and a budget that does not quietly undercut it.
| Step k | P(done ≤ k) | Input tokens this step | Tokens spent so far |
|---|---|---|---|
| 1 | 25.0% | 2,000 | 2,000 |
| 4 | 68.4% | 6,500 | 17,000 |
| 8 | 90.0% | 12,500 | 58,000 |
| 11 | 95.8% | 17,000 | 104,500 |
| 12 | 96.8% | 18,500 | 123,000 |
| 16 | 98.998% | 24,500 | 212,000 |
| 17 | 99.25% | 26,000 | 238,000 |
Solving 1 − 0.75^k ≥ 0.99 gives k ≥ 16.008, so max_steps = 17: 16 falls just short. Now look at the last column. A typical 4-step run spends 17,000 tokens, but a stuck run (p = 0) that rides the cap to step 17 spends 238,000, which is 14 times as much. Cost grows with the square of the step count, because every step re-sends a longer history: k × 2,000 + 1,500 × k(k − 1)/2. So the budget must be sized from the cap, not from the average. Set a 120,000-token budget “to be safe” and it trips before step 12, which turns it into an 11-step cap that kills 4.2% of honest runs (0.75^11). A budget of about 250,000 lets the cap do its job, and the budget is then the backstop for a run whose steps cost more than you planned.
Cost and trade-offs: which bound catches what
Here Time is the failure each bound stops, and Space is the failure that still gets through it.
| Case | Time | Space | Why |
|---|---|---|---|
| Step cap only | A fast loop of cheap steps | A few very expensive steps, and the quadratic history growth above | Simple and predictable, but it counts turns, not money. |
| Token or cost budget only | Runaway spend of any shape | A cheap loop runs for a long time before the budget is gone | It bounds the bill, not the latency or the number of tool side effects. |
| Wall-clock timeout | A tool call that hangs and never returns | A run that is fast but wrong | Steps and tokens do not move while a tool is hung, so neither cap fires. |
| Loop detection | A stuck agent repeating one action, long before the cap | An agent that wanders through actions that each look new | Cheap to add: hash (action, arguments, result) and break on a repeat. |
| All four, halt on the first | Every case above | A run that stays inside every bound and still does the wrong thing | That last case is not a bounds problem. It belongs to evals and guardrails. |
Where this shows up in production and interviews
- Agent frameworks ship the cap
LangGraph stops a graph that passes its
recursion_limit(25 by default) with aGraphRecursionError. The OpenAI Agents SDK takesmax_turnsand raisesMaxTurnsExceeded. Both are the step cap from this page. Neither is a cost budget, so you still add that yourself. - Coding agents in CI
An agent that edits code and runs tests in a pipeline needs all three limits: a turn cap, a token budget, and the job’s own timeout, because a hung test run stops neither counter. When a limit trips, the job should fail with the reason and leave its partial diff, not vanish.
- Retries count against the budget
A tool that fails and is retried with backoff is still spending. If retries live inside the tool wrapper and never pass through the loop, a step cap of 10 can hide 30 real calls. Count every model call and every tool call where the budget is checked.
- The interview version
In “design an agent that does X”, name the termination conditions before the tools. Say what the cap is and how you chose it (1/p plus headroom), what the budget is and why it is sized from the cap, how you detect a stuck loop, and what the caller gets back when a bound trips.
Check yourself
A task has p = 0.1 per step and the cap is 10 steps. What share of honest runs hit the cap?
The chance of finishing within 10 steps is 1 − 0.9^10 ≈ 65.1%, so about 34.9% hit the cap even though the average run needs only 1/p = 10 steps. A cap equal to E[steps] is far too tight. The cap has to come from the tail of the distribution, not from the mean.
Your agent alternates between two tool calls with identical arguments and results. Which bound should stop it, and when?
Loop detection, on the first repeat of the same (action, arguments, result). The step cap and the budget will stop it eventually, but only after spending the whole allowance. A repeat with an identical result means the next step has no new information to plan from.
You double max_steps but leave the token budget alone. What happens to the worst-case bill?
Usually nothing: the budget now trips first and becomes the real cap. If the budget is large enough to allow the doubled cap, the worst case grows by roughly four times, not two, because each step re-sends a longer history. Change the cap and the budget together.
A bound trips mid-task. What should the harness return?
A structured halt: which bound tripped, the step count and spend, the last observation, and any partial result. Returning a crash or an empty answer throws away work the caller paid for, and the reason is what tells the operator whether to raise the cap or fix the task.
Quick answers
What is an agent harness?
The code that wraps a model in a plan-act-observe loop — owning tool dispatch, context assembly, error handling, and the bounds that stop the loop.
What is the plan-act-observe loop?
The agent cycle: the model plans an action, the harness runs it, the result is observed back, and it repeats until done — the ReAct pattern.
Why a hard stop?
A model can fail to ever finish, so an unbounded loop runs forever burning money; max steps + a cost budget guarantee termination.
How many steps to allow?
Set from expected steps (~1/p) plus headroom, and pair with a cost budget so both a slow loop and an expensive one are bounded.
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agentic AI Interview HandbookTwenty topics every senior AI engineer should be able to reason about live — from eval pipelines to reliability patterns for generative systems.Read →
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →
- The Agent Patterns HandbookThe design patterns behind every LLM agent — the ReAct Thought–Action–Observation loop, tool/function calling, plan-and-execute, reflection, memory, multi-agent orchestration, and the failure modes (loops, hallucinated tools, recovery, human-in-the-loop) that break agents in production.Read →
- The Model Context Protocol (MCP) HandbookThe open standard connecting AI agents to the outside world — why M×N bespoke integrations collapse to M+N, the host/client/server roles over JSON-RPC, the three primitives (tools, resources, prompts), the connect→discover→call session lifecycle, when MCP earns its keep, and the security sharp edges (a server's output is untrusted input).Read →
- The Loop Engineering HandbookStop prompting your agents — design the system that prompts them for you. The inner vs outer loop, the four loop types (heartbeat, cron, hook, goal), the six building blocks (automations, worktrees, skills, MCP connectors, subagents, external memory), stopping conditions and the verification split, state across runs, cost engineering, and the six failure modes that burn tokens at 3am.Read →
- The Context Engineering HandbookThe discipline that replaced prompt-tweaking: curating everything the model sees under a finite attention budget. The anatomy of a production context window, the three taxes on an overstuffed one (context rot, cost, behavioral drift), the four operations (write, select, compress, isolate), agent-specific patterns like compaction and just-in-time retrieval, six production habits, and where it sits in the prompt → context → loop → harness stack.Read →