Advanced Strategies

Loop Engineering

Designing feedback cycles that act, verify, adapt, and know when to stop

Context engineering decides what the model can see. Loop engineering decides what the system does next.

Instead of a person repeatedly reading an answer and writing the next prompt, a loop turns that follow-up work into a designed system. It gives an AI a goal, lets it act, observes real feedback, evaluates the result, and either adapts or stops.

The Short Definition

Loop engineering is the practice of designing the feedback cycle around an AI system: the goal, actions, observations, evaluation, state, guardrails, and stop rules that move work toward a verifiable result.

From a Good Prompt to a Good Loop

A prompt can produce a strong first attempt. A loop is useful when the number of steps cannot be known in advance, the environment can change, or the first attempt must be checked against evidence.

One-Shot Prompt

Ask → Generate → Return

The model produces an answer. A person decides whether it worked and writes the next prompt.

Engineered Loop

Frame → Act → Observe → Evaluate → Adapt
                 ↑______________________↓

The system gathers evidence, records state, and continues only while another pass is useful.

This idea builds on earlier agent patterns. The ReAct paper showed the value of interleaving actions with observations from an external environment. Anthropic's evaluator-optimizer pattern adds a distinct feedback step, while OpenAI's practical guide to agents describes agent runs as loops governed by exit conditions. The newer term loop engineering focuses attention on deliberately designing that whole cycle.

The Five Moves

1. Frame

Turn intent into a goal, constraints, success criteria, and a budget.

2. Act

Choose one bounded action: search, edit, calculate, call a tool, or ask a person.

3. Observe

Collect what actually happened: test output, API results, citations, or user feedback.

4. Evaluate

Compare the evidence with explicit criteria—not with the model's confidence.

5. Adapt

Update state, change the plan, retry safely, escalate, or stop.

The loop is not the arrows. The engineering lives in the contracts between the arrows: what counts as an action, which observations are trustworthy, who evaluates them, what state survives, and exactly when execution ends.

Loop control / interactive simulator

Step through a working feedback loop

Choose a task, then advance one signal at a time. Notice how progress comes from environmental evidence and explicit evaluation—not from asking the model whether it feels finished.

Choose a loop

Goal

Fix the checkout totals without changing valid discount behavior.

Stop rule

The targeted regression test passes, the full checkout suite passes, and lint is clean—or three attempts are exhausted and the loop escalates.

Trusted evidence

Reproduction steps, test output, the code diff, and the final regression suite.

01

Frame

Re-read the contract

02

Act

Make one bounded move

03

Observe

Read external feedback

04

Evaluate

Apply the rubric

05

Adapt

Update the next move

Current signal

Fix the checkout totals without changing valid discount behavior.

Iteration1/3
Verified progress0%
Open issues3

Write the Loop Contract First

Before choosing a model or framework, write a small contract. If these fields are vague, the loop will turn ambiguity into repeated cost.

goal: "What observable state should become true?"
inputs: "What starts the loop?"
state: "What facts and attempts persist between iterations?"
actions: "Which tools may the system use, and with what permissions?"
observations: "What external signals come back from those actions?"
evaluator: "Which rubric or deterministic checks judge the result?"
success: "What evidence proves the goal is complete?"
failure: "Which conditions require recovery or human help?"
budget: "Maximum turns, time, tokens, money, or side effects"
A Loop Without an Exit Is a Failure Mode

Always define three exits: success when evidence satisfies the goal, failure when recovery is no longer useful, and budget exhausted when the loop reaches its allowed cost or risk boundary.

Observations Must Come From the World

The model saying “this looks correct” is not strong evidence. A useful observation is produced by something outside the answer being judged.

TaskWeak observationStrong observation
Code repair“The fix should work.”The original failure is reproduced, then the regression test and the full suite pass.
Research“Several sources agree.”Claims link to original sources with dates, methods, and disagreements recorded.
Data extraction“The JSON seems valid.”Schema validation passes and sampled records match the source.
Content“The copy feels clear.”It passes a named rubric, factual review, link checks, and audience testing.
Operations“The request succeeded.”The external system returns the expected state and an audit record exists.

This is why tools matter: tests, browsers, databases, validators, and human review turn an internal guess into an observable result.

Separate the Maker From the Checker

For low-risk work, one model can draft and self-review. For important work, use a checker with a different job and limited authority.

Maker

Proposes the change, calls action tools, and explains what evidence should be collected.

Checker

Receives the goal, artifact, and evidence; applies the rubric; cannot silently rewrite the work it grades.

The checker does not have to be another AI. Prefer the most deterministic evaluator available:

  1. Exact checks — types, schemas, constraints, permissions, hashes
  2. Executable checks — tests, linters, simulations, link validation
  3. Rubric checks — an independent model or human using named criteria
  4. Outcome checks — real user behavior or production metrics over time
Confidence Is Not Evidence

A confidence score generated by the same model that made the artifact is still a model output. Treat it as a routing hint, not proof.

State Is the Spine of the Loop

Context is what the model sees this turn. State is the compact record that lets the next turn continue without repeating or forgetting work.

Useful Loop State0/6

Store concise decisions and evidence—not a model's private chain of thought. Good state is small, inspectable, and safe to resume.

Common Loop Shapes

The Repair Loop

reproduce → change one thing → run checks → diagnose → repeat or stop

Best for code, configuration, data cleanup, and any task with executable feedback.

The Evaluator-Optimizer Loop

generate → score with a rubric → return targeted feedback → revise

Best for writing, translation, design critique, and outputs whose quality improves through articulated feedback.

The Research Loop

search → inspect sources → identify gaps or conflicts → search again → synthesize

Best when completeness is not known in advance. The stop rule should measure evidence coverage, not the number of search results.

The Human-Gated Loop

prepare → verify automatically → pause before high-risk action → human approves or redirects

Best for payments, publishing, deletion, access changes, medical or legal decisions, and other consequential actions.

Failure Modes to Design Out

FailureWhat happenedEngineering response
Infinite retryThe loop has no measurable success or budget exit.Add explicit terminal states and a hard iteration cap.
Self-congratulationThe maker accepts its own plausible answer without evidence.Use deterministic checks or an independent checker.
Context snowballEvery iteration appends everything until the model loses the signal.Persist structured state and rebuild only relevant context.
ThrashingThe loop alternates between two fixes.Detect repeated states and require a different strategy or escalation.
Goal driftLocal improvements replace the original objective.Re-read the immutable goal and acceptance criteria each cycle.
Unsafe repetitionA reversible mistake becomes harmful when repeated.Limit permissions, side effects, rate, spend, and blast radius.

A Minimal Implementation

let state = initialize(goal, acceptanceCriteria, budget);

while (state.budget.remaining > 0) {
  const context = assembleRelevantContext(state);
  const proposedAction = await maker.chooseAction(context);
  const observation = await tools.executeWithinPolicy(proposedAction);
  const verdict = await evaluator.check({ goal, observation, state });

  state = recordIteration(state, { proposedAction, observation, verdict });

  if (verdict.status === "passed") return complete(state);
  if (verdict.status === "unsafe" || verdict.status === "blocked") {
    return escalateToHuman(state);
  }

  state = adaptPlan(state, verdict.feedback);
}

return stopWithBudgetReport(state);

The code is the easy part. The hard questions are domain questions: Which test proves the bug is gone? Which source is authoritative? Which action is reversible? Who can approve the final step? Those decisions are the actual work of loop engineering.

Practice: Design a Loop

Draft a Loop Contract

Replace the variables with a recurring task from your own work. Ask the AI to challenge weak evidence and ambiguous stop rules.

Design a bounded AI work loop for this task:

TASK: ${task:triage new customer support issues each morning}

Define:
1. The observable goal
2. The trigger and required inputs
3. Allowed actions and tool permissions
4. Trusted observations from the external environment
5. The evaluator and its rubric
6. State that persists between iterations
7. Success, failure, and budget-exhausted exits
8. Human approval gates for risky actions
9. A trace format that makes every iteration auditable

Then identify the three most likely failure modes in your design and revise the loop to prevent them.

An agent edits code, rereads the diff, and says the bug is fixed. What is the most important missing part of the loop?

Further Reading

Summary

Build the Feedback, Not Just the Prompt

A reliable loop has a measurable goal, bounded actions, trusted observations, an explicit evaluator, compact state, safe exits, and human judgment where consequences demand it. The model is inside the loop; the engineer remains responsible for the loop.