The Agent Loop: Observe, Reason, Plan, Act, Reflect

Every agent, however elaborate, is a cycle. Learn the cycle and you can read any design.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

The agent loop is a repeating cycle: observe the situation, reason about it, plan the next step, act, then reflect on the result. It ends when the goal is met, when no progress is being made, or when a limit or a person stops it.

What you will learn: what each stage does, how environments, actions, observations and rewards relate, why closed loops beat open ones, how to stop a loop safely and how to debug one.
Prerequisites: What Is an AI Agent? Anatomy and Goals. Basic Python for the code.

Beginner The cycle in everyday terms

A loop you already know

Think of cooking soup without a timer. You taste it, judge that it is bland, decide to add salt, add a pinch, then taste again. You do not add a fixed amount and serve. You steer by what you find. An agent works the same way, with a language model doing the judging and tools doing the tasting and adding.

1. ObserveGather the latest facts
2. ReasonInterpret them against the goal
3. PlanChoose the next step
4. ActUse a tool or ask a person
5. ReflectDid it help? Continue or stop?
↺ The new situation becomes the next observation

These names are a teaching model. In many real agents, one model call performs reasoning and planning together and returns a tool request. Reflection may be part of the next call, or a separate check. The responsibilities exist even when the code does not name them.

The five stages

Observe

Observation is everything the agent learns from outside itself: the user's message, a tool result, an error, a file listing, a screenshot, an event. The agent only knows what reaches it. If a tool returns "success" without saying what changed, the agent is steering blind.

Good observations are relevant, compact and honest. A search tool that returns three useful passages with their sources is far better than one that returns forty pages. A failed call should say that it failed and, if possible, why.

Reason

Reasoning interprets the observation against the goal. Is this what we expected? What is still missing? Is there a conflict between two sources? The model does this when it reads its context. Some models produce an extended reasoning phase before answering. That can improve harder decisions, at the price of time and tokens.

Plan

Planning chooses what to do next. It may be a single step, decided each time, or a longer list that is revised as facts arrive. The two styles are compared in ReAct Agents: Reasoning and Acting and Plan-and-Execute and Dynamic Planning. A plan is a guess about the future, so treat it as something to update.

Act

Acting turns a decision into an effect, through a tool call, a message or a hand-off. Your runtime stands between the request and the effect: it validates arguments, checks permissions, asks for approval where needed and applies timeouts. See Reliable Tool Execution and Error Recovery.

Reflect

Reflection asks whether the action moved the agent toward the goal. The best reflection uses evidence from the environment: a test passed, a record now exists, a balance changed. A model judging its own work is useful but weaker, because it may share the same blind spot that caused the error. Reflection, Self-Critique and Self-Refine covers techniques.

Environment, actions, observations and rewards

The vocabulary comes from the study of decision-making systems, including reinforcement learning.

TermMeaningCoding agent example
EnvironmentThe world the agent acts inA repository, a terminal, a test suite
StateThe true situation, which may not be fully visibleAll files and running processes
ObservationWhat the agent is shownOne file's contents, a test report
ActionA choice that may change the stateEdit a file, run tests
RewardA score for how good the outcome wasTests pass; change is small
EpisodeOne attempt from start to endOne bug-fix task

The gap between state and observation matters. The agent has a partial view, so it may need actions whose only purpose is to look. In reinforcement learning, rewards are used to train a policy. Most language-model agents are not trained while they run. A reward-like score is still very useful for evaluation and for choosing between attempts. See Graph, Game, Control Theory and Reinforcement Learning.

Intermediate Build it and control it

Open-loop and closed-loop execution

An open-loop system plans everything up front and carries it out without looking at the results. A closed-loop system checks results and adjusts.

AspectOpen loopClosed loop
Uses feedbackNoYes
Model callsFewOne or more per step
Handles surprisesPoorlyBetter, if observations are good
PredictabilityHighLower
SuitsStable, cheap-to-redo tasksChanging or uncertain environments

You can mix them. Run a known sequence open-loop, then check the result once and loop only if the check fails. This saves calls without giving up correction.

The loop in code

A heating controller makes each stage visible without any model. The goal is a temperature, the actions switch a heater, and reflection compares before and after. The second run uses a broken heater.

"""One agent loop with the five stages named. Standard library only."""

class Thermostat:
    """A tiny environment the agent can observe and change."""
    def __init__(self):
        self.temperature, self.heater = 15.0, False
    def observe(self):
        return {"temperature": round(self.temperature, 1), "heater": self.heater}
    def act(self, action):
        if action == "heater_on":
            self.heater = True
        elif action == "heater_off":
            self.heater = False
        self.temperature += 2.0 if self.heater else -0.5   # time passes

def reason(observation, goal):
    gap = goal - observation["temperature"]
    return "too cold" if gap > 0.5 else "too warm" if gap < -0.5 else "on target"

def plan(assessment):
    return {"too cold": "heater_on", "too warm": "heater_off"}.get(assessment, "finish")

def reflect(before, after, goal):
    better = abs(goal - after["temperature"]) < abs(goal - before["temperature"])
    return "progress" if better else "no progress"

def run(env, goal=21.0, max_steps=10, patience=2):
    stalled = 0
    for step in range(1, max_steps + 1):
        before = env.observe()                      # 1. observe
        assessment = reason(before, goal)           # 2. reason
        action = plan(assessment)                   # 3. plan
        if action == "finish":
            return f"goal met at {before['temperature']} after {step - 1} actions"
        env.act(action)                             # 4. act
        verdict = reflect(before, env.observe(), goal)   # 5. reflect
        print(f"{step}: {before['temperature']} {assessment:9} -> {action:10} {verdict}")
        stalled = stalled + 1 if verdict == "no progress" else 0
        if stalled >= patience:
            return "stopped: no progress, asking for help"
    return "stopped: step limit"

print(run(Thermostat()))

class BrokenHeater(Thermostat):
    def act(self, action):
        self.temperature -= 0.5                     # the command has no effect

print(run(BrokenHeater()))

Output:

1: 15.0 too cold  -> heater_on  progress
2: 17.0 too cold  -> heater_on  progress
3: 19.0 too cold  -> heater_on  progress
goal met at 21.0 after 3 actions
1: 15.0 too cold  -> heater_on  no progress
2: 14.5 too cold  -> heater_on  no progress
stopped: no progress, asking for help

Two lessons sit in those lines. First, the broken heater is caught because the loop checks the effect, not the command. Without the patience rule it would try ten times. Second, "goal met" does not mean the world was left safe: the first run finishes with the heater still on. Add the clean-up to your definition of done.

To turn this into a language-model agent, replace reason and plan with one model call that sees the goal and history and returns a tool request. Keep the step limit, the progress check and the final verification in code. The full version is in Build Your First AI Agent and Multi-Agent App.

Stopping the loop

A loop without good stop rules either quits early or runs up a bill. Combine several.

Stop ruleTriggerWhat to return
SuccessA check on the environment passesResult and evidence
Step limitMaximum turns reachedProgress so far and what remains
BudgetTime, tokens or money spentSame, plus the spend
No progressThe measure has not improved for several turnsWhat was tried and the last error
RepetitionThe same call with the same argumentsThe repeated call and its result
Cannot proceedMissing information or permissionA specific question
External stopA person or monitor cancelsA safe, known state
Repetition needs judgment

Some repeats are correct, such as checking whether a long job has finished. For those, allow a set number of repeats with a delay, rather than blocking all identical calls.

More on thresholds in Agent Decisions: Confidence, Stopping, Loops and Budgets.

What the loop remembers

Each turn, the runtime sends the model the instructions, the goal and some form of history. If everything is resent, input grows with every step and old, irrelevant results compete for attention. Common remedies are to keep tool results short, replace old results with summaries, and store large outputs in files that can be read again. Keep the goal and constraints visible in every turn. Context Assembly, Retrieval, Compression and Caching covers the methods.

Errors inside the loop

Treat errors as observations, with care:

  • Temporary errors, such as a timeout, can be retried by the runtime without involving the model.
  • Correctable errors, such as a bad argument, should go back to the model with a clear explanation.
  • Permanent errors, such as a denied permission, should end that path. Do not invite the model to find a way around a control.
  • Uncertain results, where you cannot tell whether a write happened, need a read to confirm before any retry.

A second trace: a research loop

The same stages appear in a task with no physical world. The goal is to find whether a supplier offers next-day delivery, with a source.

TurnObserveReason and planActReflect
1Only the questionFind the supplier's delivery pageSearchFound a page, undated
2Page says "next day on most items""Most" is not an answer for this itemOpen the item pageProgress: item listed
3Item page says "two to three days"Two sources differ; the item page is more specificReport both, cite bothGoal met, with a stated caveat

A weaker loop would have stopped at turn 2 with a confident "yes".

Expert Design variations and diagnosis

Variations on the loop

VariationIdeaUse when
Step-by-step (ReAct style)Decide one action at a timeThe next step depends on the last result
Plan then executeMake a plan, run it, replan on failureSteps are mostly foreseeable
Evaluator and optimizerOne part produces, another critiques, repeatQuality can be judged against clear criteria
Nested loopsAn outer plan loop calls inner task loopsLarge tasks with separable parts
Event-drivenSleep between steps and wake on eventsWaiting hours or days for replies
Parallel branchesSeveral attempts or sub-tasks at onceIndependent work, or choosing the best attempt

For long waits, the loop must survive restarts. Save state after each step and make actions safe to repeat. See Durable Execution, Checkpoints and Approvals.

Why short, checked loops win

Suppose each step succeeds 95 times in 100 and steps are independent. The chance that a whole run has no failed step is 0.95 raised to the number of steps: about 77% for 5 steps, 60% for 10 and 36% for 20. Real steps are not independent, and agents can recover from errors, so treat this as an intuition and not a prediction. It still explains two good habits: verify intermediate results so errors are caught early, and move predictable steps into code so there are fewer chances to go wrong.

Debugging a loop

Read the trace turn by turn and ask, for the first turn that went wrong:

  1. Did the model see the information it needed?
  2. Was the observation accurate and understandable?
  3. Was a suitable action available and clearly described?
  4. Did the runtime run exactly what was asked?
  5. Was there a check that should have caught the mistake?
Pattern in the traceLikely causeRemedy
Alternates between two actionsTwo goals or rules conflictResolve the conflict; detect cycles, not only repeats
Declares success earlyNo external checkVerify before accepting a final answer
Wanders off the taskGoal buried by long historyRestate goal and plan each turn; trim results
Gives up at the first errorError gives no hintReturn the cause and an allowed next step

Tooling for traces is covered in Agent Tracing and OpenTelemetry, and a method for diagnosis in Debugging Agents, RAG and Handoffs.

Expert tip

Measure steps per successful task over time. A rising number is an early warning: a changed tool message, a new model version or messier data can make the agent work harder long before success rates visibly fall.

Loop checklist

  • Every tool result says what happened, including failures.
  • Success is verified from the environment.
  • Step, time and spending limits are set.
  • Repetition and lack of progress are detected.
  • The loop can ask a question and hand over cleanly.
  • Stopping leaves the system in a safe state.
  • Each turn is recorded in a trace.

Frequently asked questions

Is "observe, reason, plan, act, reflect" a standard?

No. Authors use different stage names, such as perceive, think and act. They describe the same feedback cycle.

How many steps should I allow?

Measure successful runs on your own test set and set the limit somewhat above what they need. Review the runs that reach it.

Does reflection require a second model?

No. A test, a rule or a database read is often better. A second model can help where no automatic check exists, but evaluate how often it is right.

Can an agent have more than one loop?

Yes. Planners, sub-agents and evaluators each run loops. Give every loop its own limits, and share an overall budget.

References and further reading

Next steps