Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 3

Lab: Plan, Execute, Replan

Build a Plan-and-Execute agent: a planner writes a list of steps, the runtime runs them one at a time, and the agent replans when a step fails or a result breaks the plan, within a fixed replan budget.

Contentsand lesson path

What you will learn

  • Implement plan-and-execute with replanning when a step fails or new information arrives.

Prerequisites: Agent Loops & ReAct

01. Why Write the Plan Down: The Plan-and-Execute Pattern

A plain agent loop decides only its next step at each turn. This loop is often called ReAct, short for "reason and act": the model thinks, calls one tool, reads the result and repeats. That works well for short tasks. On a long task there is no written plan to come back to, so one surprising tool result can pull the model away from the goal. This is called plan drift. For example, an agent asked for a full market review might spend all eight of its turns on one odd price figure and never look at churn or margins.

The Plan-and-Execute pattern writes the plan down first. The planning idea comes from Plan-and-Solve prompting (Wang et al. 2023), where one model writes a plan and then solves the problem in the same answer. Frameworks such as LangGraph turned it into an agent pattern with a separate executor and replanner. The work is split into two roles:

  • The planner: one model call reads the goal and returns a list of steps, each naming a tool and its arguments. In agent.py below this is planner.plan(goal).
  • The executor: the part that carries out one step and records the result. In this lab it is a plain tool call, TOOLS[step["tool"]](**step["args"]). In a larger system it can be a separate model call that works out how to do one step.

The plan lives in your program as a Python list, not only in the model's context. That makes it easier to keep the goal in view when a result is surprising, and it lets your code check, log and change the plan. It does not make the plan correct: a bad plan is still bad, which is why the runtime can replan.

02. Replanning: When the Plan No Longer Fits

A fixed pipeline usually has one answer to a surprise: stop with an error. A Plan-and-Execute agent can change the rest of its plan instead. Surprises are common: an API returns a different shape, a data source times out, or a result shows that an assumption was wrong. In this lab a competitor has cut prices by 25%, so a plan built on a 30% margin no longer makes sense.

After each step, agent.py below does four things:

  1. Record the result. A step that worked is added to done with its result. A step that failed goes back to the front of steps, because it is still pending.
  2. Decide whether to replan. There are two triggers: the step failed, or a judge (planner.invalidates_plan) says the new result breaks the remaining plan. The judge returns {invalidates, reason}. In production it is a model call or a rule you write.
  3. Ask for a new plan. planner.replan(goal, done, steps, obs, reason) receives the goal, the finished steps with their results, the pending steps and the reason. It returns new pending steps only, so finished work is kept and is not run again.
  4. Check the new plan and continue. valid() checks it against the tool registry, then the loop runs it. If replans already equals max_replans, there is no step 3: the loop returns a failure report instead.

The failure report carries the goal, the reason, the results of the steps that finished (the partial result) and the steps still pending. The runtime also returns a report, without running anything, when a plan names a tool that is not in the registry.

Python · replan-lab/agent.py
"""Plan, execute step by step, and replan on failure or on new information."""
import json
import sys

import planner
from tools import TOOLS


def show(title, steps):
    print(title)
    for i, s in enumerate(steps, 1):
        print(f"    {i}. {s['tool']}({json.dumps(s['args'])})")


def valid(steps):  # check the planner's structured output before using it
    return all(s.get("tool") in TOOLS and isinstance(s.get("args"), dict)
               for s in steps)


def failed(goal, done, reason, steps):
    return {"status": "failed", "goal": goal, "blocked_by": reason,
            "partial_results": {d["tool"]: d["result"] for d in done},
            "pending": [s["tool"] for s in steps]}


def run(goal, max_replans):
    steps, done, replans = planner.plan(goal), [], 0
    if not valid(steps):
        return failed(goal, done, "planner returned an unknown tool", steps)
    show("plan", steps)
    while steps:
        step = steps.pop(0)
        try:
            obs = TOOLS[step["tool"]](**step["args"])
        except Exception as exc:
            obs = {"error": f"{type(exc).__name__}: {exc}"}
        print(f"  {step['tool']} -> {json.dumps(obs)[:58]}")
        if "error" in obs:
            reason = f"step failed: {obs['error']}"
            steps.insert(0, step)  # the failed step is still pending
        else:
            done.append({**step, "result": obs})
            verdict = planner.invalidates_plan(obs, steps)
            reason = verdict["reason"] if verdict["invalidates"] else None
        if reason is None:
            continue
        if replans == max_replans:  # budget spent: stop, do not run a stale plan
            return failed(goal, done, reason, steps)
        replans += 1
        steps = planner.replan(goal, done, steps, obs, reason)
        if not valid(steps):
            return failed(goal, done, "replanner returned an unknown tool", steps)
        show(f"replan {replans}/{max_replans}: {reason}", steps)
    return {"status": "done", "replans": replans, "answer": done[-1]["result"]}


if __name__ == "__main__":
    budget = int(sys.argv[1]) if len(sys.argv) > 1 else 2
    print(json.dumps(run("propose a market entry strategy", budget), indent=1))

03. Lab: Replan on Failure and on New Information

In this lab the agent prepares a market-entry recommendation. Two things go wrong, one of each kind: the first step reveals a 25% competitor price cut that breaks the plan's margin assumption, and the churn data warehouse times out. You will watch the agent replan twice and finish, then cut the replan budget to one and watch it stop with a clear report.

You need: Python 3.12 or later; standard library only, no API key. Tested with Python 3.12.13 to 3.14.7, which all print the same output. Create a folder replan-lab, save agent.py from the section above and the two files below into it. The planner, judge and replanner are scripted stand-ins for three model calls; each returns the structured shape you would request from a real model (a list of {tool, args} steps, and {invalidates, reason} for the judge).

Python · replan-lab/tools.py
"""Fixture tools for a market-entry analysis; one source is down."""


def fetch_competitor_pricing(market):
    return {"competitor": "X", "price_drop_pct": 25}


def query_churn_reasons(months):
    raise TimeoutError("churn warehouse did not answer in 10 s")


def read_churn_survey(months):
    return {"top_reason": "no enterprise SLA", "share": 0.41}


def build_positioning(margin_pct):
    return {"position": "price match", "margin_pct": margin_pct}


def model_sla_premium(price_drop_pct):
    return {"position": "premium SLA tier", "margin_pct": 31 - price_drop_pct // 5}


def write_recommendation(position):
    return {"recommendation": f"Enter with a {position} offer."}


TOOLS = {f.__name__: f for f in (fetch_competitor_pricing, query_churn_reasons,
                                   read_churn_survey, build_positioning,
                                   model_sla_premium, write_recommendation)}
Python · replan-lab/planner.py
"""Scripted planner, judge and replanner: stand-ins for three structured model calls.
Each returns the JSON shape you would request from a real model."""


def plan(goal):
    return [{"tool": "fetch_competitor_pricing", "args": {"market": "storage"}},
            {"tool": "query_churn_reasons", "args": {"months": 6}},
            {"tool": "build_positioning", "args": {"margin_pct": 30}},
            {"tool": "write_recommendation", "args": {"position": "price match"}}]


def invalidates_plan(observation, remaining):
    """Judge: {"invalidates": bool, "reason": str}. A real one is a model call."""
    if observation.get("price_drop_pct", 0) > 15 and any(
            s["tool"] == "build_positioning" for s in remaining):
        return {"invalidates": True,
                "reason": "a 25% price cut breaks the 30% margin assumption"}
    return {"invalidates": False, "reason": ""}


def replan(goal, done, remaining, observation, reason):
    """Returns new remaining steps; completed steps are never repeated."""
    tools_done = {d["tool"] for d in done}
    if "error" in observation:  # switch to another source for the failed step
        swap = {"query_churn_reasons": "read_churn_survey"}
        return [{**s, "tool": swap.get(s["tool"], s["tool"])} for s in remaining]
    if "fetch_competitor_pricing" in tools_done:  # new information: re-plan the rest
        keep = [s for s in remaining if s["tool"] == "query_churn_reasons"]
        drop = observation["price_drop_pct"]
        return keep + [
            {"tool": "model_sla_premium", "args": {"price_drop_pct": drop}},
            {"tool": "write_recommendation", "args": {"position": "premium SLA tier"}}]
    return remaining

Step 1: create the files. Save agent.py, tools.py and planner.py in replan-lab.

Step 2: run with a budget of two replans. The command uses the default budget.

Terminal
python3 agent.py
Expected output
plan
    1. fetch_competitor_pricing({"market": "storage"})
    2. query_churn_reasons({"months": 6})
    3. build_positioning({"margin_pct": 30})
    4. write_recommendation({"position": "price match"})
  fetch_competitor_pricing -> {"competitor": "X", "price_drop_pct": 25}
replan 1/2: a 25% price cut breaks the 30% margin assumption
    1. query_churn_reasons({"months": 6})
    2. model_sla_premium({"price_drop_pct": 25})
    3. write_recommendation({"position": "premium SLA tier"})
  query_churn_reasons -> {"error": "TimeoutError: churn warehouse did not answer in
replan 2/2: step failed: TimeoutError: churn warehouse did not answer in 10 s
    1. read_churn_survey({"months": 6})
    2. model_sla_premium({"price_drop_pct": 25})
    3. write_recommendation({"position": "premium SLA tier"})
  read_churn_survey -> {"top_reason": "no enterprise SLA", "share": 0.41}
  model_sla_premium -> {"position": "premium SLA tier", "margin_pct": 26}
  write_recommendation -> {"recommendation": "Enter with a premium SLA tier offer."}
{
 "status": "done",
 "replans": 2,
 "answer": {
  "recommendation": "Enter with a premium SLA tier offer."
 }
}

The first replan is triggered by new information, not by an error: the judge sees that build_positioning still assumes a 30% margin. The replanner drops that step and the old recommendation, keeps the pending churn query, and adds the SLA-premium model. The second replan is triggered by the timeout: the failed step is swapped for another data source. Completed steps never run twice.

Step 3: run with a budget of one. Pass the budget as an argument.

Terminal
python3 agent.py 1
Expected output
plan
    1. fetch_competitor_pricing({"market": "storage"})
    2. query_churn_reasons({"months": 6})
    3. build_positioning({"margin_pct": 30})
    4. write_recommendation({"position": "price match"})
  fetch_competitor_pricing -> {"competitor": "X", "price_drop_pct": 25}
replan 1/1: a 25% price cut breaks the 30% margin assumption
    1. query_churn_reasons({"months": 6})
    2. model_sla_premium({"price_drop_pct": 25})
    3. write_recommendation({"position": "premium SLA tier"})
  query_churn_reasons -> {"error": "TimeoutError: churn warehouse did not answer in
{
 "status": "failed",
 "goal": "propose a market entry strategy",
 "blocked_by": "step failed: TimeoutError: churn warehouse did not answer in 10 s",
 "partial_results": {
  "fetch_competitor_pricing": {
   "competitor": "X",
   "price_drop_pct": 25
  }
 },
 "pending": [
  "query_churn_reasons",
  "model_sla_premium",
  "write_recommendation"
 ]
}

With no replans left, the agent stops at the timeout and reports the goal, what blocked it, the result it already has and what is still pending. That report is something a person or a retry job can act on; an agent that kept replanning would only spend more.

Step 4: run with a budget of zero. Predict the result first, then run the command below. This time the run stops after the first step, because new information invalidated the plan and there is no replan left. The agent does not carry on with build_positioning, a step it has just judged to be wrong.

Terminal
python3 agent.py 0
Expected output
plan
    1. fetch_competitor_pricing({"market": "storage"})
    2. query_churn_reasons({"months": 6})
    3. build_positioning({"margin_pct": 30})
    4. write_recommendation({"position": "price match"})
  fetch_competitor_pricing -> {"competitor": "X", "price_drop_pct": 25}
{
 "status": "failed",
 "goal": "propose a market entry strategy",
 "blocked_by": "a 25% price cut breaks the 30% margin assumption",
 "partial_results": {
  "fetch_competitor_pricing": {
   "competitor": "X",
   "price_drop_pct": 25
  }
 },
 "pending": [
  "query_churn_reasons",
  "build_positioning",
  "write_recommendation"
 ]
}

04. Practice questions

Practice check · 3 questions

Plan-and-Execute architecture and replanning check

Three questions on plan validation, what a replan keeps, and what the agent returns when it cannot replan again.

Q1. Why does the lab's runtime check every plan against the tool registry before running it?
Q2. After a replan, which steps does the lab's agent run again?
Q3. You run the lab with a replan budget of zero. The first step reveals the 25% price cut, and the judge says `build_positioning` no longer fits. What does the agent do?
Practice only: not graded, not saved, not evidence.

05. Apply it

Apply these rules to a planning agent of your own:

  • Use a structured JSON output schema for the planner, so your runtime can validate and edit the step list.
  • Feed the executor only the current active step and relevant facts from earlier steps, so its context does not fill up with old plans.
  • Write deterministic rules or evaluation prompts that define exactly what unexpected observations require replanning.
  • When replanning, do not discard or re-run completed steps; only change the pending ones.
  • Set a max_replans limit (for example, 2) and return a clear failure report when it is reached, so the run ends within budget instead of replanning forever.

When you instrument a planning agent, track how often it replans: frequent replans often point to vague plans or unreliable tools that need fixing.

06. Review prompt

Explain why writing the plan down helps on a long task, compared with a plain agent loop that only picks the next step. Describe the four things the lab's runtime does after each step and name the two events that trigger a replan. Then explain what the agent returns when the replan budget is spent, and why that is better than running the old plan to the end.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check