Time: 45 minutes | Difficulty: Intermediate
The Plan-and-Execute pattern separates planning from execution into two distinct phases. Unlike ReAct which interleaves thinking and action, Plan-and-Execute creates a complete plan upfront, then executes it systematically.
By the end of this tutorial, you'll be able to:
- Understand the Plan-and-Execute pattern
- Separate planning from execution
- Create detailed action plans before executing
- Monitor execution and handle failures
- Revise plans based on execution results
- Compare Plan-and-Execute with ReAct
We'll implement agents that:
- Plan Phase - Analyze task and create detailed action plan
- Execute Phase - Systematically execute each planned step
- Monitor Phase - Track progress and detect issues
- Revise Phase - Update plan if needed
Make sure you have:
- Completed Tutorial 8: Tree of Thoughts
- Understanding of ReAct pattern
- PHP 8.1+ installed
- Claude PHP SDK configured
Plan-and-Execute divides work into two phases:
Think → Act → Observe → Think → Act → Observe → ...
PLAN: Analyze → Break down → Sequence steps
↓
EXECUTE: Step 1 → Step 2 → Step 3 → ...
Create comprehensive plan before any action:
$planPrompt = "Task: {$task}\n\n" .
"Create a detailed step-by-step plan. For each step:\n" .
"1. Describe the action\n" .
"2. What tool to use\n" .
"3. Expected outcome\n" .
"4. Dependencies on previous steps";Follow the plan systematically:
foreach ($plan->steps as $step) {
echo "Executing: {$step->action}\n";
$result = executeTool($step->tool, $step->input);
$step->result = $result;
if ($result->isError) {
// Handle failure
}
}Track execution progress:
$monitor = [
'completed' => [],
'current' => $currentStep,
'remaining' => $remainingSteps,
'failures' => []
];Update plan if execution reveals issues:
if ($executionFailed) {
$revisedPlan = revisePlan($originalPlan, $executionResults);
}| Aspect | Plan-and-Execute | ReAct |
|---|---|---|
| Planning | Upfront, complete | Interleaved with action |
| Flexibility | Less (follows plan) | High (adapts constantly) |
| Efficiency | Better (no wasted actions) | Can be exploratory |
| Complexity | Simpler execution | Complex loop |
| Best For | Well-defined tasks | Exploratory tasks |
| Resource Use | Predictable | Variable |
$analysisPrompt = "Task: {$task}\n\n" .
"Analyze this task:\n" .
"1. What is the end goal?\n" .
"2. What information do we need?\n" .
"3. What tools are available?\n" .
"4. What are the constraints?";$planningPrompt = "Task: {$task}\n\n" .
"Available tools: {$toolsList}\n\n" .
"Create a detailed plan with these sections:\n\n" .
"STEPS:\n" .
"1. [Action] - Tool: [tool_name] - Expected: [outcome]\n" .
"2. ...\n\n" .
"DEPENDENCIES:\n" .
"- Step 2 depends on Step 1 result\n\n" .
"RISKS:\n" .
"- Potential issues and mitigation";function validatePlan($plan) {
// Check all dependencies are satisfied
// Verify tools exist
// Ensure steps are ordered correctly
// Check for circular dependencies
}function executePlan($client, $plan, $tools) {
$results = [];
$context = [];
foreach ($plan->steps as $i => $step) {
echo "Step " . ($i + 1) . ": {$step->description}\n";
// Execute with context from previous steps
$result = executeStep($step, $context, $tools);
if ($result->success) {
$results[] = $result;
$context[$step->id] = $result->data;
} else {
// Handle failure
return handleFailure($plan, $i, $result);
}
}
return $results;
}function handleFailure($plan, $failedStepIndex, $error) {
// Options:
// 1. Retry the step
// 2. Skip and continue
// 3. Revise plan
// 4. Abort mission
if ($error->isRecoverable) {
return retryStep($plan->steps[$failedStepIndex]);
} else {
return revisePlan($plan, $failedStepIndex, $error);
}
}When execution reveals issues:
$revisionPrompt = "Original plan: {$originalPlan}\n\n" .
"Execution so far:\n" .
"- Completed: {$completedSteps}\n" .
"- Failed: {$failedStep} - Reason: {$error}\n\n" .
"Revise the plan to:\n" .
"1. Work around the failure\n" .
"2. Maintain completed progress\n" .
"3. Still achieve the goal";Task: Research and summarize the benefits of serverless architecture
PLAN:
1. Search for serverless architecture overview
Tool: web_search
Expected: General information about serverless
2. Search for serverless benefits
Tool: web_search
Expected: List of key advantages
3. Search for serverless case studies
Tool: web_search
Expected: Real-world examples
4. Synthesize findings
Tool: none (pure reasoning)
Expected: Coherent summary with sources
EXECUTE:
✓ Step 1: Found overview (5 sources)
✓ Step 2: Found 8 key benefits
✓ Step 3: Found 3 case studies
✓ Step 4: Created summary document
For independent steps:
// Identify independent steps
$parallelBatches = groupIndependentSteps($plan);
foreach ($parallelBatches as $batch) {
$promises = [];
foreach ($batch as $step) {
$promises[] = executeStepAsync($step);
}
$results[] = await($promises);
}Plans with branches:
"Step 3: IF Step 2 found more than 5 results THEN
summarize top 5
ELSE
search with broader query";Track and limit resource usage:
$plan->estimatedCost = [
'api_calls' => 10,
'tokens' => 15000,
'time_seconds' => 30
];Use Plan-and-Execute when:
- ✅ Task is well-defined
- ✅ Steps are predictable
- ✅ Efficiency is important
- ✅ Resource budgets are fixed
- ✅ Need audit trail
- ✅ Parallel execution possible
Use ReAct when:
- ✅ Task is exploratory
- ✅ Outcomes uncertain
- ✅ Flexibility needed
- ✅ Learning as you go
- ✅ Dynamic environments
Track execution:
$metrics = [
'plan_generation_time' => 2.5, // seconds
'total_steps' => 8,
'completed_steps' => 6,
'failed_steps' => 1,
'retries' => 2,
'execution_time' => 45.2,
'cost' => 0.0234, // dollars
'success_rate' => 0.875
];function visualizePlan($plan) {
echo "EXECUTION PLAN\n";
echo str_repeat("=", 60) . "\n\n";
foreach ($plan->steps as $i => $step) {
$status = $step->completed ? "✓" :
($step->inProgress ? "⏳" : "⭘");
echo "{$status} Step " . ($i + 1) . ": {$step->description}\n";
echo " Tool: {$step->tool}\n";
echo " Expected: {$step->expected}\n";
if ($step->dependencies) {
echo " Depends on: " . implode(", ", $step->dependencies) . "\n";
}
echo "\n";
}
}Before moving on, make sure you understand:
- Difference between Plan-and-Execute and ReAct
- How to create comprehensive plans
- Systematic execution of planned steps
- When to revise vs abort
- Monitoring execution progress
- When each pattern is most appropriate
You've mastered Plan-and-Execute! But what if we want our agent to evaluate and improve its own work?
Tutorial 10: Reflection & Self-Critique →
Learn how to build agents that reflect on and improve their outputs!
Run the complete working example:
php tutorials/09-plan-and-execute/plan_execute_agent.phpThe script demonstrates:
- ✅ Planning phase with explicit strategies
- ✅ Systematic execution of plan steps
- ✅ Progress tracking and monitoring
- ✅ Plan revision on failure
- ✅ Comparison with ReAct approach
- ✅ Visualization of execution flow
- Separate planning from execution - Think first, act later
- Complete plans upfront - Less trial and error
- Systematic execution - Follow the plan
- Monitor progress - Track what works
- Revise when needed - Plans aren't perfect
- Better efficiency - Fewer wasted actions
- Audit trail - Know what was done and why
- LangChain Plan-and-Execute
- AutoGPT Architecture
- Tutorial 2: ReAct Basics - Comparison
- Tutorial 11: Hierarchical Agents - Next level
Break down projects into tasks, assign resources, execute systematically.
Plan data transformation steps, execute in order, handle failures gracefully.
Plan article structure, research each section, write systematically.
Plan deployment steps, execute with rollback capability, monitor progress.