Sub topic 11
Planning and reasoning patterns
This chapter assumes you can write the basic agent loop from the earlier chapter (model call, tool call, observation, repeat). It also assumes you are comfortable with JSON tool results and step limits. Here you will learn how to help an agent decide what to do next, and how to pick a pattern that fits the task.
Why planning matters
The basic loop is greedy. At each step the model sees the history and picks one action. For short tasks this works. For longer tasks, three problems show up:
- Drift. After many tool calls, the original goal is far back in the history and the model starts chasing side details.
- Dead ends. The model commits to an approach and keeps retrying it instead of changing course.
- Wasted steps. Without an overview, the model repeats searches or reads the same file twice.
Planning patterns address these by giving the agent an explicit structure for deciding, tracking, and revising its work. Each pattern adds model calls and tokens, so it costs more. Use one only when the task needs it.
Pattern 1: ReAct (reason, act, observe)
ReAct interleaves a short piece of reasoning with each action. The model writes what it thinks, requests a tool call, reads the result, and reasons again. The loop you already built is ReAct if the model produces text before each tool call. You can encourage this in the system prompt:
Before each tool call, write one sentence stating what you expect to learn from it.
After each result, state whether the goal is closer, and what you will do next.ReAct is adaptive. Every observation can change the next step. Its weakness is that the plan only exists implicitly in the history. On long tasks the model may lose track of it.
Pattern 2: Plan, then execute
In plan-and-execute, one model call writes a list of steps up front. A separate executor works through the list, one step at a time. The plan lives outside the chat history as data, so you can inspect it, log it, show it to a user for approval, and track progress against it.
Benefits:
- The agent stays on goal, because each executor call sees only one step plus the results it needs.
- You can use a cheaper model for execution and a stronger one for planning.
- A human can review the plan before anything runs. This links directly to the guardrails chapter.
The main risk is a stale plan. If step 2 fails or reveals something unexpected, steps 3 to 5 may be wrong. So you need replanning.
Pattern 3: Replanning
Replanning means that when a step fails or the result changes the situation, you call the planner again. You give it the goal, the completed steps with their results, and the failure. It returns a new list of remaining steps. Always cap the number of replans, for the same reason you cap loop steps: a model can replan forever.
def plan_and_execute(call_planner, call_executor, goal, max_replans=2):
plan = call_planner(goal, completed=[])
done = []
replans = 0
while plan:
step = plan[0]
outcome = call_executor(step)
if outcome["ok"]:
done.append({"step": step, "result": outcome["result"]})
plan = plan[1:]
continue
if replans >= max_replans:
raise RuntimeError(f"Gave up at step '{step}': {outcome['error']}")
replans += 1
plan = call_planner(
goal,
completed=done,
failure={"step": step, "error": outcome["error"]},
)
return done
def fake_planner(goal, completed, failure=None):
# Scripted stand-in for a planning model.
if failure is None:
return ["locate report", "read report", "summarize report"]
return ["read report from backup", "summarize report"]
def fake_executor(step):
# Scripted stand-in: the first read attempt fails.
if step == "read report":
return {"ok": False, "error": "file locked"}
return {"ok": True, "result": f"done: {step}"}
results = plan_and_execute(fake_planner, fake_executor, "Summarize the report")
for item in results:
print(item["step"], "->", item["result"])The run prints three completed steps: locate report, read report from backup, and summarize report. The failed step never appears in done, so the replanned list continues from the real state of the world.
Pattern 4: Reflection
Reflection adds a critique step. After the agent produces a draft answer or finishes a step, a second call (or the same model with a different prompt) checks the work against explicit criteria. If the check fails, the critique goes back to the agent for another try.
Reflection works best when the criteria are concrete and checkable: "the SQL runs without error", "every claim cites a retrieved document", "the output validates against the schema". It works poorly with vague criteria such as "make it better", because the model tends to approve its own output.
Choosing a pattern
| Pattern | Best for | Cost | Main risk |
|---|---|---|---|
| Plain loop | Short tasks, 1 to 4 tool calls | Lowest | Drift on long tasks |
| ReAct | Exploratory tasks where each result changes the next move | Low to medium | Plan is implicit and can be forgotten |
| Plan-and-execute | Long, multi-step tasks with predictable structure | Medium | Stale plan after a failure |
| Plan with replanning | Long tasks in changing environments | Medium to high | Replan loops |
| Reflection | Output with checkable quality criteria | Adds one call per check | Self-approval |
A practical rule: start with the plain loop. Add a pattern when you observe a specific failure in your traces, such as drift or repeated calls. Do not add planning because it sounds more capable.
Keeping the plan visible
In plan-and-execute designs, the plan is state. Treat it like any other state in your program:
- Store each step with a status, such as
pending,done, orfailed. - Include the current plan in the context on every executor call, so the model knows where it is.
- Log every plan and every replan, so you can see why the agent changed direction.
A model can also maintain its own plan through a tool, for example an update_plan tool that takes the full list of steps and statuses. This keeps the plan in the history without a separate planner call. The trade-off is that the model may mark steps done that it did not complete, so verify important steps with tool results.
Reasoning models and "thinking" budgets
Some models do extended reasoning internally before they answer. This overlaps with ReAct-style prompts. If you use such a model, you usually do not need to ask it to "think step by step", and doing so can waste tokens. Instead, control the reasoning budget, if your provider exposes one. Spend more on planning steps and less on routine ones.
Common errors
- Planning for trivial tasks. A three-step plan for "what is the weather in Oslo?" adds latency and gains nothing.
- Plans that are too detailed. A plan with exact arguments for every call breaks as soon as one result differs. Plan at the level of intent ("find the config file"), and let the executor choose arguments.
- No replan cap. The agent keeps producing new plans that fail in the same way.
- Replanning without the failure. If the planner does not see the error and the completed steps, it will often repeat the same plan.
- Trusting plan status. Mark a step done only from observed tool output, not from the model's claim.
- Reflection with no exit. Always limit the number of critique rounds, and stop early if the critique repeats itself.
Exercise
Your agent researches a topic over 15 tool calls. In traces, you see it re-running searches it already did and forgetting the user's constraint on date range. Which pattern would you add first, and what would you log to confirm it helped?
Show answer
Add plan-and-execute with a visible plan, and include the plan and the user's constraints in the context on every executor call. This tackles both problems: the stored step list with statuses prevents repeated searches, and restating the constraints counters drift. To confirm the change helped, log each plan and replan, and compare the number of duplicate tool calls and constraint violations per run before and after, using the same set of test tasks.
Exercise
In the planandexecute code, what happens if call_planner returns an empty list after a failure, and why might that be a problem?
Show answer
The while loop ends because plan is empty, and the function returns the completed steps as if the task succeeded, even though the failed step was never completed. A safer version would treat an empty plan after a failure as an error, or require the planner to say explicitly that the goal is already met.