Planning and Task Decomposition

Learn how agents plan: breaking a complex task into subtasks, ordering them with dependencies, executing the plan sequentially, planning dynamically as new information arrives, and replanning after a failure.

30 minIntermediateCode Examples

The Core Idea: Big goals are solved by breaking them into subtasks, ordering them by dependencies, executing them, and replanning when something fails or something new is learned, while keeping the work that is already done.

  1. Beginner: Why Plan?

Some tasks are too large to handle with one decision at a time. Write a report comparing electric-car markets and battery technology involves research, comparison and writing. Without a plan an agent may wander, repeat itself, or forget a part.

Without a planStep by step guessing
Easy to get lost
Repeats or skips work
Hard to explain or check
With a planA clear route
Each subtask is small and testable
Progress can be shown
Failures are easy to locate

Analogy: A plan is a map. You can still change the route, but you know where you are and where you are going.

  1. Beginner: Breaking Complex Tasks Into Subtasks

Task decomposition splits a large goal into smaller pieces that are each easy to do and check.

Good subtaskWhy
Has one clear outcomeEasy to tell when it is done
Small enough for a few tool callsFits one focused step
States its inputsKnows what it needs from earlier subtasks
Can be checkedA test or a rule says whether it worked
Example
Goal: write a market and technology report. Subtasks: find market data, find technology data, compare the two, write the report.

  1. Medium: Planning and Sequential Execution

A plan is more than a list: some subtasks depend on others. In the example, compare needs both data subtasks, and write the report needs the comparison. Drawing these links gives a dependency graph.

Sequential execution runs subtasks one after another in a valid order. Independent subtasks (the two data searches) could even run in parallel, which a later lesson covers.

In the code: Python's graph tools list a valid order in which every subtask comes after the ones it depends on.

Two planning styles: Plan first, then execute (predictable, but the plan can go stale) and plan a little, act, plan again (flexible, but more model calls).

  1. Medium: Dynamic Planning

The world rarely follows the plan exactly. Dynamic planning means the plan is a living document: after each result, the agent can add, remove or reorder subtasks.

New informationPlan change
A search shows the topic is bigger than expectedAdd more research subtasks
A needed tool is unavailableChoose another route
An early result makes a later step unnecessaryRemove the step
The user changes the goalRewrite the plan, keep reusable results

Rule of thumb: Plan in enough detail for the next few steps and keep the rest loose. Over-detailed long plans break first.

  1. Advanced: Replanning After Failure

When a subtask fails, the agent should not start from zero. Replanning keeps the completed work and changes only what is broken.

1
Detect the failure: A tool error, a bad result or a failed check.
2
Keep finished work: Results from completed subtasks are reused.
3
Change the plan: Swap the failed subtask for an alternative or a fix.
4
Continue: Execute only the subtasks that are not yet done.
5
Limit it: Allow a few replans, then stop or ask a human.

Danger: Unlimited replanning is a loop in disguise. Always cap the number of replans.

  1. Visual Explanation: A Plan With Dependencies and a Replan

The figure shows the dependency structure of the plan in the code, then what happens when one subtask fails and the plan is replaced.

Part 1 · A Plan With DependenciesFour subtasks
GatherParallel-ready
find_market_data
↓
find_tech_data
↓
Independent subtasks
CombineNeeds both
compare
↓
Waits for both data subtasks
DeliverNeeds compare
write_report
↓
The final result
Part 2 · What Happened When One Subtask FailedReplanning in the code
Failure
Plan 1
find_market_data fails.
Kept
Done work
find_tech_data stays finished.
Swap
Plan 2
find_market_data_backup replaces it.
Finish
Continue
compare and write_report run.
Click to see why we keep finished workCompare ▼
Redoing completed subtasks wastes time and money. Keeping a record of completed subtasks lets the new plan skip them. The code shows the technology data being reused instead of re-fetched.

Part 1 shows the order constraints. Part 2 shows the failure and the swap. Open the bar to see why finished work is kept.

  1. Python Implementation: Dependency Planning and Replanning

This script builds a plan as a dependency graph, finds a valid execution order, runs it until one subtask fails, then replans by swapping in a backup subtask while keeping the completed work.

planning_and_replanning.pyPython 3.10+ · standard library only
from graphlib import TopologicalSorter # A plan is a set of subtasks and what each one depends onplan = {    "find_market_data": [],    "find_tech_data": [],    "compare": ["find_market_data", "find_tech_data"],    "write_report": ["compare"],}completed = set()broken = {"find_market_data"}            # this subtask will fail the first time def execute(plan, completed, broken):    ts = TopologicalSorter(plan)    ts.prepare()    while ts.is_active():        failed = []        for task in sorted(ts.get_ready()):            if task in completed:                ts.done(task)            # already finished earlier: skip            elif task in broken:                failed.append(task)            else:                print("  ran:", task)                completed.add(task)                ts.done(task)        if failed:            return failed    return [] print("Plan 1 order if nothing fails:", list(TopologicalSorter(plan).static_order()))print("Executing plan 1")failed = execute(plan, completed, broken)print("  FAILED:", failed) # Replanning: swap the failed subtask for a backup, keep the finished workdef replace(plan, old, new):    return {(new if k == old else k): [new if d == old else d for d in deps] for k, deps in plan.items()} plan2 = replace(plan, "find_market_data", "find_market_data_backup")print("Executing plan 2 (replanned)")failed = execute(plan2, completed, broken)print("  Finished. Everything done:", sorted(completed))
EXPECTED OUTPUT (your numbers may differ slightly)
Plan 1 order if nothing fails: ['find_market_data', 'find_tech_data', 'compare', 'write_report']
Executing plan 1
ran: find_tech_data
FAILED: ['find_market_data']
Executing plan 2 (replanned)
ran: find_market_data_backup
ran: compare
ran: write_report
Finished. Everything done: ['compare', 'find_market_data_backup', 'find_tech_data', 'write_report']

The first execution completes the technology search and then stops at the failed market search. The replanned run swaps in the backup subtask and runs only the remaining work: the backup, the comparison and the report.

Knowledge Check

Question 1: What is a dependency in a plan?
Question 2: What should the agent do with finished work when replanning?

Key Points

✓Planning breaks a big goal into subtasks with clear outcomes.
✓Good subtasks are small, have clear inputs and outputs, and can be checked.
✓Dependencies decide the valid order. Independent subtasks can run in parallel.
✓Dynamic planning updates the plan as new information arrives.
✓Replanning swaps broken subtasks and keeps completed work.
✓Cap the number of replans to avoid disguised infinite loops.

The Big Picture

Planning in One Line

Decompose → order by dependencies → execute → replan the broken parts only

A good plan turns a vague goal into small steps the agent can do and check.

Up Next: Plans work best when the agent thinks, acts and learns from each result. In ReAct, Reflection and Self-Correction you will see how agents reason while acting and fix their own mistakes.