Skip to content

Module 05 · Lesson 5.2

Plan-and-Execute Workflows

40 minUpdated 18 Nov 2026Part of Planning and Agent Execution Patterns · AI Agent Development
On this page
  1. What you will learn
  2. What is a plan-and-execute workflow?
  3. Write the plan as data, not as free text
  4. Why a plan written as data can be checked before it runs
  5. Validate a plan in Python
  6. What to do when a step fails
  7. Plan-and-execute vs. ReAct: how to choose
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. References

Before a trip, a careful traveller writes the whole itinerary first: train at 8, flight at 11, hotel at night. Then a friend glances over it and says, "Your train arrives after the flight leaves." Fixing that on paper costs nothing. Fixing it at the airport costs a lot.

Plan-and-execute works the same way for AI agents. The model writes the whole plan first, your code checks it, and only then do the steps run. Most of this lesson needs no coding. One short Python example at the end checks a good plan and rejects a bad one.

What you will learn

  • Explain how plan-and-execute separates planning from doing.
  • Write a plan as data in the JSON plan format used in this module.
  • Check a plan against a list of rules before any step runs.
  • Choose between plan-and-execute and ReAct for a task.

Before you start

What is a plan-and-execute workflow?

In the last lesson the agent chose one step at a time, looked at the result, then chose again. A plan-and-execute workflow does the opposite. It has two separate phases: first the model plans, then your code executes.

Think of an itinerary. Writing it is one job. Following it is another. In between, someone can read it and spot mistakes while no money has been spent.

The four stages of plan-and-execute
  1. Plan

    The model writes all the steps

  2. Check

    Your code tests the plan against rules

  3. Execute

    Your code runs the steps in order

  4. Report

    Save the answer, with approval

The check sits between the plan and the first step. Nothing runs until the plan passes.

This lesson uses a research question from a made-up shop, Quillfeather Cycles: "Which battery should Quillfeather Cycles stock next season: Battery Alpha or Battery Beta?" The agent can read a small set of company documents, labelled RS-01 to RS-06. It has three tools:

  • search_docs(query) finds documents. It only reads.
  • read_doc(doc_id) opens one document, such as RS-01. It only reads.
  • save_report(title) saves the finished report. It writes, so a person must approve it first.

This builds on Task Decomposition and Planning Strategies, where you met fixed and adaptive plans. A fixed plan is written by people. An adaptive plan is changed by the agent as it goes. Plan-and-execute sits in between: the model writes the plan, but your code checks it, and the steps do not change unless you allow a re-plan.

Write the plan as data, not as free text

A plan can be a paragraph of English, such as "First I will read the spec sheets." That is hard for code to check. It is better to ask for the plan as data: a structured list that code can read field by field. This module uses JSON, a plain-text format made of named fields, lists and values.

JSONplan.json
{
  "goal": "Which battery should Quillfeather Cycles stock next season: Battery Alpha or Battery Beta?",
  "steps": [
    {"id": 1, "tool": "read_doc", "args": {"doc_id": "RS-01"}, "after": []},
    {"id": 2, "tool": "read_doc", "args": {"doc_id": "RS-02"}, "after": []},
    {"id": 3, "tool": "read_doc", "args": {"doc_id": "RS-04"}, "after": []},
    {"id": 4, "tool": "save_report", "args": {"title": "Battery recommendation"}, "after": [1, 2, 3]}
  ]
}

One plan for the battery question. Steps 1 to 3 read documents. Step 4 saves the report.

What each field means

goal
The question the plan answers, copied from the user.
id
The step's number. Each step has its own.
tool
Which tool the step uses. It must be a tool you gave the agent.
args
The exact inputs for that tool, such as which document to read.
after
The ids of steps that must finish first. An empty list means the step can start at once.

Notice what the model does here. It does not run anything. It only writes a list. The model also does not call tools by itself in this phase, so a mistake in the plan cannot cause a side effect yet.

Why a plan written as data can be checked before it runs

Here is the big benefit. Because the plan is data, your code can test it before the first step. Think of the traveller's friend again. Finding a clash on paper is cheap. Undoing a bad action later can be slow, costly or impossible. A saved report cannot always be taken back.

The plan rules, as a checklist

Your code should reject any plan that breaks one of these rules:

  • Step count: at least 1 and at most 8 steps.
  • Unique ids: each id is a positive whole number and appears once.
  • Allowed tools: the tool is search_docs, read_doc or save_report. Anything else is rejected.
  • Exact args: each step has exactly the keys its tool needs and no extras. search_docs needs query. read_doc needs doc_id. save_report needs title.
  • ID pattern: a doc_id must match ^RS-[0-9]{2}$, which means "RS-" followed by exactly two digits.
  • Valid after references: every id in after belongs to a step that exists and comes earlier than this step.
  • Save last: at most one save_report, and it must be the final step.
  • Approval: save_report always needs a person's approval when it runs. The plan cannot switch that off.

The approval gate for save_report is the same idea as the approve step for request_return in Practical Lab: Build an Agent That Uses Two Tools. Writes wait for a person.

Validate a plan in Python

The script below turns most of the rules into code. validate_plan returns a list of problems. An empty list means the plan is fine. It runs two plans: a good one and a bad one. No AI model is needed, and nothing goes online. The approval rule is not checked here, because it happens when the step runs.

Pythonvalidate_plan.py
import re

REQUIRED_ARGS = {"search_docs": {"query"}, "read_doc": {"doc_id"}, "save_report": {"title"}}

def validate_plan(plan):
    problems, steps = [], plan.get("steps", [])
    ids = [s["id"] for s in steps]
    if not 1 <= len(steps) <= 8:
        problems.append(f"{len(steps)} steps (allowed 1 to 8)")
    if len(set(ids)) != len(ids):
        problems.append("step ids are not unique")
    for s in steps:
        tool, args = s["tool"], s["args"]
        if tool not in REQUIRED_ARGS:
            problems.append(f"step {s['id']}: unknown tool {tool!r}")
        elif set(args) != REQUIRED_ARGS[tool]:
            problems.append(f"step {s['id']}: wrong args for {tool}")
        elif tool == "read_doc" and not re.fullmatch(r"RS-[0-9]{2}", args["doc_id"]):
            problems.append(f"step {s['id']}: bad doc_id {args['doc_id']!r}")
        for dep in s["after"]:
            if dep not in ids or dep >= s["id"]:
                problems.append(f"step {s['id']}: 'after' {dep} is not an earlier step")
    saves = [i for i, s in enumerate(steps) if s["tool"] == "save_report"]
    if saves and (len(saves) > 1 or saves[0] != len(steps) - 1):
        problems.append("save_report must appear once, as the last step")
    return problems

def read(i, doc_id, after=()):
    return {"id": i, "tool": "read_doc", "args": {"doc_id": doc_id}, "after": list(after)}

def save(i, after):
    return {"id": i, "tool": "save_report", "args": {"title": "Battery recommendation"}, "after": after}

GOAL = "Which battery should we stock next season: Alpha or Beta?"
good = {"goal": GOAL, "steps": [read(1, "RS-01"), read(2, "RS-02"), read(3, "RS-04"), save(4, [1, 2, 3])]}
bad = {"goal": GOAL, "steps": [{**read(1, "RS-01"), "tool": "delete_doc"}, read(2, "RS-7", [3]), save(3, [1]), read(4, "RS-04")]}

for name, plan in [("good plan", good), ("bad plan", bad)]:
    problems = validate_plan(plan)
    print(f"{name}: {'OK' if not problems else 'REJECTED'}")
    for p in problems:
        print("  -", p)

Runs offline with Python 3.10 or later. Run it with python validate_plan.py.

What each part does

  • REQUIRED_ARGS is a dictionary that pairs each allowed tool with the argument names it needs. A tool missing from it is not allowed.
  • validate_plan(plan) starts with an empty problems list and adds one message for each rule that fails.
  • re.fullmatch(r"RS-[0-9]{2}", ...) tests the document ID pattern. "Full" means the whole text must match, not just a part.
  • dep >= s["id"] catches an after that points to the same step or a later one. A step cannot wait for something that has not happened yet.
  • saves collects the positions of save_report steps. The rule fails if there are two, or if the only one is not last.
  • read(...) and save(...) are small helpers that build step dictionaries, so the two plans stay short.
  • The bad plan breaks four rules at once: an unknown tool, a bad document ID, an after pointing forward, and save_report in the middle.
OutputCaptured from a real run
good plan: OK
bad plan: REJECTED
  - step 1: unknown tool 'delete_doc'
  - step 2: bad doc_id 'RS-7'
  - step 2: 'after' 3 is not an earlier step
  - save_report must appear once, as the last step

The rejected plan never reaches the executor. Nothing was read and nothing was saved. This is also a good place to log the problems, which helps you see what the model gets wrong.

What to do when a step fails

Plans are checked before they run, but the world can still surprise you. A document may be missing, or a tool may time out. You need a rule for this in advance. Tool errors come back as an error message, as you saw in Tool Errors, Retries, Timeouts and Idempotency. The executor then has two choices.

Choice 1: stop

Stop the run, keep the results so far, and tell a person which step failed and why. This is the safest choice. It is the right default.

Choice 2: ask for a revised plan

Send the model the goal, the finished steps with their results and the error. Ask for a new plan for the remaining work. This is called re-planning. Like a satnav after a closed road, the agent finds another route.

  • Run the new plan through the same checks as the first one.
  • Keep the results of steps that already succeeded. Do not run them again.
  • Set a re-plan limit, such as 2. After that, stop and hand over to a person. Without a limit, a failing task can loop and cost money.
  • Never let a re-plan skip the approval gate for save_report.

Plan-and-execute vs. ReAct: how to choose

Both patterns can finish the battery research. They differ in who steers and when. In ReAct, the model decides the next step after every result. In plan-and-execute, the model decides everything up front and your code steers.

Plan-and-executeReAct
PredictabilityHigh. You can read the full plan before anything runs.Lower. You only see each step after it is chosen.
CostOften lower. One planning call, then steps that need few model calls.Higher for long tasks. A model call before every step.
FlexibilityLower. A surprise needs a re-plan.Higher. Each result can change the next step.
Safety checksEasy. Validate the whole plan first.Harder. Each step must be checked as it appears.
Choose it whenThe steps are mostly known, such as reading named documents and then saving a report.The next step depends on what you find, such as tracking down an unknown cause.
Many real agents mix both: a plan for the known part, ReAct inside one open-ended step.

The research community has studied this idea too. A paper called Plan-and-Solve Prompting asks a model to write a plan inside its answer and then follow it, which helps it skip fewer steps. This lesson goes one step further: the plan is data that your code checks and runs. For a wider view of when to use simple workflows or agents, read Anthropic's Building effective agents (opens in a new tab).

Conclusion and your next step

Plan-and-execute splits one hard job into two easier ones. The model writes the plan as data. Your code checks it against clear rules, then runs it. If a step fails, you stop, or you ask for a new plan within a set limit. A checked plan is cheaper to fix than a bad action is to undo.

Your next step: take the plan JSON above and break one rule on purpose, for example point an after forward. Run validate_plan.py and watch it reject the plan. Then continue to Sequential, Parallel and Conditional Tool Execution, where you use the after field to decide which steps can run together.

Want more background first? Read The Tool-Calling Loop: Reference Diagram, or review the Agent Launch Safety Checklist before you let any agent write anything.

Common errors and how to fix them

A plan step uses a tool the agent was never given, such as delete_doc.

Why it happens: The model invents a plausible-sounding tool, or the plan was not checked.

Fix: Check every step's tool against a fixed list of allowed tools, and reject the whole plan if one is unknown.

A step waits for a result that does not exist yet.

Why it happens: An after list points to a later step or to an id that is not in the plan.

Fix: Require that every id in after exists and is smaller than the step's own id.

The agent keeps re-planning and never finishes.

Why it happens: There is no limit on re-plans, so each failure triggers another new plan.

Fix: Count re-plans in code. After the limit, stop and hand over to a person.

A report is saved without anyone looking at it.

Why it happens: The plan was trusted, and the approval rule lived only in the instructions.

Fix: Make your code ask a person before every save_report, whatever the plan says.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Check and fix two plans for the battery question

Below are two plans for the question "Which battery should Quillfeather Cycles stock next season?". For each one, list every rule it breaks, then write the corrected steps. Use the plan rules from this lesson.

You will need

  • Plan A: step 1 read_doc RS-01 after []; step 2 read_doc RS-02 after [1, 5]; step 3 save_report title "Battery recommendation" after [1, 2].
  • Plan B: step 1 search_docs with args {"query": "battery", "limit": 3}; step 2 save_report title "Report" after [1]; step 3 read_doc RS-06 after [2].
  • Rules: 1 to 8 steps, allowed tools only, exact args, doc_id like RS-01, after ids exist and are earlier, save_report once and last.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Check each rule against each step, one rule at a time.
  • Step 2 of Plan A is allowed to wait for step 1, but not for step 5.
  • In Plan B, move the read_doc step before save_report and update the after lists.
Show a model answer

Plan A breaks one rule: step 2 says after [1, 5] but there is no step 5, and a step may only wait for earlier steps. The fix is after [] or [1] for step 2, for example [1]. Plan B breaks two rules. Step 1 has an extra key, limit, so its args are not exactly query. Also save_report is step 2 while a read_doc step comes after it, so save is not last. A corrected Plan B has step 1 search_docs with args {"query": "battery"} after [], step 2 read_doc RS-06 after [1], and step 3 save_report after [1, 2]. Both corrected plans still pause for approval at save_report, because that gate lives in your code, not in the plan.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.What is the main benefit of writing a plan as data?
    Show the answer and explanation

    Answer: B. Data can be tested field by field, so a bad plan is caught while it is still only text. JSON does not make the model smarter, which is the tempting claim, and the speed of reading it is not the point.

  2. 2.A plan has save_report as step 2 and a read_doc as step 3. What should your code do?
    Show the answer and explanation

    Answer: A. The plan rules say the one save_report comes last, so the research is finished before anything is saved. Running it because the model chose the order is tempting, but the plan is only a request. Silently editing the plan hides the model's mistake.

  3. 3.A step fails and the agent has already re-planned twice, which is the limit. What now?
    Show the answer and explanation

    Answer: C. A re-plan limit exists so a failing task cannot loop forever. A third plan breaks the limit. Saving a report with a missing step risks a wrong answer in a saved file.

Frequently asked questions

What is plan-and-execute in AI agents?

It is a pattern with two phases. First the model writes a full plan. Then your code runs the steps in order. Because the plan comes first, you can check it before anything happens.

What is the difference between plan-and-execute and ReAct?

In ReAct the model picks one step at a time and looks at each result before choosing the next. In plan-and-execute the model writes all the steps first and your code runs them. Plan-and-execute is easier to check. ReAct is more flexible.

Can an agent change its plan while it runs?

Yes, through re-planning. When a step fails, you can ask the model for a revised plan for the remaining work. Set a limit on how often this may happen, and check each new plan with the same rules.

Why does the plan need to be JSON?

It does not have to be JSON, but the plan should be structured data. Plain sentences are hard for code to check. JSON gives named fields, so code can test things like which tool is used and which steps come first.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.