Plan and Execute › When to Re-Plan

Michael BrenndoerferJuly 21, 20252 min read
AI Agent HandbookAll chapters
Part 9 of 15Planning - Agents with a Plan
Chapter 25Plan and Execute › When to Re-Plan
Reading section 6 of 10 · When to Re-Plan · 2 minSection 6 of 10 · 2 min

Book contents

Section 6 of 10 · 2 min read

Plan and Execute › When to Re-PlanOne section · Sections in this chapter6 / 10 ↓

Sometimes execution reveals that the original plan won't work. Maybe the user's requirements were unclear, or the situation changed. In these cases, the agent needs to go back to the planning phase.

Here are signs that re-planning might be necessary:

  • Multiple consecutive failures: If several steps in a row fail, the plan might be fundamentally flawed.
  • Changed requirements: The user provides new information that invalidates the plan.
  • Impossible constraints: The agent discovers that the goal can't be achieved as originally envisioned.

When re-planning, the agent should use everything it learned from the failed execution. This is valuable information. If the hotel search failed because everywhere is booked, the new plan might include alternative dates or nearby cities.

In[5]:
Code
## Using Claude Sonnet 4.5 for adaptive re-planning
def replan_if_needed(original_plan, execution_results, user_request):
    """Create a new plan if execution revealed problems."""
    
    # Analyze the execution results
    failures = [r for r in execution_results if "error" in r]
    
    if len(failures) > 2:  # Multiple failures suggest plan issues
        print("\nMultiple failures detected. Re-planning...\n")
        
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=1024,
            messages=[{
                "role": "user",
                "content": f"""Original request: {user_request}

Original plan: {original_plan}

Execution results: {execution_results}

The original plan encountered problems. Create a new plan that accounts 
for what we learned. Be specific about what to do differently."""
            }]
        )
        
        new_plan = response.content[0].text
        print(f"New plan:\n{new_plan}")
        return new_plan
    
    return original_plan

This creates a learning loop. The agent tries a plan, sees what works and what doesn't, and adjusts accordingly. Over time, with enough examples, an agent can get better at creating plans that are more likely to succeed on the first try.