The Agent Loop: Observe, Reason, Plan, Act, Reflect
Every agent, however elaborate, is a cycle. Learn the cycle and you can read any design.
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.
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.
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.
| Term | Meaning | Coding agent example |
|---|---|---|
| Environment | The world the agent acts in | A repository, a terminal, a test suite |
| State | The true situation, which may not be fully visible | All files and running processes |
| Observation | What the agent is shown | One file's contents, a test report |
| Action | A choice that may change the state | Edit a file, run tests |
| Reward | A score for how good the outcome was | Tests pass; change is small |
| Episode | One attempt from start to end | One 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.
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.
| Aspect | Open loop | Closed loop |
|---|---|---|
| Uses feedback | No | Yes |
| Model calls | Few | One or more per step |
| Handles surprises | Poorly | Better, if observations are good |
| Predictability | High | Lower |
| Suits | Stable, cheap-to-redo tasks | Changing 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 rule | Trigger | What to return |
|---|---|---|
| Success | A check on the environment passes | Result and evidence |
| Step limit | Maximum turns reached | Progress so far and what remains |
| Budget | Time, tokens or money spent | Same, plus the spend |
| No progress | The measure has not improved for several turns | What was tried and the last error |
| Repetition | The same call with the same arguments | The repeated call and its result |
| Cannot proceed | Missing information or permission | A specific question |
| External stop | A person or monitor cancels | A safe, known state |
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.
| Turn | Observe | Reason and plan | Act | Reflect |
|---|---|---|---|---|
| 1 | Only the question | Find the supplier's delivery page | Search | Found a page, undated |
| 2 | Page says "next day on most items" | "Most" is not an answer for this item | Open the item page | Progress: item listed |
| 3 | Item page says "two to three days" | Two sources differ; the item page is more specific | Report both, cite both | Goal met, with a stated caveat |
A weaker loop would have stopped at turn 2 with a confident "yes".
Variations on the loop
| Variation | Idea | Use when |
|---|---|---|
| Step-by-step (ReAct style) | Decide one action at a time | The next step depends on the last result |
| Plan then execute | Make a plan, run it, replan on failure | Steps are mostly foreseeable |
| Evaluator and optimizer | One part produces, another critiques, repeat | Quality can be judged against clear criteria |
| Nested loops | An outer plan loop calls inner task loops | Large tasks with separable parts |
| Event-driven | Sleep between steps and wake on events | Waiting hours or days for replies |
| Parallel branches | Several attempts or sub-tasks at once | Independent 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:
- Did the model see the information it needed?
- Was the observation accurate and understandable?
- Was a suitable action available and clearly described?
- Did the runtime run exactly what was asked?
- Was there a check that should have caught the mistake?
| Pattern in the trace | Likely cause | Remedy |
|---|---|---|
| Alternates between two actions | Two goals or rules conflict | Resolve the conflict; detect cycles, not only repeats |
| Declares success early | No external check | Verify before accepting a final answer |
| Wanders off the task | Goal buried by long history | Restate goal and plan each turn; trim results |
| Gives up at the first error | Error gives no hint | Return 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.
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
- ReAct: Synergizing Reasoning and Acting in Language Models (paper)
- Reflexion: Language Agents with Verbal Reinforcement Learning (paper)
- Self-Refine: Iterative Refinement with Self-Feedback (paper)
- Building effective agents (Anthropic engineering)
Next steps
ReAct Agents: Reasoning and Acting
The most widely taught step-by-step loop.
Plan-and-Execute and Dynamic Planning
Plan first, then adapt.
Agent Decisions: Confidence, Stopping, Loops and Budgets
Set confidence, stop rules and budgets.