08C.1 Task Decomposition and Plan-as-Artifact

Agents & multimodalLesson 1 of 35,209 words5 parts
Module 08C · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3

An agent that has to do ten things in a row will, sooner or later, forget one of them. The fix is not a better prompt. The fix is to break the job into small steps, write the steps down as data the program owns, and check each step against the real world before moving on. In this lesson you build that in plain Python: a plan model, a validator that rejects bad plans, a scripted planner that repairs its own mistakes when the validator complains, and a runner that keeps its plan, todo list and notes in files it re-reads every turn. It is the first of three planning lessons: this one is about making the plan, 08C.2 is about changing it when reality disagrees and fitting it to budgets, and 08C.3 is about surviving a crash.

What you'll learn

  • What task decomposition is and four ways to do it: top-down, goal-backward, by dependency graph, and by risk
  • How big a step should be, and why every step needs a verifiable sub-goal (a done_when check that reads the world, not the model's claim)
  • Plans as data: a JSON plan file, a markdown todo file and an append-only scratchpad that the agent reads and rewrites each turn
  • How to validate a plan before running it: unknown tools, missing checks, oversized steps, dependency cycles
  • How to show the model its own validation errors so it repairs the plan, and how to get a structured plan from OpenAI and Anthropic
  • What to measure when you evaluate plans, and a tiny eval design for it

What you don't need

  • API keys. Every runnable sample uses a scripted fake planner and plain Python (standard library only). The OpenAI and Anthropic sample in Part 4 needs keys and is labelled illustrative.
  • Docker or any service.
  • LangGraph or any framework. Plan-and-execute as a pattern (planner, executor, replanner) is already taught in 08A.10, Part 3. This lesson does not repeat it. It teaches the layer underneath: how to break work down and how to store the plan.

Setup

As of 1 December 2026. Python 3.11 or newer. The runnable code in Parts 2 to 4 uses only the standard library, so there is nothing to install. For the optional provider sample in 4.4:

bash
uv add openai anthropic
# or: pip install openai anthropic

Each code block starts with a comment giving its file name. Save the files in one folder (plan_model.py, decompose_demo.py, plan_files.py) and run them with python plan_files.py. The running example is the support assistant from Module 08A: look up an order, find the refund policy, refund or open a ticket, tell the customer. All tools are fakes over in-memory data.


What you must be able to do after this lesson#

  • Split a goal into steps that are bounded, verifiable and independent enough
  • Write a done_when check for a step that reads the world instead of the model's claim
  • Store a plan as data (JSON, a generated todo file and an append-only scratchpad) and re-read it every turn
  • Validate a plan for unknown tools, missing checks, oversized steps and dependency cycles before running it
  • Feed validation errors back to a planner with a capped retry
  • Measure plan validity, step success and task success per dollar against a plain loop

Why this matters for an AI engineer#

A single model call can answer a question. A task such as "migrate this service", "research this market" or "process this month's refunds" takes dozens of calls over minutes or hours. Without a plan the agent re-decides everything each turn, drifts from the goal and cannot tell you how far along it is. With a plan stored as data, you can show progress, resume after a crash, cap the work, let a human edit it, and score it in an eval.

You'll hear... You'll understand it after...
"Break the task down first." Part 2: Decomposition strategies
"Each step needs an exit criterion." 2.4 Verifiable sub-goals
"Keep the plan in a file, not in the chat." Part 3: Plans as data
"The agent keeps a todo list and a scratchpad." 3.3 Todo files and scratchpads
"The planner returned a plan with a cycle." Part 4: Validating a plan
"How do we know the plan was any good?" Part 5: Evaluate it

Part 1: What a plan is for#

1.1 Decomposition in one paragraph#

Task decomposition means splitting one goal that is too big to do in one go into smaller sub-tasks that are each easy to do and easy to check. People do it all the time ("to cook dinner I need to shop, chop, cook, serve"). An agent needs it for three reasons:

  1. Reliability. Each model call is more accurate on a small, clear step than on a large vague one. Errors still compound (see 10A.7, 1.3), but a small step is easier to verify and retry.
  2. Control. Small steps are the unit you can budget, approve, retry, skip and resume.
  3. Visibility. A list of steps with statuses is a progress bar. A transcript is not.

1.2 When not to plan#

Planning costs model calls and adds a stale-plan risk. 08A.10, 3.4 compares plan-and-execute with a plain ReAct loop and says when each wins. The short version: skip the plan when the task is two or three tool calls, or when each next step depends on what the last one found. Plan when the work has an enumerable shape, when you need progress you can show, or when you need the plan as an auditable record.

1.3 Where this fits#

flowchart LR
    G([goal]) --> D["decompose<br/>(08C.1)"]
    D --> V{"validate<br/>(08C.1)"}
    V -- "problems" --> D
    V -- "ok" --> S["plan as files<br/>(08C.1)"]
    S --> X["execute step<br/>(bounded loop, 08A.2)"]
    X --> C{"done_when<br/>check passes?"}
    C -- "yes" --> S
    C -- "no" --> R["recover / replan<br/>(08C.2)"]
    S -. "checkpoint<br/>(08C.3)" .-> S

Part 2: Decomposition strategies#

2.1 Top-down#

Start from the goal and split it, then split each piece that is still too big, until every leaf is a step you could do in one bounded loop. This is the default and the one models do naturally.

text
Goal: refund order A17 if allowed, else open a ticket, then tell the customer
├── understand the case
│   ├── load order A17
│   └── find the refund policy
├── act
│   └── refund (if allowed) or open a ticket
└── communicate
    └── email the customer the outcome

Stop splitting when a step passes the three tests in 2.3. Splitting past that point is a cost without a benefit: more steps mean more boundaries, and every boundary is a place to lose context.

2.2 Goal-backward, dependency graphs and risk#

Three other angles often give a better plan than pure top-down.

Goal-backward. Ask "what must be true just before the goal is reached?" and repeat. For the refund: the customer must have been told, which needs a recorded outcome, which needs either a refund or a ticket, which needs the policy and the order. Reading the chain backwards gives you the order of the steps and exposes missing preconditions. Use it when the end state is clear and the route is not.

Dependency graph. Write each step with the ids it depends on. The steps form a directed acyclic graph (DAG: arrows go one way and never loop back). A DAG tells you three things a flat list hides:

  • which steps may run at the same time (steps with no dependency on each other),
  • the longest chain of waiting steps (your minimum latency),
  • which step blocks the most others (where a failure hurts most).

If the graph has a cycle (A needs B and B needs A), the plan cannot be run at all. Part 4 checks for that.

Risk-first ordering. Within what the graph allows, put the steps that are likely to fail, cost the most, or cannot be undone late, and put cheap checks early. Load the order and read the policy (cheap, read-only) before you issue a refund (costly, hard to undo). If the policy says no, you have lost nothing. This is the same instinct as "fail fast" in a build pipeline.

2.3 How big should a step be?#

There is no universal number. Use three tests:

Test Question If it fails
Bounded Can one agent loop finish it in a handful of tool calls (say 1 to 4)? Split it
Verifiable Can code or a person check, without asking the model, whether it is done? Add a done_when check, or merge it into a neighbour that has one
Independent enough Does its input come only from the goal and from named earlier steps? Add the missing depends_on, or pass the data explicitly

Too large and the step is a mini-agent with no plan inside it. Too small ("open the order", "read field total", "copy field total") and you pay a model call and a checkpoint for nothing. A practical range is 3 to 8 steps for a task an agent finishes in minutes, with each step costing 1 to 4 tool calls. If a plan needs more than about 8 to 12 steps, plan in levels: a short top-level plan whose steps are themselves planned when reached.

2.4 Verifiable sub-goals: the done_when check#

The most useful field in a plan is the one the model does not control: done_when, the name of a check function that inspects the world. The model saying "I refunded the order" is a claim. The payments table containing a refund for A17 is evidence.

text
step "refund"   done_when: refund_recorded   ->  payments table has a 42.00 refund for A17
step "notify"   done_when: customer_notified ->  outbox has an email to the customer

This is the same rule that 10A.7, Part 3 applies to grading: read the world, not the model's account of it. Here you apply it during the run, so a step that claims success but did not succeed is caught at once and routed to recovery (08C.2) instead of poisoning every later step.

Kinds of check, cheapest first: a state lookup (row exists, file exists), a test run (exit code 0), a schema check on the output, a rule over the output (contains a citation), and last a model judge. Prefer the cheap ones. Some steps ("write a friendly reply") have no cheap check. Keep a judge for those, and say so in the plan.


Part 3: Plans as data#

08A.10, 3.2 shows the plan as a list[PlanStep] you own, and 08A.10, 5.4 shows a todo tool. This part extends both with dependencies, verifiable checks, a JSON-or-markdown choice and a runner that re-reads its files every turn.

3.1 The plan model#

08A.10, 3.2 makes the key point: the plan is state you own, not text buried in the message history where context trimming can silently drop it. This part builds that state with dependencies, checks and size estimates, which the PlanStep in 08A.10 does not have.

python
# plan_model.py: the plan as data, plus a validator that returns readable problems
from __future__ import annotations

import json
from dataclasses import asdict, dataclass, field


@dataclass
class Step:
    id: str
    goal: str                      # what this step achieves, in one sentence
    depends_on: list[str] = field(default_factory=list)
    tools: list[str] = field(default_factory=list)
    done_when: str = ""            # name of a check function: the verifiable sub-goal
    est_tool_calls: int = 1        # step-size estimate
    status: str = "pending"        # pending | running | done | failed | skipped
    result: str | None = None


@dataclass
class Plan:
    goal: str
    steps: list[Step]
    version: int = 1

    def to_json(self) -> str:
        return json.dumps(asdict(self), indent=2)

    @staticmethod
    def from_json(text: str) -> "Plan":
        raw = json.loads(text)
        return Plan(raw["goal"], [Step(**s) for s in raw["steps"]], raw.get("version", 1))

    def by_id(self) -> dict[str, Step]:
        return {s.id: s for s in self.steps}


def validate_plan(plan: Plan, known_tools: set[str], known_checks: set[str],
                  max_steps: int = 8, max_tool_calls_per_step: int = 4) -> list[str]:
    """Return a list of problems. An empty list means the plan is valid."""
    problems: list[str] = []
    ids = [s.id for s in plan.steps]
    if not plan.steps:
        return ["plan has no steps"]
    if len(plan.steps) > max_steps:
        problems.append(f"too many steps: {len(plan.steps)} > {max_steps}")
    for dup in {i for i in ids if ids.count(i) > 1}:
        problems.append(f"duplicate step id {dup!r}")
    for s in plan.steps:
        for d in s.depends_on:
            if d not in ids:
                problems.append(f"{s.id}: depends on unknown step {d!r}")
            if d == s.id:
                problems.append(f"{s.id}: depends on itself")
        for t in s.tools:
            if t not in known_tools:
                problems.append(f"{s.id}: unknown tool {t!r}")
        if not s.done_when:
            problems.append(f"{s.id}: no done_when check (sub-goal is not verifiable)")
        elif s.done_when not in known_checks:
            problems.append(f"{s.id}: unknown check {s.done_when!r}")
        if s.est_tool_calls > max_tool_calls_per_step:
            problems.append(f"{s.id}: too big ({s.est_tool_calls} tool calls > {max_tool_calls_per_step}); split it")
    cycle = find_cycle(plan)
    if cycle:
        problems.append("dependency cycle: " + " -> ".join(cycle))
    return problems


def find_cycle(plan: Plan) -> list[str] | None:
    graph = {s.id: [d for d in s.depends_on if d in {x.id for x in plan.steps}] for s in plan.steps}
    state: dict[str, int] = {}   # 1 = visiting, 2 = done
    stack: list[str] = []

    def visit(n: str) -> list[str] | None:
        state[n] = 1
        stack.append(n)
        for m in graph[n]:
            if state.get(m) == 1:
                return stack[stack.index(m):] + [m]
            if m not in state:
                found = visit(m)
                if found:
                    return found
        stack.pop()
        state[n] = 2
        return None

    for n in graph:
        if n not in state:
            found = visit(n)
            if found:
                return found
    return None


def layers(plan: Plan) -> list[list[str]]:
    """Group steps into layers; steps in one layer do not depend on each other."""
    remaining = {s.id: set(s.depends_on) for s in plan.steps}
    out: list[list[str]] = []
    done: set[str] = set()
    while remaining:
        ready = sorted(i for i, deps in remaining.items() if deps <= done)
        if not ready:
            raise ValueError("cycle: cannot layer the plan")
        out.append(ready)
        done.update(ready)
        for i in ready:
            del remaining[i]
    return out

Three design choices to notice:

  • Everything is a plain dataclass that round-trips through JSON. There is no hidden object state, so a plan can be saved, diffed, edited by a person and loaded again.
  • status and result live on the step. Progress is the data, not a separate counter.
  • validate_plan returns a list of readable problems instead of raising on the first one. A list is what you want to show a person or feed back to a model.

3.2 JSON plan file or markdown plan file?#

Both are common. Pick by who edits it.

JSON (plan.json) Markdown (PLAN.md, todo.md)
Best reader Your code The model and the human
Validation Exact (schema, types) Weak; the model may break the format
Human editing Possible, easy to break Easy
Diffs Fine Very readable
Token cost Higher (quotes, braces) Lower

A common and sturdy setup is both: JSON is the source of truth that your code validates, and a markdown todo is generated from it for the model and the human to read. If you let the model edit a markdown file directly, parse it back and validate it every time, and reject edits that break the format. Never trust a hand-edited or model-edited plan file without running it through the validator.

3.3 Todo files and scratchpads#

Three small files do most of the work in long tasks. They differ by purpose.

File Holds Who writes Written how
plan.json The steps, dependencies, checks, statuses Planner, then the runner Rewritten whole, atomically
todo.md A short human-readable view of the plan The runner (generated) Rewritten whole each turn
scratchpad.md Free notes: findings, decisions, dead ends The agent Append-only

The scratchpad is where the agent keeps things it learned that do not belong in a step result ("the customer's account is on the legacy plan", "the policy page has two versions, use the 2026 one"). Append-only is deliberate: it is cheap, it never loses earlier notes, and a crash cannot corrupt it. If it grows too long, summarise it into a fresh file instead of editing it in place (see 04.7 for context management over long runs).

The agent re-reads these files at the start of each turn instead of trusting its memory of them. That one habit gives you three things: a person can edit the plan between turns and the agent will pick it up, a restarted process can continue from the files (08C.3), and context trimming cannot drop the plan.

3.4 The read, act, check, rewrite loop#

Now the runner. It is deliberately boring: read the plan file, pick the next ready step, run it, check the result, write the files.

Below, fake_execute stands in for "run one bounded agent loop for this step" (08A.2). CHECKS are the verifiable sub-goals: they read the WORLD dictionary. The plan comes from the validated planner you will meet in Part 4, so the file imports it. Read run() first.

python
# plan_files.py: the plan lives in files the agent re-reads every turn: plan.json, todo.md, scratchpad.md
import json
import tempfile
from pathlib import Path

from decompose_demo import make_valid_plan  # reuses the validated plan from the last section
from plan_model import Plan

WORLD: dict = {}

CHECKS = {   # verifiable sub-goals: they read the WORLD, not the model's claim
    "order_loaded": lambda: "order" in WORLD,
    "policy_found": lambda: "policy" in WORLD,
    "refund_recorded": lambda: WORLD.get("refund") == 42.0,
    "customer_notified": lambda: bool(WORLD.get("emails")),
}


def fake_execute(step_id: str) -> None:
    """Stands in for 'run a bounded agent loop for this step'."""
    if step_id == "load":
        WORLD["order"] = {"id": "A17", "total": 42.0}
    elif step_id == "policy":
        WORLD["policy"] = "refunds allowed within 30 days"
    elif step_id == "refund":
        WORLD["refund"] = WORLD["order"]["total"]
    elif step_id == "notify":
        WORLD.setdefault("emails", []).append("Your refund of 42.00 is on its way.")


def render_todo(plan: Plan) -> str:
    box = {"done": "x", "skipped": "-", "failed": "!", "running": "~", "pending": " "}
    lines = [f"# TODO (plan v{plan.version}): {plan.goal}"]
    for s in plan.steps:
        lines.append(f"- [{box[s.status]}] {s.id}: {s.goal}")
    return "\n".join(lines) + "\n"


def save(plan: Plan, folder: Path) -> None:
    tmp = folder / "plan.json.tmp"
    tmp.write_text(plan.to_json())
    tmp.replace(folder / "plan.json")          # atomic swap (details in 08C.3)
    (folder / "todo.md").write_text(render_todo(plan))


def note(folder: Path, text: str) -> None:
    with (folder / "scratchpad.md").open("a") as f:   # append-only notes: cheap and never lost
        f.write(text + "\n")


def run(folder: Path) -> None:
    for turn in range(10):
        plan = Plan.from_json((folder / "plan.json").read_text())   # re-read every turn
        done = {s.id for s in plan.steps if s.status in ("done", "skipped")}
        ready = [s for s in plan.steps if s.status == "pending" and set(s.depends_on) <= done]
        if not ready:
            break
        step = ready[0]
        fake_execute(step.id)
        ok = CHECKS[step.done_when]()
        step.status, step.result = ("done", "check passed") if ok else ("failed", "check failed")
        note(folder, f"turn {turn}: {step.id} -> {step.status}")
        save(plan, folder)
        if not ok:
            break


folder = Path(tempfile.mkdtemp(prefix="plan_"))
print("making plan...")
plan = make_valid_plan()
save(plan, folder)
run(folder)
print((folder / "todo.md").read_text())
print((folder / "scratchpad.md").read_text())
print("world:", WORLD)

Output (real, run with Python 3.14 on 1 December 2026; the first lines are the planner of Part 4 doing its work):

text
making plan...
  planner call 1: feedback=none
   - s1: no done_when check (sub-goal is not verifiable)
   - s1: too big (7 tool calls > 4); split it
   - s3: unknown tool 'policy_lookup'
   - dependency cycle: s2 -> s3 -> s2
  planner call 2: feedback=['s1: no done_when check (sub-goal is not verifiable)', 's1: too big (7 tool calls > 4); split it', "s3: unknown tool 'policy_lookup'", 'dependency cycle: s2 -> s3 -> s2']
  plan accepted
# TODO (plan v1): Refund order A17 if the policy allows it, otherwise open a ticket; tell the customer.
- [x] load: Load order A17
- [x] policy: Find the refund policy
- [x] refund: Issue the refund if allowed
- [x] notify: Email the customer the outcome

turn 0: load -> done
turn 1: policy -> done
turn 2: refund -> done
turn 3: notify -> done

world: {'order': {'id': 'A17', 'total': 42.0}, 'policy': 'refunds allowed within 30 days', 'refund': 42.0, 'emails': ['Your refund of 42.00 is on its way.']}

What to notice:

  • ready is every pending step whose dependencies are all done or skipped. load and policy are both ready at the start. This simple runner takes ready[0], but the dependency data would let you run both at once (see 08A.2 on bounded parallel calls and 08A.11).
  • A failed check sets status = "failed" and stops. What to do next is 08C.2.
  • save writes plan.json through a temp file and replace. The reason is in 08C.3, 2.2.
  • Because the runner calls Plan.from_json(...) at the start of every turn, a human could mark refund as skipped in plan.json between turns and the runner would obey.

Part 4: Validating a plan#

4.1 Why validate#

A plan from a model is a proposal. Running an invalid plan wastes the run: a step with an unknown tool fails at step 3, a cycle never starts, a step with no check can never be confirmed. Checking the plan before the first tool call is nearly free and catches whole classes of failure. Deterministic checks first, a judge only for what code cannot check.

4.2 What to check#

The validate_plan function in 3.1 checks:

Check Why
At least one step; at most N steps Empty plans and runaway plans
Unique ids Dependencies refer to ids
Every dependency exists and is not itself Dangling references
No dependency cycle A cycle cannot run
Every tool is in the known tool set The model invents tool names
Every step has a done_when, and the check exists A step with no check is unverifiable
Estimated tool calls per step within the limit Oversized steps

Things code can add later: every step's tools are allowed for this user (see 08C.2, Part 4), total estimated cost fits the budget, and steps that write or delete are marked for approval (08A.12).

4.3 The planner repairs its own plan#

When validation fails, do not throw the plan away. Show the model the list of problems and ask again, with a small cap on attempts. This is the plan-level version of "return tool errors as data" from 08A.2.

The scripted planner below returns a flawed plan first on purpose (a step with no check and seven tool calls, a made-up tool, and a cycle between two steps), then a fixed one.

python
# decompose_demo.py: a scripted planner proposes a bad plan, the validator rejects it, the planner repairs it
import json

from plan_model import Plan, layers, validate_plan

TOOLS = {"orders_get", "docs_search", "refund_issue", "ticket_create", "email_send"}
CHECKS = {"order_loaded", "policy_found", "refund_recorded", "ticket_recorded", "customer_notified"}

GOAL = "Refund order A17 if the policy allows it, otherwise open a ticket; tell the customer."

# The scripted "model": first reply is flawed on purpose, second reply fixes what the validator said.
SCRIPT = [
    {"goal": GOAL, "steps": [
        {"id": "s1", "goal": "Handle the whole refund", "tools": ["orders_get", "refund_issue", "docs_search"],
         "est_tool_calls": 7, "done_when": ""},
        {"id": "s2", "goal": "Tell the customer", "depends_on": ["s3"], "tools": ["email_send"],
         "done_when": "customer_notified"},
        {"id": "s3", "goal": "Check policy", "depends_on": ["s2"], "tools": ["policy_lookup"],
         "done_when": "policy_found"},
    ]},
    {"goal": GOAL, "steps": [
        {"id": "load", "goal": "Load order A17", "tools": ["orders_get"], "done_when": "order_loaded"},
        {"id": "policy", "goal": "Find the refund policy", "tools": ["docs_search"], "done_when": "policy_found"},
        {"id": "refund", "goal": "Issue the refund if allowed", "depends_on": ["load", "policy"],
         "tools": ["refund_issue"], "done_when": "refund_recorded", "est_tool_calls": 2},
        {"id": "notify", "goal": "Email the customer the outcome", "depends_on": ["refund"],
         "tools": ["email_send"], "done_when": "customer_notified"},
    ]},
]


def scripted_planner(feedback: list[str] | None, attempt: int) -> str:
    print(f"  planner call {attempt + 1}: feedback={feedback or 'none'}")
    return json.dumps(SCRIPT[attempt])


def make_valid_plan(max_attempts: int = 3) -> Plan:
    feedback = None
    for attempt in range(max_attempts):
        text = scripted_planner(feedback, attempt)
        plan = Plan.from_json(text)
        problems = validate_plan(plan, TOOLS, CHECKS)
        if not problems:
            print("  plan accepted")
            return plan
        for p in problems:
            print("   -", p)
        feedback = problems
    raise RuntimeError("planner could not produce a valid plan")


if __name__ == "__main__":
    plan = make_valid_plan()
    print("layers:", layers(plan))
    print("steps:", [s.id for s in plan.steps])
Output · real9 lines
  planner call 1: feedback=none
   - s1: no done_when check (sub-goal is not verifiable)
   - s1: too big (7 tool calls > 4); split it
   - s3: unknown tool 'policy_lookup'
   - dependency cycle: s2 -> s3 -> s2
  planner call 2: feedback=['s1: no done_when check (sub-goal is not verifiable)', 's1: too big (7 tool calls > 4); split it', "s3: unknown tool 'policy_lookup'", 'dependency cycle: s2 -> s3 -> s2']
  plan accepted
layers: [['load', 'policy'], ['refund'], ['notify']]
steps: ['load', 'policy', 'refund', 'notify']

The first plan fails four checks at once. The planner gets all four messages back, in plain words, and the second plan passes. Note the cap: max_attempts=3. If the planner still cannot produce a valid plan, raise and let a person or a simpler fallback take over. Never loop forever on a planner. layers then shows the plan has three waves: load and policy can run together, then refund, then notify.

4.4 Getting a structured plan from a real model#

Use the provider's structured output feature so the reply is JSON that matches your schema. 03.4 covers structured output in full, including which schema features strict mode accepts, so this sample keeps the schema simple: strings, arrays, an integer, no minimum or defaults. Strict mode needs every property listed in required and additionalProperties set to false.

python
# provider_plan.py: ask a hosted model for a plan as structured JSON (OpenAI and Anthropic; needs keys, not run here)
import json

from openai import OpenAI
from anthropic import Anthropic

from plan_model import Plan

STEP_SCHEMA = {
    "type": "object",
    "additionalProperties": False,
    "required": ["id", "goal", "depends_on", "tools", "done_when", "est_tool_calls"],
    "properties": {
        "id": {"type": "string"},
        "goal": {"type": "string"},
        "depends_on": {"type": "array", "items": {"type": "string"}},
        "tools": {"type": "array", "items": {"type": "string"}},
        "done_when": {"type": "string"},
        "est_tool_calls": {"type": "integer"},
    },
}
PLAN_SCHEMA = {
    "type": "object",
    "additionalProperties": False,
    "required": ["goal", "steps"],
    "properties": {"goal": {"type": "string"}, "steps": {"type": "array", "items": STEP_SCHEMA}},
}
SYSTEM = ("You are a planner. Split the goal into at most 8 steps. Every step needs a done_when check "
          "name, at most 4 tool calls, and depends_on listing the ids it needs first. "
          "Tools: orders_get, docs_search, refund_issue, ticket_create, email_send. "
          "Checks: order_loaded, policy_found, refund_recorded, ticket_recorded, customer_notified.")
GOAL = "Refund order A17 if the policy allows it, otherwise open a ticket; tell the customer."


def plan_openai() -> Plan:
    client = OpenAI()                                   # reads OPENAI_API_KEY
    response = client.responses.create(
        model="gpt-6-luna",
        input=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": GOAL}],
        text={"format": {"type": "json_schema", "name": "plan", "strict": True, "schema": PLAN_SCHEMA}},
    )
    return Plan.from_json(response.output_text)


def plan_anthropic() -> Plan:
    client = Anthropic()                                # reads ANTHROPIC_API_KEY
    response = client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=2_000,
        system=SYSTEM,
        messages=[{"role": "user", "content": GOAL}],
        output_config={"format": {"type": "json_schema", "schema": PLAN_SCHEMA}},
    )
    text = next(b.text for b in response.content if b.type == "text")
    return Plan.from_json(text)


if __name__ == "__main__":
    for name, fn in [("openai", plan_openai), ("anthropic", plan_anthropic)]:
        plan = fn()
        print(name, [s.id for s in plan.steps])

Output (illustrative, needs OPENAI_API_KEY and ANTHROPIC_API_KEY; your exact output will differ):

text
openai ['load', 'policy', 'refund', 'ticket', 'notify']
anthropic ['load_order', 'find_policy', 'decide', 'act', 'notify']

The schema guarantees the shape. It does not guarantee the plan is good: ids may still dangle and tools may still be invented. So the reply goes straight into Plan.from_json and then validate_plan, exactly as in 4.3. The provider enforces the shape. Checking the meaning is your job.


Part 5: Evaluate it#

You now have a plan, a validator and a runner. How do you know the plans are any good? Measure the plan and the run separately.

Concept lessons first.

  • 10A.7, Part 4: grading process is the concept home. 4.5 Plan quality covers judge-scored plan quality, and 4.4 covers budget and permission compliance.
  • 10A.7, 8.3 covers milestone grading for long tasks: the per-step done_when checks you wrote here are exactly those milestones.
  • 10A.11 is the concept home for judging what the agent kept in context, which matters if the plan lives in the transcript instead of in files.
  • 10A.12 applies if a planner agent hands steps to worker agents.

DeepEval lessons (required track).

  • 10B.2 and 10B.4 for test cases and built-in metrics.
  • 10B.5, Part 9 for the plan-quality and plan-adherence judges on a trace.
  • 10B.6 for turning planning tasks into a dataset, and 10B.7 for running them in CI.

Inspect AI lessons (optional).

  • 10B.14, 4.4 (optional): the todo_write and update_plan tools.
  • 10B.15, Part 10 (optional): long-horizon agents.
  • 10B.16 (optional): reading trajectories from events.

5.1 What to measure for planning#

Measure What it tells you How to compute
Plan validity rate How often the first plan passes the validator valid_first_try / plans, plus the average number of repair rounds
Plan fit Whether the plan has the right shape Steps within bounds, no step over the size limit, every step has a check
Step success rate Whether steps reach their sub-goal Share of done_when checks that pass on first try
Plan adherence Whether the agent did what the plan said Share of executed tool calls that belong to the current step
Task success Whether the real goal was reached End-state grader from 10A.7, Part 3
Cost and steps vs optimal Whether planning paid for itself Tokens and calls with the plan vs a plain ReAct loop on the same tasks

The last row matters most. Planning must beat the simpler loop on task success per dollar, or it is overhead (08A.10, 3.4).

5.2 A tiny eval design#

  • Inputs: 12 support tasks: 4 that need a refund, 4 that the policy forbids (ticket expected), 4 ambiguous (the order id is missing, so the right plan asks for it).
  • Metric 1 (code): plan validity at attempt 1, with validate_plan. Pass rule: at least 10 of 12 valid on the first attempt, and 12 of 12 within 3.
  • Metric 2 (code): end-state check per task: refund row exists for the 4 refund tasks, no refund row and a ticket row for the 4 forbidden, no write at all for the 4 ambiguous. Pass rule: 11 of 12, run each task 3 times and count it only if it passes all 3 (see 10A.7, Part 5).
  • Metric 3 (judge, optional): a plan-quality rubric on the 12 plans ("does every step have a check", "is the risky step last"). Calibrate the judge first (10A.5).
  • Compare with a plain ReAct loop on the same 12 tasks. Report success rate and tokens per successful task for both.

Common misconceptions#

  • "A longer plan is a better plan." Past about 8 to 12 steps, plan in levels. Long flat plans go stale fast.
  • "The model's plan is trustworthy because it is structured JSON." Schema checks guarantee the shape. They say nothing about whether the dependencies exist, the tools are real or the steps are sensible.
  • "The agent marks a step done when it says so." Done means the done_when check passed against the world.
  • "The plan belongs in the prompt." The plan belongs in state you own. Put a view of it in the prompt.
  • "A markdown todo is enough." It is fine for reading. Keep a validated structured source of truth next to it.
  • "Planning always helps." It costs calls and can go stale. Measure it against a plain loop.

Key takeaways#

  • Decompose until each step is bounded, verifiable and independent enough.
  • Use dependencies, not just order. A DAG shows what can run in parallel and exposes cycles.
  • Put cheap, read-only, likely-to-fail steps early and expensive or irreversible steps late.
  • Every step gets a done_when check that reads the world.
  • Store the plan as data: a JSON source of truth, a generated todo view and an append-only scratchpad. Re-read them every turn.
  • Validate every plan before running it, and feed the problem list back to the planner with a capped retry.
  • Evaluate plan validity, step success and task success per dollar against a simple baseline.

Terms introduced in this lesson#

Term Meaning
Task decomposition Splitting a goal into smaller steps that are each easy to do and to check
Plan An ordered or dependency-linked list of steps, held as data
Step The smallest unit of work given to one bounded agent loop
Sub-goal The outcome a single step must reach
Verifiable sub-goal A sub-goal with a done_when check that inspects the world, not the model's claim
done_when The name of the check function that confirms a step is finished
Dependency graph Steps and the arrows showing which step needs which
DAG Directed acyclic graph: arrows go one way, with no loops
Cycle A circular dependency (A needs B, B needs A) that makes a plan impossible to run
Layer A group of steps that do not depend on each other and may run together
Step sizing Choosing how much work one step holds (bounded, verifiable, independent enough)
Plan-as-artifact Keeping the plan in files or a store the program owns, not only in chat text
Todo file A short readable view of the plan with a status per step
Scratchpad An append-only notes file for findings and decisions
Plan validation Checking a plan (ids, dependencies, tools, checks, size) before running it
Plan repair Returning validation problems to the planner so it produces a corrected plan
Scripted planner A fake planner that returns canned plans, used to test planning without a model

Exercises#

  1. Break the validator. Write three more flawed plans: one with a duplicate id, one where a step depends on itself, one with a three-step cycle (a -> b -> c -> a). Confirm each message names the right step. Hint: find_cycle returns the cycle as a list; print it with arrows as validate_plan does. For the self-dependency, two checks fire (unknown or self); decide which message is more useful.
  2. Add a risk field. Add risk: str = "read" (read, write, destructive) to Step. In validate_plan, reject any plan where a destructive step has no dependency on a read step. Hint: walk depends_on transitively; a simple recursive helper with a visited set is enough.
  3. Run in parallel. Change run in plan_files.py to execute every step in ready in one turn using a thread pool, then save once. What new problem appears when two steps write the same field of WORLD? Hint: think about which step's result wins, and whether the plan should have a dependency instead.
  4. Human edit. After the first turn, mark refund as skipped in plan.json and let the runner continue. Does notify still run? Should it? Hint: notify depends on refund, and skipped counts as satisfied. Decide whether a skip should instead block dependants, and implement your choice.
  5. A markdown plan. Generate PLAN.md from plan.json, let a scripted "model" edit one line, then parse it back and validate it. Make the parser reject lines it cannot map to a step. Hint: use a fixed line format such as - [ ] id: goal (needs: a, b) and a strict regular expression.
  6. Real planner. Run provider_plan.py against one provider with a key. How many repair rounds does it need on the 12 tasks from 5.2? Hint: count validate_plan failures at attempt 1; if the number is zero, make the tool list longer and try again.

Check yourself#

  1. What are the three tests a step should pass?
  2. Why is done_when a name of a check function and not a sentence for the model to judge?
  3. What does a dependency graph tell you that an ordered list does not?
  4. Why does the validator return a list of problems instead of raising on the first one?
  5. Why order cheap read-only steps before expensive irreversible ones?
  6. Give two reasons to keep the plan in a file instead of the message history.
  7. Why is the scratchpad append-only, and what do you do when it grows too long?
  8. What does a structured-output schema guarantee about a plan, and what does it not?
  9. How can a planner's plan be wrong while still being valid JSON?
  10. Name two measures that tell you whether planning paid for itself.

Further resources#


← Module 08B: Context, State and Memory | Module 08C overview | 08C.2 — Dynamic Replanning and Constraint-Aware Planning →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close