Plan and Execute › Maintaining Flexibility
Michael BrenndoerferJuly 21, 20252 min read
AI Agent HandbookAll chapters Part 9 of 15Planning - Agents with a Plan
Plan and Execute › Maintaining FlexibilityOne section · Sections in this chapter4 / 10 ↓
Sections in this chapter10
The best plans are flexible. As the agent executes steps, it might discover new information that suggests a better approach. Maybe step 1 reveals that the user's preferred destination is fully booked this weekend. A rigid executor would continue anyway, trying to book unavailable hotels. A flexible one would recognize the problem and adjust.
We can build this flexibility into our executor by periodically checking if the plan still makes sense:
In[4]:
Code## Using Claude Sonnet 4.5 for adaptive planning and execution
def execute_with_flexibility(plan, tools):
"""Execute a plan while remaining open to adjustments."""
results = []
current_plan = plan.copy()
for i, step in enumerate(current_plan):
print(f"\nStep {i + 1}: {step}")
# Execute the step
result = execute_step_with_retry(step, tools, results)
results.append({"step": step, "result": result})
# After each step, check if we should continue as planned
if i < len(current_plan) - 1:
should_adjust = check_if_adjustment_needed(
current_plan[i + 1:],
results
)
if should_adjust:
print("\nAdjusting plan based on new information...")
current_plan = replan(current_plan[i + 1:], results, tools)
return results
def check_if_adjustment_needed(remaining_steps, results_so_far):
"""Ask the agent if the plan needs adjustment."""
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=256,
messages=[{
"role": "user",
"content": f"""Given these results: {results_so_far}
And these remaining steps: {remaining_steps}
Should we adjust the plan? Answer yes or no, with brief reasoning."""
}]
)
answer = response.content[0].text.lower()
return "yes" in answerThis creates a feedback loop. The agent executes a step, evaluates whether the plan still makes sense, and adjusts if needed. It's like driving with GPS. The GPS gives you a route, but if you miss a turn or encounter road construction, it recalculates.