Sub topic 11
Planning and reasoning patterns
This chapter assumes you have read about the agent loop and tool calling. You should be able to write a loop that calls a model, runs a tool, and appends the result to the history.
Why planning matters
A basic agent loop picks one action at a time. That works for short tasks. On longer tasks the agent can lose track of its goal, repeat steps, or take actions in the wrong order. Planning patterns add structure to how the model decides what to do next.
Three common patterns
| Pattern | How it works | Best for |
|---|---|---|
| ReAct | The model alternates between a short reasoning note, an action, and an observation | Open-ended tasks where each result changes what to do next |
| Plan-then-execute | The model writes a full step list first, then code runs each step | Tasks with predictable steps and a clear order |
| Reflection | The model reviews its own output or a failed step, then revises | Tasks with a checkable result, such as code that must pass tests |
ReAct needs no extra code beyond the loop you already have. The reasoning text is part of the assistant message, so it stays in the history and guides later steps.
Plan-then-execute separates deciding from doing. You can inspect, log, or ask a human to approve the plan before any tool runs.
A plan-then-execute sketch
This version replans when a step fails, and caps the number of replans. A scripted planner stands in for the model so the code runs as shown.
def run_plan(plan_model, execute_step, goal, max_replans=2):
plan = plan_model(goal, [])
done = []
replans = 0
while plan:
step = plan.pop(0)
ok, result = execute_step(step)
done.append({"step": step, "ok": ok, "result": result})
if not ok:
if replans >= max_replans:
return done
replans += 1
plan = plan_model(goal, done)
return done
def fake_plan(goal, done):
if not done:
return ["fetch", "summarize"]
if not done[-1]["ok"]:
return ["fetch_backup", "summarize"]
return []
def fake_execute(step):
return (step != "fetch", f"ran {step}")
for entry in run_plan(fake_plan, fake_execute, "Summarize the report"):
print(entry["step"], entry["ok"])The planner receives the completed steps, including failures. Without that history it would repeat the same plan.
Common errors
- Stale plans. A plan written at step 0 may be wrong by step 4. Replan on failure, or when an observation contradicts an assumption.
- Unbounded replanning. Always cap replans, just as you cap loop steps.
- Over-planning. A one-tool question does not need a plan. Extra planning calls add cost and latency.
- Trusting reasoning text. A model's written reasoning does not always match what it does. Judge the agent by its actions and results.
Exercise
In the sketch above, why does plan_model receive the list of completed steps when replanning?
Show answer
The planner needs to see which step failed and what was already done. Without that history it could return the same failing plan and waste a replan.