Agentic AIPHPverifiedVerified

Plan-and-Execute Pattern in PHP

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 PHP

1Step 1: Define the plan and step structures

class PlanStep
{
    public function __construct(
        public readonly string $description,
        public readonly string $tool,
        public string $status = 'pending',
        public ?string $result = null,
    ) {}
}

class Plan
{
    /** @var PlanStep[] */
    public array $steps = [];

    public function addStep(string $description, string $tool): void
    {
        $this->steps[] = new PlanStep($description, $tool);
    }

    public function isComplete(): bool
    {
        return empty(array_filter($this->steps, fn(PlanStep $s) => $s->status === 'pending'));
    }
}

2Step 2: Implement the planner that generates a plan from a task

function createPlan(string $task, callable $llm): Plan
{
    $response = $llm("Break this task into steps: {$task}");
    $plan = new Plan();

    // Parse LLM response into steps
    foreach (explode("\n", $response) as $line) {
        if (trim($line) !== '') {
            $plan->addStep(trim($line), 'default');
        }
    }

    return $plan;
}

3Step 3: Execute each step in the plan sequentially

function executePlan(Plan $plan, callable $executor): string
{
    foreach ($plan->steps as $step) {
        $step->result = $executor($step->description, $step->tool);
        $step->status = 'completed';
    }

    $results = array_map(fn(PlanStep $s) => $s->result, $plan->steps);
    return implode("\n", array_filter($results));
}

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.