1Why does an agent that improvises step by step miss parts of a big job?
An agent that decides only its next move never sees the whole job. It skips parts, does them in the wrong order or stops early. Planning writes the full list of steps before any work, carries them out one by one and rewrites the remaining steps when a result changes the picture.
You may need it if
- Deliverables come back with whole sections missing.
- The task has a natural order, such as gather, analyse, then write.
- You want to see and approve the approach before money or time is spent.
2When is planning ahead a waste?
Use it when
- The job breaks into three to ten steps that can be named before starting.
- Most steps can run without knowing the result of the one before.
- A person or a later stage should see the approach before it runs.
Avoid it when
- Each step depends on what the last one revealed, so any plan would be rewritten every time.
Use ReAct instead - A wrong step causes real damage and each one must be checked before the next.
Use Plan–Execute–Verify instead - The steps need different specialists and some can run in parallel.
Use Supervisor & Specialists instead - The task is a single lookup or a short answer. A plan adds a call and nothing else.
Use Tool Use instead
What it costs
- Model calls
- 1 plan + 1 per step + 1 per revision (typically 5 to 12)
- Latency
- medium
- Complexity
- low
3How does a goal become a plan, and the plan become a result?
The planner writes ordered steps into the plan. A setting decides whether this run executes it or hands it to the next stage. If it executes, the executor takes one step at a time and calls the planner back when a result breaks the plan.
- Step 1 of 5
The plan comes first
For "Prepare a pricing review for our three plans", the planner writes steps such as pull usage per plan, compare with competitors, model two price changes, write the memo. Each step states its expected result.
- Step 2 of 5
Execute here, or hand off
A setting fixed by whoever runs the stage decides. In hand-off mode the plan leaves as is, for a person to approve or a later stage to execute.
- Step 3 of 5
One step at a time
In execute mode, the executor reads the next pending step, does it and writes the result back into the plan, then moves to the next.
- Step 4 of 5
A result changes the picture
If a result contradicts the plan, for example usage data shows one plan has no customers, the executor stops and the planner rewrites the remaining steps.
- Step 5 of 5
The result
When every step is done, the step results are assembled into the deliverable, with the final plan attached so readers see how it was produced.
What each part does
- Goal
- The goal, the constraints, and whether this run should execute the plan or only write it.
- Planner
- Writes the ordered steps, each with its expected result. Rewrites the remaining steps on request.
- Plan
- The step list with the status and result of each step.
- Execute here?
- A fixed setting, not a model choice. Either this run executes the plan, or it hands the plan on.
- Plan only
- The written plan, handed to the next stage. Nothing has been executed.
- Executor
- Carries out the next pending step, records its result, and flags a result that contradicts the plan.
- Result
- The deliverable assembled from the step results, with the final plan.
- Planner → Plan: ordered steps
- Execute here? → Plan only: hand off the plan
- Execute here? → Executor: execute here
- Plan → Executor: next pending step
- Executor → Plan: step result
- Executor → Executor: steps remain, step limit not hit
- Executor → Planner: result breaks the plan, revisions left
- Executor → Result: all steps done
Where it connects
A goal with its constraints and the expected deliverable, plus the mode, execute or hand off. Without a mode, the stage executes.
When: The run was set to execute and every step of the final plan is done.
The deliverable built from the step results, followed by the final plan with each step's status and any revisions made.
When: The run was set to hand off. It stops as soon as the plan is written.
Ordered steps, each with its purpose, its expected result and what it depends on. No step has been executed.
The current step list with a status per step (pending, done, replaced) and the result of each finished step.
4What do I ask my assistant to set up?
The agents to launch
Planner
Write a plan of three to ten ordered steps for the goal. For each step give its purpose, its expected result and the steps it depends on. When asked to revise, keep finished steps unchanged and rewrite only the pending ones, using the new result. Do no step yourself.
Sees: The goal, the constraints and, on revision, the plan with every finished step's result.
Executor
Carry out exactly one step and report its result. If the result contradicts what the step expected, or makes a later step pointless, say so plainly and stop instead of improvising.
Sees: The current step, the results of the steps it depends on, and the goal in one line. Not the full plan history.
A prompt you can paste
Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.
You are the orchestrator of a multi-agent workflow that follows the "Planning" architecture. Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it. # Task [Describe your task here] # Planning Write the steps first, then work through them in order. Input: the task above. It must provide: A goal with its constraints and the expected deliverable, plus the mode, execute or hand off. Without a mode, the stage executes. If something essential is missing, ask for it before starting. Agents to launch: - Planner: Write a plan of three to ten ordered steps for the goal. For each step give its purpose, its expected result and the steps it depends on. When asked to revise, keep finished steps unchanged and rewrite only the pending ones, using the new result. Do no step yourself. Context for this agent: The goal, the constraints and, on revision, the plan with every finished step's result. - Executor: Carry out exactly one step and report its result. If the result contradicts what the step expected, or makes a later step pointless, say so plainly and stop instead of improvising. Context for this agent: The current step, the results of the steps it depends on, and the goal in one line. Not the full plan history. Procedure: 1. Restate the goal and the constraints, and decide the mode. If the input names no mode, execute here. 2. Launch the planner and store its steps as the plan. 3. In hand-off mode, return the plan and stop. 4. In execute mode, launch the executor on the first pending step with the results it depends on. Record the result in the plan. 5. If the executor flags a contradiction, send the plan back to the planner for a revision of the pending steps. Allow at most 2 revisions. 6. Repeat until every step is done, then assemble the deliverable from the step results. Stop rule: Stop when every step is done, after 2 revisions with a step still contradicting the plan, or after 15 executed steps. In hand-off mode, stop once the plan is written. Exits: - `result`, when: The run was set to execute and every step of the final plan is done. Deliver: The deliverable built from the step results, followed by the final plan with each step's status and any revisions made. - `plan`, when: The run was set to hand off. It stops as soon as the plan is written. Deliver: Ordered steps, each with its purpose, its expected result and what it depends on. No step has been executed. # Final deliverable In execute mode, the deliverable and the final plan with each step's status. In hand-off mode, the plan only, labelled as not executed.
The same thing in code
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel
EXECUTE_HERE = True # the mode gate: a fixed setting, not a model choice
MAX_REVISIONS, MAX_EXECUTED = 2, 15
PLANNER = ("Write a plan of three to ten ordered steps for the goal, each with its purpose, expected "
"result and the steps it depends on. When revising, keep finished steps unchanged and "
"rewrite only the pending ones. Do no step yourself.")
EXECUTOR = ("Carry out exactly one step and report its result. If the result contradicts what the step "
"expected, or makes a later step pointless, say so plainly instead of improvising.")
class PlanStep(BaseModel):
id: int
purpose: str
expected: str
depends_on: list[int]
class Plan(BaseModel):
steps: list[PlanStep]
class Report(BaseModel):
result: str
contradicts_plan: bool
reason: str
class State(TypedDict):
goal: str
plan: Plan | None
results: dict[int, str] # the plan store: a step with a result is done
surprise: str
revisions: int
executed: int
model = init_chat_model("anthropic:claude-sonnet-5-5")
planner_model, executor_model = model.with_structured_output(Plan), model.with_structured_output(Report)
def pending(state: State) -> list[PlanStep]:
return [s for s in state["plan"].steps if s.id not in state["results"]] if state["plan"] else []
async def planner(state: State) -> dict:
prompt, old = f"Goal and constraints:\n{state['goal']}", state["plan"]
if old: # revision: finished steps with their results, plus the surprise
done = "\n".join(f"{s.id}. {s.purpose} -> {state['results'][s.id]}" for s in old.steps if s.id in state["results"])
prompt += f"\n\nFinished steps, keep unchanged:\n{done}\n\nSurprise: {state['surprise']}\nRewrite the pending steps."
plan = Plan.model_validate(await planner_model.ainvoke([SystemMessage(PLANNER), HumanMessage(prompt)]))
if old:
kept = [s for s in old.steps if s.id in state["results"]]
plan = Plan(steps=kept + [s for s in plan.steps if s.id not in state["results"]])
return {"plan": plan, "surprise": "", "revisions": state["revisions"] + (1 if old else 0)}
async def executor(state: State) -> dict:
step = pending(state)[0]
inputs = "\n".join(f"{d}: {state['results'][d]}" for d in step.depends_on if d in state["results"])
# one step, its inputs and the goal in one line: not the plan history
prompt = f"Goal: {state['goal'].splitlines()[0]}\nStep: {step.purpose}\nExpected: {step.expected}\nInputs:\n{inputs or '(none)'}"
report = Report.model_validate(await executor_model.ainvoke([SystemMessage(EXECUTOR), HumanMessage(prompt)]))
if report.contradicts_plan:
return {"surprise": f"step {step.id}: {report.reason}", "executed": state["executed"] + 1}
return {"results": {**state["results"], step.id: report.result}, "executed": state["executed"] + 1}
def after_executor(state: State) -> str:
if state["surprise"]:
return "planner" if state["revisions"] < MAX_REVISIONS else END
return "executor" if pending(state) and state["executed"] < MAX_EXECUTED else END
builder = StateGraph(State)
builder.add_node("planner", planner)
builder.add_node("executor", executor)
builder.add_edge(START, "planner")
builder.add_conditional_edges("planner", lambda s: "executor" if EXECUTE_HERE else END, ["executor", END])
builder.add_conditional_edges("executor", after_executor, ["executor", "planner", END])
graph = builder.compile()
async def run(task: str) -> dict:
s = await graph.ainvoke({"goal": task, "plan": None, "results": {}, "surprise": "", "revisions": 0, "executed": 0})
steps = s["plan"].steps if s["plan"] else []
if not EXECUTE_HERE:
return {"plan": [p.model_dump() for p in steps], "executed": False}
return {
"deliverable": "\n".join(s["results"][p.id] for p in steps if p.id in s["results"]),
"plan": [{**p.model_dump(), "status": "done" if p.id in s["results"] else "pending"} for p in steps],
"revisions": s["revisions"],
"all_done": len(s["results"]) == len(steps),
"open_contradiction": s["surprise"],
}
The deliverable here is the step results joined in order; add a final assembly call if your goal needs one composed document.
from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel
EXECUTE_HERE = True # the mode gate: a fixed setting, not a model choice
MAX_REVISIONS, MAX_EXECUTED = 2, 15
class PlanStep(BaseModel):
id: int
purpose: str
expected: str
depends_on: list[int]
class Plan(BaseModel):
steps: list[PlanStep]
class Report(BaseModel):
result: str
contradicts_plan: bool
reason: str
AGENTS = {
"planner": AgentDefinition(
description="Writes or revises the ordered plan.",
prompt="Write a plan of three to ten ordered steps for the goal, each with its purpose, expected "
"result and the steps it depends on. When revising, keep finished steps unchanged and "
"rewrite only the pending ones. Do no step yourself.",
),
"executor": AgentDefinition(
description="Carries out exactly one plan step.",
prompt="Carry out exactly one step and report its result. If the result contradicts what the step "
"expected, or makes a later step pointless, say so plainly instead of improvising.",
),
}
async def delegate[T: BaseModel](agent: str, message: str, schema: type[T]) -> T:
# one fresh session per call, so each sub-agent sees only the message it is given
options = ClaudeAgentOptions(
agents=AGENTS,
allowed_tools=["Agent"],
output_format={"type": "json_schema", "schema": schema.model_json_schema()},
)
prompt = f"Delegate this to the {agent} agent, passing it verbatim, and return its reply unchanged:\n\n{message}"
async for msg in query(prompt=prompt, options=options):
if isinstance(msg, ResultMessage):
return schema.model_validate(msg.structured_output)
raise RuntimeError("no result")
async def run(task: str) -> dict:
plan = await delegate("planner", f"Goal and constraints:\n{task}", Plan)
if not EXECUTE_HERE:
return {"plan": plan.model_dump(), "executed": False}
results: dict[int, str] = {} # the plan store: a step with a result is done
revisions, executed, surprise = 0, 0, ""
while executed < MAX_EXECUTED:
todo = [s for s in plan.steps if s.id not in results]
if not todo:
break
step = todo[0]
inputs = "\n".join(f"{d}: {results[d]}" for d in step.depends_on if d in results)
# one step, its inputs and the goal in one line: not the plan history
prompt = f"Goal: {task.splitlines()[0]}\nStep: {step.purpose}\nExpected: {step.expected}\nInputs:\n{inputs or '(none)'}"
report = await delegate("executor", prompt, Report)
executed += 1
if not report.contradicts_plan:
results[step.id] = report.result
continue
surprise = f"step {step.id}: {report.reason}"
if revisions == MAX_REVISIONS: # 2 revisions spent and the plan still breaks
break
revisions += 1
done = [s for s in plan.steps if s.id in results]
finished = "\n".join(f"{s.id}. {s.purpose} -> {results[s.id]}" for s in done)
revise = f"Goal and constraints:\n{task}\n\nFinished steps, keep unchanged:\n{finished}\n\nSurprise: {surprise}\nRewrite the pending steps."
revised = await delegate("planner", revise, Plan)
plan, surprise = Plan(steps=done + [s for s in revised.steps if s.id not in results]), ""
return {
"deliverable": "\n".join(results[s.id] for s in plan.steps if s.id in results),
"plan": [{**s.model_dump(), "status": "done" if s.id in results else "pending"} for s in plan.steps],
"revisions": revisions,
"all_done": len(results) == len(plan.steps),
"open_contradiction": surprise,
}
The deliverable here is the step results joined in order; add a final assembly call if your goal needs one composed document.
from agents import Agent, Runner
from pydantic import BaseModel
EXECUTE_HERE = True # the mode gate: a fixed setting, not a model choice
MAX_REVISIONS, MAX_EXECUTED = 2, 15
class PlanStep(BaseModel):
id: int
purpose: str
expected: str
depends_on: list[int]
class Plan(BaseModel):
steps: list[PlanStep]
class Report(BaseModel):
result: str
contradicts_plan: bool
reason: str
planner = Agent(
name="Planner",
instructions="Write a plan of three to ten ordered steps for the goal, each with its purpose, expected "
"result and the steps it depends on. When revising, keep finished steps unchanged and "
"rewrite only the pending ones. Do no step yourself.",
output_type=Plan,
)
executor = Agent(
name="Executor",
instructions="Carry out exactly one step and report its result. If the result contradicts what the step "
"expected, or makes a later step pointless, say so plainly instead of improvising.",
output_type=Report,
)
async def run(task: str) -> dict:
plan = (await Runner.run(planner, f"Goal and constraints:\n{task}")).final_output_as(Plan)
if not EXECUTE_HERE:
return {"plan": plan.model_dump(), "executed": False}
results: dict[int, str] = {} # the plan store: a step with a result is done
revisions, executed, surprise = 0, 0, ""
while executed < MAX_EXECUTED:
todo = [s for s in plan.steps if s.id not in results]
if not todo:
break
step = todo[0]
inputs = "\n".join(f"{d}: {results[d]}" for d in step.depends_on if d in results)
# one step, its inputs and the goal in one line: not the plan history
prompt = f"Goal: {task.splitlines()[0]}\nStep: {step.purpose}\nExpected: {step.expected}\nInputs:\n{inputs or '(none)'}"
report = (await Runner.run(executor, prompt)).final_output_as(Report)
executed += 1
if not report.contradicts_plan:
results[step.id] = report.result
continue
surprise = f"step {step.id}: {report.reason}"
if revisions == MAX_REVISIONS: # 2 revisions spent and the plan still breaks
break
revisions += 1
done = [s for s in plan.steps if s.id in results]
finished = "\n".join(f"{s.id}. {s.purpose} -> {results[s.id]}" for s in done)
revise = f"Goal and constraints:\n{task}\n\nFinished steps, keep unchanged:\n{finished}\n\nSurprise: {surprise}\nRewrite the pending steps."
revised = (await Runner.run(planner, revise)).final_output_as(Plan)
plan, surprise = Plan(steps=done + [s for s in revised.steps if s.id not in results]), ""
return {
"deliverable": "\n".join(results[s.id] for s in plan.steps if s.id in results),
"plan": [{**s.model_dump(), "status": "done" if s.id in results else "pending"} for s in plan.steps],
"revisions": revisions,
"all_done": len(results) == len(plan.steps),
"open_contradiction": surprise,
}
The deliverable here is the step results joined in order; add a final assembly call if your goal needs one composed document.
import { anthropic } from '@ai-sdk/anthropic';
import { Output, ToolLoopAgent } from 'ai';
import { z } from 'zod';
const EXECUTE_HERE = true; // the mode gate: a fixed setting, not a model choice
const MAX_REVISIONS = 2;
const MAX_EXECUTED = 15;
const model = anthropic('claude-sonnet-5-5');
const planSchema = z.object({
steps: z.array(z.object({ id: z.number().int(), purpose: z.string(), expected: z.string(), dependsOn: z.array(z.number().int()) })),
});
type Plan = z.infer<typeof planSchema>;
const planner = new ToolLoopAgent({
model,
instructions:
'Write a plan of three to ten ordered steps for the goal, each with its purpose, expected ' +
'result and the steps it depends on. When revising, keep finished steps unchanged and ' +
'rewrite only the pending ones. Do no step yourself.',
output: Output.object({ schema: planSchema }),
});
const executor = new ToolLoopAgent({
model,
instructions:
'Carry out exactly one step and report its result. If the result contradicts what the step ' +
'expected, or makes a later step pointless, say so plainly instead of improvising.',
output: Output.object({ schema: z.object({ result: z.string(), contradictsPlan: z.boolean(), reason: z.string() }) }),
});
export async function run(task: string) {
let plan: Plan = (await planner.generate({ prompt: `Goal and constraints:\n${task}` })).output;
if (!EXECUTE_HERE) return { plan, executed: false };
const results = new Map<number, string>(); // the plan store: a step with a result is done
let revisions = 0;
let surprise = '';
for (let executed = 0; executed < MAX_EXECUTED; executed++) {
const step = plan.steps.find((s) => !results.has(s.id));
if (!step) break;
const inputs = step.dependsOn.filter((d) => results.has(d)).map((d) => `${d}: ${results.get(d)}`).join('\n');
// one step, its inputs and the goal in one line: not the plan history
const { output: report } = await executor.generate({
prompt: `Goal: ${task.split('\n')[0]}\nStep: ${step.purpose}\nExpected: ${step.expected}\nInputs:\n${inputs || '(none)'}`,
});
if (!report.contradictsPlan) {
results.set(step.id, report.result);
continue;
}
surprise = `step ${step.id}: ${report.reason}`;
if (revisions === MAX_REVISIONS) break; // 2 revisions spent and the plan still breaks
revisions++;
const done = plan.steps.filter((s) => results.has(s.id));
const finished = done.map((s) => `${s.id}. ${s.purpose} -> ${results.get(s.id)}`).join('\n');
const { output: revised } = await planner.generate({
prompt: `Goal and constraints:\n${task}\n\nFinished steps, keep unchanged:\n${finished}\n\nSurprise: ${surprise}\nRewrite the pending steps.`,
});
plan = { steps: [...done, ...revised.steps.filter((s) => !results.has(s.id))] };
surprise = '';
}
return {
deliverable: plan.steps.filter((s) => results.has(s.id)).map((s) => results.get(s.id)).join('\n'),
plan: plan.steps.map((s) => ({ ...s, status: results.has(s.id) ? 'done' : 'pending' })),
revisions,
allDone: results.size === plan.steps.length,
openContradiction: surprise,
};
}
The deliverable here is the step results joined in order; add a final assembly call if your goal needs one composed document.
Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.
What goes wrong
- Plans with vague steps such as "research the market" cannot be checked. Each step needs an expected result.
- An executor that silently works around a surprise hides the moment the plan stopped being true. Make it stop and report.
- Rewriting finished steps during a revision throws away paid work. Revise only pending steps.
Chain it
Its result can feed
- Reflection direct
Treat the executed deliverable as an existing result to improve: score it against the criteria and rewrite it until it passes, keeping the step record as context.
- ReAct conditional
Condition: The plan calls for several dependent tool actions to fulfil the original task.
- Supervisor & Specialists direct
Treat each plan step as a subtask to assign to a specialist, respecting the stated dependencies, then merge the results.
- Plan–Execute–Verify direct
Take the written plan as given, add an acceptance check to each step, and execute it step by step with verification.
- Dry Run conditional
Condition: Only when the task calls for side-effecting operations on an external system, so the plan's steps are actions to simulate and approve.
- Chain of Verification conditional
Condition: Only when the planning run's deliverable is an answer rather than a document.
- Debate conditional
Condition: Only when the planning run's deliverable is an answer rather than a document.
- Constitutional Critique direct
Treat the deliverable as the text to check rule by rule against the constitution, revising only the rules it fails.
- SWE Agent conditional
Condition: Only when the task is a code change on a named repository.
- Computer Use conditional
Condition: Only when the task's goal must be reached through a graphical interface such as a web portal or desktop app.
- Human Approval Gate conditional
Condition: The link applies when the handed-off plan contains steps that perform consequential actions on the approval list, such as payments, deletions or external changes.
- Session-Loop Harness conditional
Condition: The link applies when the task is to build a software project from an empty repository.
- Shared Task List direct
Turn each plan step into a task, keep its stated dependencies, and let teammates claim unblocked tasks.
- Textual Backpropagation direct
Treat A's deliverable as an existing result to improve, and score and refine it against the configured criteria.
- Recursive Agent Harness direct
Make the plan's steps the phases of the script, and run them through sub-agents in the dependency order given.
- Recoverable Execution conditional
Condition: The link applies when every step of the plan acts only within a workspace the harness can save and restore, with no external side effects.
Source
- Wang et al., 2023. Plan-and-Solve Prompting: Improving Zero-Shot Chain-of-Thought Reasoning by Large Language Models