Planning and reflection in agents
A plain ReAct loop decides one step at a time. That works well for short tasks, but on long ones the agent can lose the thread, repeat work or wander off goal. Two techniques help: planning, where the agent writes down how it intends to solve the problem before acting, and reflection, where it looks back at what happened and adjusts. Both are cheap to add and both have failure modes worth knowing.
Why it matters
Long-horizon tasks (a multi-file refactor, a research report, a data migration) need the agent to keep a goal in mind across dozens of tool calls. Without an explicit plan, the only record of intent is buried in an ever-growing conversation. With a plan, you get:
- A checkpoint you can show a human before any side effects happen.
- A progress tracker the agent can re-read after context is compacted.
- A natural unit for parallelism (independent plan steps can go to sub-agents).
Reflection addresses a different problem: models often produce a plausible first attempt that is wrong in ways they could catch if asked to check. Papers like Self-Refine and Reflexion showed that a critique-and-retry loop improves results on tasks such as coding and reasoning, particularly when the critique is grounded in an external signal like a failing test.
How it works
Planning patterns
- Plan-and-execute. One call produces a list of steps; an executor (often a ReAct agent) carries them out one at a time. The Plan-and-Solve prompting paper is an early version of this idea.
- Replanning. After each step, or after a failure, the planner sees results so far and revises the remaining steps. This is the version I recommend; static plans go stale quickly.
- To-do lists as tools. Many coding agents expose a simple "write todos" tool. The plan lives in state, the model updates it as it goes, and the UI can show progress. It is planning without a separate planner model.
- Search-based planning. Tree of Thoughts and similar methods explore several candidate steps and evaluate them. Powerful for puzzles, usually too expensive for everyday product work.
Modern reasoning models also plan internally (extended thinking). That reduces the need for a separate planning prompt on short tasks, but an explicit, persisted plan is still valuable for long runs and human review.
Reflection patterns
- Self-critique. After producing output, ask the model to review it against explicit criteria and revise. This is the evaluator-optimizer workflow applied inside an agent.
- Grounded reflection. Feed the critique real evidence: test results, linter output, a validator's errors. This is far more reliable than asking "are you sure?".
- Reflexion. After a failed attempt, the agent writes a short verbal lesson ("I assumed the API returned a list, it returns a paginated object") into memory, and the next attempt includes those lessons. It is learning through the prompt rather than through weights.
Rendering diagram…
Reference architecture
In a production agent I keep plan and lessons as explicit state, not just chat history:
Rendering diagram…
The human approval gate on the plan is one of the highest-leverage controls you can add: it is cheap for a person to read a ten-line plan, and much cheaper than undoing ten wrong actions.
Code
A minimal plan-execute-reflect loop in Python. The planner returns JSON, each step is executed (here, by a stub that would call your ReAct agent), and failures trigger a reflection that is fed into the replanning call.
import json
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
def call(system: str, prompt: str) -> str:
msg = client.messages.create(
model=MODEL, max_tokens=1024, system=system,
messages=[{"role": "user", "content": prompt}],
)
return msg.content[0].text
PLANNER = (
"You plan tasks for a coding agent. Return only JSON: "
'{"steps": ["..."]}. At most 6 steps. Use the lessons to avoid past mistakes.'
)
def plan(goal: str, done: list[str], lessons: list[str]) -> list[str]:
raw = call(PLANNER, json.dumps({"goal": goal, "completed": done, "lessons": lessons}))
return json.loads(raw)["steps"]
def execute(step: str) -> tuple[bool, str]:
# Replace with your tool-using agent plus a real check (tests, validator)
return True, f"done: {step}"
def reflect(step: str, evidence: str) -> str:
return call(
"In one sentence, state what went wrong and what to do differently next time.",
f"Step: {step}\nEvidence: {evidence}",
)
def run(goal: str, max_steps: int = 12) -> list[str]:
done, lessons = [], []
steps = plan(goal, done, lessons)
while steps and len(done) < max_steps:
step = steps.pop(0)
ok, evidence = execute(step)
if ok:
done.append(step)
else:
lessons.append(reflect(step, evidence))
steps = plan(goal, done, lessons) # replan with the new lesson
return done
print(run("Add input validation to the signup endpoint and cover it with tests"))
In a real system, parse the planner output with a schema validator (or use structured outputs) rather than trusting raw json.loads, and persist done and lessons so a crash does not lose progress.
Trade-offs and pitfalls
- Over-planning simple tasks. A planner call adds latency and cost. For tasks that finish in two or three tool calls, skip it.
- Stale plans. A plan written before the agent has looked at the codebase is a guess. Replan after discovery steps.
- Ungrounded self-critique. Models asked to critique their own work without evidence can rubber-stamp it, or "fix" correct answers. Anchor reflection to tests, validators or a separate evaluator with clear criteria.
- Lesson pollution. Reflexion-style memories can encode wrong lessons. Scope them to a task or user, give them timestamps, and prune them.
- Infinite revision. Cap reflection rounds and keep the best attempt, not the latest.
- Plans are not guarantees. An agent can claim a step is done when it is not. Verify completion with checks in code wherever possible.
Checklist
- Use an explicit plan only for tasks long enough to benefit from one.
- Store the plan as structured state with per-step status.
- Replan after discovery steps and after any failure.
- Ground reflection in external evidence such as tests or validators.
- Cap planning, execution and reflection iterations separately.
- Offer human review of the plan before side-effectful steps.
- Persist lessons with scope and expiry, and review them periodically.