Agentic AIPythonverifiedVerified

Plan-and-Execute Pattern in Python

Separate high-level planning from step-by-step execution: one LLM call produces a structured plan, then individual executor calls carry out each step, with replanning triggered by unexpected results.

How to Implement the Plan-and-Execute Pattern in Python

1Step 1: Define the Step and Plan data structures

from dataclasses import dataclass, field
from typing import Callable, Awaitable, Literal


@dataclass
class Step:
    id: str
    description: str
    status: Literal["pending", "running", "done", "failed"] = "pending"
    result: str | None = None


@dataclass
class Plan:
    goal: str
    steps: list[Step]


Planner = Callable[[str], Awaitable[list[Step]]]
Executor = Callable[[Step], Awaitable[str]]

2Step 2: Implement the plan-and-execute loop

async def plan_and_execute(
    goal: str,
    planner: Planner,
    executor: Executor,
) -> Plan:
    raw_steps = await planner(goal)
    plan = Plan(goal=goal, steps=raw_steps)

    for step in plan.steps:
        step.status = "running"
        try:
            step.result = await executor(step)
            step.status = "done"
        except Exception as exc:
            step.result = str(exc)
            step.status = "failed"
            break

    return plan

3Step 3: Run the pipeline with a sample goal

async def main() -> None:
    async def planner(goal: str) -> list[Step]:
        return [
            Step("1", "Research the topic"),
            Step("2", "Draft the outline"),
            Step("3", "Write the post"),
            Step("4", "Review and publish"),
        ]

    async def executor(step: Step) -> str:
        print(f"Executing: {step.description}")
        return f"Completed: {step.description}"

    plan = await plan_and_execute(
        "Write and publish a blog post", planner, executor
    )
    for s in plan.steps:
        print(f"[{s.status}] {s.description}")


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Plan-and-Execute Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Plan-and-Execute Pattern in the Real World

A building contractor (Planner) reviews the architectural blueprints and produces a phased construction schedule: foundation, framing, electrical, finishing. Individual trade crews (Executors) carry out each phase. If an inspection fails (unexpected result), the contractor revises the remaining schedule rather than demolishing the entire building and starting over.