Agentic Architectures

Catalogue / Tools & Action

Planning

Write the steps first, then work through them in order

Shape
pipeline
Model calls
1 plan + 1 per step + 1 per revision (typically 5 to 12)
Latency
medium
Complexity
low

Also known as Plan-and-Execute, Plan-and-Solve

1

Why 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.
2

When 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

What it costs

Model calls
1 plan + 1 per step + 1 per revision (typically 5 to 12)
Latency
medium
Complexity
low
3

How 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.

hand off theplanexecute heresteps remain,step limit nothitresult breaksthe plan,revisions leftall steps doneGoal: The goal, the constraints, and whether this run should execute the plan or only write it.GoalPlanner: Writes the ordered steps, each with its expected result. Rewrites the remaining steps on request.PlannerPlan: The step list with the status and result of each step.PlanExecute here?: A fixed setting, not a model choice. Either this run executes the plan, or it hands the plan on.Execute here?Plan only: The written plan, handed to the next stage. Nothing has been executed.Plan onlyExecutor: Carries out the next pending step, records its result, and flags a result that contradicts the plan.ExecutorResult: The deliverable assembled from the step results, with the final plan.Result
  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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

Entry
goal
Task

A goal with its constraints and the expected deliverable, plus the mode, execute or hand off. Without a mode, the stage executes.

Exit
result
AnswerDocument

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.

Exit
plan
Plan

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.

Working memory for one run
working-plan
Plan

The current step list with a status per step (pending, done, replaced) and the result of each finished step.

4

What 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.

Framework-agnostic prompt
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

LangGraph, python, package langgraph
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.

Claude Agent SDK, python, package claude-agent-sdk
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.

OpenAI Agents SDK, python, package openai-agents
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.

Vercel AI SDK, typescript, package ai
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

Source

  • Wang et al., 2023. Plan-and-Solve Prompting: Improving Zero-Shot Chain-of-Thought Reasoning by Large Language Models