Plan-and-Execute and Dynamic Planning

Write the route down before setting off, check it, and change it when the road does.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

A plan-and-execute agent first produces a list of steps, then carries them out, usually with a separate and cheaper executor. A dynamic planner revises the remaining steps when results differ from expectations. The plan is data you can validate, show to a person and measure.

What you will learn: the architecture, how to represent and check a plan, how to enforce constraints and policy, when and how to replan, and when this pattern beats step-by-step agents.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and ideally ReAct Agents: Reasoning and Acting. Basic Python.

Beginner Plans in plain words

Why plan first?

Organizing a workshop involves booking a room, ordering food and inviting people. If you improvise, you may order food before knowing the room. A written plan shows the order, exposes missing steps and lets someone else check it before money is spent.

Agents gain the same things:

  • Overview: the whole task is considered at once.
  • Review: a person or program can approve the plan before any action.
  • Efficiency: routine steps may need no large model call.
  • Parallel work: independent steps can run together.
  • Progress: you can show what is done and what remains.

The architecture

PlannerGoal to list of steps
ValidatorTools, order, limits, policy
ExecutorRuns one step at a time or in parallel
MonitorDid reality match?
↺ On failure or surprise, replan only what remains
When all steps and the final success check pass, a synthesizer writes the report.
PartJobOften implemented as
PlannerBreak the goal into stepsA capable model with structured output
ValidatorReject impossible or forbidden plansOrdinary code and rules
ExecutorPerform each stepCode, a smaller model, or a small ReAct loop
MonitorCheck results and assumptionsCode checks, sometimes a model
SynthesizerReport the outcomeA model reading the recorded results

Compared with ReAct

QuestionReActPlan-and-execute
When are steps chosen?One at a timeMostly in advance
Can the route be reviewed?Only as it happensYes, before execution
Reaction to surprisesImmediateNeeds monitoring and replanning
Large-model callsEvery stepMainly planning and replanning
Parallel stepsHarderNatural when dependencies are explicit
Best forExplorationStructured, multi-step tasks
Intermediate Represent, check and run a plan

A plan is data

Ask the planner for structured output instead of a paragraph. Each step needs enough information to be checked and run without guessing.

{
  "id": "food",
  "tool": "order_food",
  "args": {"people": 8},
  "after": ["room"],
  "why": "Lunch is part of the request",
  "success": "supplier returns an order number"
}

The after field turns a list into a graph. Steps with no unmet dependency can run at the same time. Where a later step needs an earlier result, refer to it by name and let the executor fill it in, rather than letting the planner guess the value.

Instructing the planner

The planner needs different instructions from an executor. It should think about structure and not perform the task.

You plan work; you do not carry it out.
Goal: <the goal>
Constraints: <hard limits first, then preferences>
Available tools: <names, descriptions, input schemas>
Already completed: <step ids and results>

Return a list of steps in the required format.
- Use only the listed tools.
- Give each step an id, its dependencies and a success test.
- Put checks that could stop the task early.
- Put actions that cannot be undone last.
- If the goal cannot be met, return no steps and say why.

The last line matters. Without a permitted way to say "impossible", a planner tends to produce a confident plan that cannot work. Use your provider's structured output feature where available, and validate the result either way.

Working example

The planner below is a stand-in for a model. Everything else is real: validation before execution, stopping on failure, and replanning only the remaining work.

"""Plan-and-execute with validation, dependencies and one replan."""

def book_room(args, world):
    if args["room"] in world["unavailable"]:
        raise RuntimeError(f"room {args['room']} is unavailable")
    world["booked"] = args["room"]
    return f"booked {args['room']}"

def order_food(args, world):
    if "booked" not in world:
        raise RuntimeError("no room booked")
    return f"food for {args['people']} to room {world['booked']}"

def send_invite(args, world):
    return f"invite sent for room {world['booked']}"

TOOLS = {"book_room": book_room, "order_food": order_food, "send_invite": send_invite}

def planner(goal, done, failure=None):
    """Stand-in for a model call that returns a plan as data."""
    room = "B" if failure else "A"
    steps = [
        {"id": "room", "tool": "book_room", "args": {"room": room}, "after": []},
        {"id": "food", "tool": "order_food", "args": {"people": 8}, "after": ["room"]},
        {"id": "invite", "tool": "send_invite", "args": {}, "after": ["room", "food"]},
    ]
    return [s for s in steps if s["id"] not in done]

def validate(plan, done, budget=6):
    """Check the whole plan before running any of it."""
    if len(plan) > budget:
        return "plan too long"
    known = set(done)
    for step in plan:
        if step["tool"] not in TOOLS:
            return f"unknown tool {step['tool']}"
        if not set(step["after"]) <= known:
            return f"step {step['id']} depends on something not done before it"
        known.add(step["id"])
    return None

def run(goal, world, max_replans=2):
    done, failure = {}, None
    for attempt in range(max_replans + 1):
        plan = planner(goal, done, failure)
        problem = validate(plan, done)
        if problem:
            return f"rejected plan: {problem}"
        print(f"plan {attempt + 1}: {[s['id'] for s in plan]}")
        for step in plan:
            try:
                done[step["id"]] = TOOLS[step["tool"]](step["args"], world)
                print("  ok  ", done[step["id"]])
            except RuntimeError as exc:
                failure = {"step": step["id"], "error": str(exc)}
                print("  fail", failure["error"])
                break                              # stop and replan
        else:
            return "complete"
    return "needs a person"

print(run("Set up Friday's workshop", {"unavailable": {"A"}}))

Output:

plan 1: ['room', 'food', 'invite']
  fail room A is unavailable
plan 2: ['room', 'food', 'invite']
  ok   booked B
  ok   food for 8 to room B
  ok   invite sent for room B
complete

Room A is unavailable, so the first plan stops at once. Food is not ordered for a room that does not exist. The second plan chooses room B. Completed steps are removed from new plans, so a successful booking would not be repeated.

Reading the run

Three decisions in the example are worth naming, because real systems must make them too.

  1. What stops the plan? Any failed step breaks out of the loop. A gentler system might continue with steps that do not depend on the failure.
  2. What is carried forward? The done record and the failure reason go to the planner. Without the reason, it might propose room A again.
  3. When does it give up? After two replans the function returns "needs a person". An unbounded replanning loop is just an agent loop with extra cost.

Try making both rooms unavailable and confirm that the program ends. Then add a step with a tool called fire_confetti and watch validation reject the plan before anything runs.

Keep plan state outside the model

Store each step with a status such as pending, running, done, failed, skipped or waiting for approval, along with its result and timestamps. The runtime owns these statuses; the model may suggest changes but cannot mark its own work done. This record gives users a progress view, lets a restarted process continue where it stopped and prevents a finished payment from running twice.

Validate before you execute

A plan is a proposal from a model. Check it as you would any untrusted input.

  • Every tool exists and the user may use it.
  • Arguments match each tool's schema.
  • Dependencies refer to real steps and contain no cycle.
  • The number of steps and estimated cost are within budget.
  • Forbidden combinations are absent.
  • Steps needing approval are marked.

Constraint-based planning

Constraints state what any acceptable plan must respect. Hard constraints may never be broken, such as a budget or a legal requirement. Soft constraints are preferences, such as a morning start. Put both in the planner's instructions so it can aim well, and check hard ones in code so that aiming badly is harmless.

Constraint typeExampleChecked
ResourceTotal cost at most $500Before and during execution
OrderApproval before paymentOn the dependency graph
TimeFinish before Friday noonAgainst estimates and the clock
AccessNo personal data to external toolsAt each tool call
PreferencePrefer an existing supplierScored, not enforced

For problems with many interacting constraints, such as rota scheduling, give the search to a dedicated solver and let the model translate the request into its inputs. Classical methods are introduced in Planning and Search Algorithms.

Policy-guided execution

Validation happens once, but the world changes while steps run. Check policy again at the moment of each action, with the real arguments: who is asking, which resource, how much, and whether approval was given for exactly this. A plan approved in the morning does not authorize a different amount in the afternoon. Keep the policy outside the model and record each decision. See Action Guardrails and Policy Engines.

Expert Dynamic planning at scale

Dynamic planning: when to replan

TriggerExampleTypical response
Step failedRoom unavailableReplan the remaining steps
Assumption brokenAttendance doublesRevisit affected steps, including finished ones
New informationA cheaper option appearsReplan only if the gain justifies the disruption
Budget pressureHalf the time left, most work remainingReduce scope and say so
User change"Make it Thursday"Pause, update goal and constraints, replan

Replanning every turn throws away the benefits of planning and can cause the agent to oscillate between options. Replanning too rarely lets it follow a stale route. Define triggers in code where possible, limit the number of replans, and give the planner the reason for the new plan along with results so far.

Handle work already done

Some completed steps become wrong when the plan changes. For each action with an effect, know how to compensate: cancel the booking, withdraw the order, send a correction. If an action cannot be undone, place it as late in the plan as possible and require approval. Engines that manage this durably are discussed in Durable Execution, Checkpoints and Approvals.

Parallel execution

Running independent steps together shortens the total time, but they must not change the same resource, and your rate limits still apply. Decide in advance what happens when one branch fails: cancel the others, or let them finish and replan with their results.

How plans go wrong

ProblemSignRemedy
Too vague"Handle logistics"Require a tool and success test per step
Too detailedFifty tiny steps that break at oncePlan milestones; let the executor handle detail
Imagined capabilityUses a tool that does not existValidate names; list tools clearly
Hidden assumptionAssumes a free roomAdd an early check step
Missing final checkAll steps pass, goal unmetTest the goal itself at the end
Planner and executor disagreeExecutor reinterprets a stepPass the purpose and success test with each step

A security advantage, with limits

Because the plan is made before the agent reads untrusted material, you can restrict execution to the approved steps. Text found in a document then has less opportunity to add new actions. It can still corrupt the data that flows between steps, and a replan that reads that data can be influenced. Treat this as one layer, not a solution. See Prompt Injection Attacks and Defenses.

Hybrid designs

You rarely have to choose one pattern for a whole system.

DesignHow it worksFits
Plan, then ReAct per stepMilestones are fixed; each is explored step by stepLong tasks with uncertain detail
ReAct, then planInvestigate first, then write a plan for the changeCoding and operations work
Rolling planPlan the next few steps, execute, extendChanging environments
Template plus agentA fixed workflow calls an agent for one hard stageRegulated processes

The second design is popular where changes are risky: the exploration uses read-only tools, the plan is reviewed by a person, and only the approved plan receives write access.

Showing plans to people

A plan is a natural place for human control, if it can be read quickly. Show the goal, the steps in order, which of them change something, the expected cost and what cannot be undone. Let the reviewer remove or edit a step, then validate the edited plan again, because a changed plan is a new plan. Record who approved which version. If a later replan adds a consequential action or exceeds the approved cost, pause and ask again instead of treating the first approval as covering it.

Plan v2 for "Friday workshop"        estimated cost: 420 (limit 500)
1. Book room B                       changes data, cancellable
2. Order lunch for 8                 spends money, cancel by Wednesday
3. Send invitation to 8 people       cannot be unsent
Changed since v1: room A unavailable, replaced by room B
Approve all / edit / reject

Avoid asking for approval of every trivial step. People who approve dozens of harmless items start approving without reading.

What to measure

  • Share of plans that pass validation first time.
  • Replans per task, and their causes.
  • Steps executed that did not contribute to the goal.
  • Goal success, cost and time compared with a step-by-step baseline on the same tasks.
Expert tip

Cache good plans as templates. When a request matches a task you have solved many times, start from the reviewed template and let the model only fill in values. Over time, the most common templates become ordinary workflows.

Frequently asked questions

Is plan-and-execute always cheaper than ReAct?

Not always. It can save large-model calls on long, predictable tasks. Frequent replanning can remove the saving. Compare both on your own tasks.

Should a person approve every plan?

Approve according to risk. Low-risk read-only plans can run automatically; plans containing consequential actions deserve review of those steps.

Can the executor be another agent?

Yes. Each step can be a small agent with its own tools and limits. Pass it a clear task and a required result format.

How long should a plan be?

Short enough that each step is still likely to be valid when reached. For uncertain tasks, plan the next few milestones in detail and keep later ones broad.

References and further reading

Next steps