Chapter 19 of 32 · ~22 min read & lab+80 XP
Chapter 19 · Agentic AI

Plan-and-Execute Agents: Task Decomposition, Step Tracking & Dynamic Re-Planning

Why pure ReAct loses the plot on 12-step tasks, how Plan-and-Execute separates strategic planning from tactical execution, Frontier-Planner + Mini-Executor model tiering, and dynamic re-planning when tools fail!

What Is It?

Plan-and-Execute separates high-level task decomposition (creating an ordered step list) from focused step execution, dynamically updating the plan whenever a step uncovers surprises.

Why Is It Required?

Pure step-by-step ReAct loses the big picture on 15-step tasks; explicit planning keeps long-horizon work coherent while allowing cheaper models to execute routine sub-steps.

Everyday Analogy: Drawing a travel itinerary before leaving home—and smoothly rerouting Day 3 if a train gets canceled.
Why ML Engineers & Data Scientists Actually Need This

ReAct agents are tactical sprinters — on long 10-step research or analytics tasks, they wander, forget earlier sub-goals, and burn Frontier tokens on every trivial step!

ML / AI Engineer

Plan-and-Execute gives you an explicit, inspectable checklist ([S1, S2, S3]) you can stream to users in the UI, resume after crashes, and execute with cheap mini models.

Data Scientist

When Step 2 discovers unexpected schema drift or an empty API response, a Dynamic Re-Planner splices recovery steps automatically instead of crashing with NaN.

Interview & Debug Edge

Top system-design & coding interview question: 'How does Plan-and-Execute differ from ReAct, and how do you handle a mid-plan tool failure without restarting from scratch?'

Step 0 · Test Your Gut Before Any Math!

If Step 2 of a 4-step plan fails with 404 Endpoint Deprecated, what is the best recovery behavior?

What You Will Master in This Chapter
  • Contrast greedy single-step ReAct loops with explicit Plan-and-Execute task decomposition
  • Design a typed PlanState with steps[], completed_results[], and a bounded Dynamic Re-Planner
  • Slash multi-step agent costs by 60%+ using Model Tiering (Frontier Planner + Fast Mini Executor)
  • Prevent infinite re-planning loops with a strict max_replans budget and progress invariants
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
P0=[s1,s2,…,sk]P_0 = [s_1, s_2, \dots, s_k]Say aloud:“Initial plan P-zero equals steps s-1 through s-k”
Plain-English Meaning
The ordered checklist or dependency DAG emitted by the Planner LLM before running any tools.
Everyday Example
[Fetch Q3 CSV, Query Billing DB, Compute YoY Growth, Draft Memo].
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of ReAct like hiking through a forest looking only one step ahead at your feet — great for short trails, terrible for a 12-mile summit. Plan-and-Execute is checking the topographic map at the trailhead, writing down 5 clear waypoints, and re-routing calmly if a bridge washes out at Waypoint 2!

1. Why Pure ReAct Struggles on Long-Horizon Tasks

Plan-and-Execute Architecture: Plan → Execute Step → Re-Plan Loop1. Planner LLMEmit [S1, S2, S3]2. Executor AgentRun next step + tools3. Re-PlannerUpdate / prune plan4. Final AnswerAll steps done ✓Remaining steps > 0? Loop back to Executor with updated Plan!
Plan-and-Execute separates strategic planning (generating a numbered Task DAG) from tactical step execution and dynamic re-planning when reality diverges!

In Module 1, ReAct (Thought → Action → Observation) shined on 2–4 step lookups. Push ReAct to a 12-step research or analytics workflow and three failure modes hit immediately:

  1. Myopic wandering: Deciding only one step ahead causes detours and forgotten early constraints.
  2. Frontier token burn: Every trivial step re-sends the growing transcript to your most expensive reasoning model.
  3. Zero user visibility: Users stare at a spinner with no live progress checklist.

Plan-and-Execute solves all three by separating strategic planning from tactical step execution!

Walk Through With Me · Interactive Worked Example

Tracing a Self-Healing Plan-and-Execute Run

User asks: 'Compare our Q3 enterprise revenue against last quarter and summarize the top 2 drivers.'

11. Strategic Planning (Frontier Model)Step 1 / 4

The Planner outputs a crisp 3-step JSON plan: [1: Fetch Q2 CSV, 2: Query Stripe Q3 API, 3: Compute delta & summarize]. Users immediately see the live checklist!

Teacher's Note: Notice how each transition keeps state explicit and verifiable!

2. Static Plans vs. Dynamic Re-Planning

Static Plan (Brittle) vs. Dynamic Re-Planning (Self-Healing)Static Plan (No Re-Planner)Step 1: Fetch Q3 CSV → ✓ OKStep 2: Query Stripe API → ✗ 404 Not FoundStep 3: Compute Growth → 💥 NaN / Crash!Blindly executes stale stepsDynamic Re-PlannerStep 1: Fetch Q3 CSV → ✓ OKStep 2: Stripe 404 → Re-Plan inserts Step 2b!Step 2b: Query Billing DB → Step 3: ✓ Success!Adapts plan to live observations
A Static Plan fails the moment Step 2 returns unexpected data; a Dynamic Re-Planner inspects completed results and splices recovery steps into the remaining plan!

Early Plan-and-Execute prototypes emitted a rigid list once and ran it blindly — breaking the moment real-world APIs returned unexpected data or 404s.

Production systems add a Dynamic Re-Planner on failure or surprise:

  • Keep completed_results[] immutable — never redo work that already succeeded.
  • Mutate only the remaining tail steps[]: splice a fallback step, skip redundant steps, or exit early.
  • Enforce max_replans (e.g., 3) so a broken downstream API triggers a graceful fallback rather than an infinite re-plan storm.
Animated Mini-Lab • 4.1

Plan-DAG Failure & Dynamic Re-Planner Simulator

S1
Fetch Q3 CSV
S2
Stripe API (404!)
S2b
Re-Plan: Query Billing DB
S3
Compute YoY Growth
Pause & Check · Quick Intuition Pulse

When a Dynamic Re-Planner runs after Step 2 fails, what should happen to Step 1's completed result?

3. Model Tiering: Frontier Planner + Mini Executor

Cost Optimization: Frontier Planner + Fast/Cheap Executor TieringFrontier Model (1–2 calls)Deep reasoning & DAG designHigh IQ · Called sparinglyCost: ~$0.015 / taskMini/Flash Executor (6–10 calls)Focused single-step tool calls200ms latency · 15× cheaperCost: ~$0.004 / task−65% CostSame quality2.4× faster
Model Tiering in Plan-and-Execute: use a Frontier Reasoning Model once for high-leverage planning, and a fast, cheap Executor Model for routine tool steps — slashing cost by 60%+!

One of the highest-ROI production tricks in Agentic AI is asymmetric model routing:

  • Use a Frontier Reasoning Model once to decompose the goal into unambiguous, atomic steps (and only re-invoke it when re-planning is needed).
  • Dispatch each atomic step to a fast Mini/Flash Executor with only the 2–3 tools needed for that step — cutting latency by 2×+ and LLM spend by 60%–80%!
Formula Anatomy · Click Any Colored Piece to Decode It
Model-Tiered Plan-and-Execute Cost Equation

Click each term to see why separating Planning from Execution cuts production bills dramatically.

Total Task Cost

Combined LLM API spend to finish a multi-step goal from prompt to final answer.

In our example: \$0.019 per complex analytics task
Put it together with real numbers: Splitting a 10-step workflow into 2 Frontier Planner calls + 8 Mini Executor calls cuts spend from \$0.11 (pure Frontier ReAct) down to \$0.019 (~83% cheaper) while improving global coherence!
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

No! Plan-and-Execute adds an extra upfront Planner LLM call. For simple 1–2 step tasks, a fast single-turn tool call or basic ReAct loop is much faster and cheaper.

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Plan-and-Execute Studio recover from Step 2's 404 via Dynamic Re-Planning.
Interactive Animation • 4.1 Deep Lab

Plan-and-Execute + Dynamic Re-Planner Recovery Studio

Watch the Executor hit an unexpected 404 on Step 2 and the Re-Planner dynamically splice a recovery step.

1. Planner
[1. Planner]Emits [S1: Fetch CSV, S2: Stripe API, S3: Report]
[2. Execute S1]S1 Fetch CSV → ✓ 1,240 rows loaded
[3. Execute S2]S2 Stripe API → ✗ HTTP 404 (Endpoint Deprecated)
[4. Re-Planner]Splices S2b: Query Billing Postgres → ✓ $1.42M ARR
[5. Complete]S3 Report generated & verified ✓
0%
1. Planner
Intuition Takeaway: Plan-and-Execute pairs a Frontier Planner with fast Mini Executors and a bounded Dynamic Re-Planner (max_replans), giving long-horizon agents global coherence, live UI checklists, self-healing recovery, and 60%+ lower cost.
Where This Powers Real ML, Deep Learning & Generative AI

Deep Research & Competitive Intelligence

Generates an explicit multi-step research checklist before browsing, streaming live progress to users.

Automated SQL & BI Data Analysts

Decomposes multi-table analytics questions into verifiable query steps with dynamic re-planning on schema surprises.

Production NumPy & PyTorch Code Patterns
from dataclasses import dataclass, field
from typing import List, Dict, Any

@dataclass
class PlanState:
    goal: str
    steps: List[str] = field(default_factory=list)
    completed: List[Dict[str, Any]] = field(default_factory=list)
    replans: int = 0
    max_replans: int = 3

def run_plan_and_execute(goal: str, planner, executor, replanner) -> str:
    state = PlanState(goal=goal, steps=planner(goal))

    while state.steps:
        current_step = state.steps.pop(0)
        obs = executor(current_step, context=state.completed)
        state.completed.append({"step": current_step, "obs": obs})

        if obs.get("status") == "error" or obs.get("needs_replan"):
            if state.replans >= state.max_replans:
                return f"Stopped safely after {state.max_replans} re-plans: {obs}"
            state.replans += 1
            decision = replanner(state.goal, state.completed, state.steps)
            if decision["done"]:
                return decision["final_answer"]
            state.steps = decision["updated_steps"]

    return replanner(state.goal, state.completed, [])["final_answer"]
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Re-invoking the Re-Planner on every single step even when steps succeed cleanly.
Best Practice: Only trigger the Re-Planner on failure, unexpected output, or milestone checkpoints to avoid doubling LLM calls!
Trap #2: Forgetting a max_replans cap on the Dynamic Re-Planner.
Best Practice: Enforce max_replans = 3 so a persistently broken API exits gracefully instead of looping forever.
Chapter Mastery Check (+80 XP)
Score: 0 / 2
1What is the primary cost advantage of Model Tiering in Plan-and-Execute agents?
2Which safeguard prevents a Dynamic Re-Planner from spinning forever when an external API is permanently down?

Apply What You Learned — Solve Matching Coding Problems