Lesson 5 of 5 · Planning
When Plans Fail
What AI agents should do when a step fails: transient vs permanent errors, retries with backoff, no duplicate side effects, replanning, loops and escalation.
- 8 min read
- Advanced
- Reviewed
- Tell transient errors from permanent ones, and respond to each correctly
- Retry safely with backoff, without repeating side effects
- Replan from the current state, keeping finished steps
- Detect loops and set limits on retries, replans and budget
- Handle half-finished plans and escalate to a person with a useful report
Plans meet reality
No plan survives every tool call. Services time out, flights sell out, files aren't where they should be, and users change their minds halfway through. A good agent isn't one whose plans never fail; it's one that fails well.
The right response depends on what kind of failure it is:
| What happened | Example | Response |
|---|---|---|
| Transient error | Timeout, rate limit, server busy | Retry after a short wait, a few times |
| Permanent error | Sold out, not found, not allowed | Don't retry the same thing: replan or find an alternative |
| Surprising result | The search returns no flights at all | Rethink the assumptions: replan or ask |
| Goal changed | “Actually, make it Porto” | Replan from the current state |
| Stuck | The same action keeps repeating | Stop and change approach, or ask |
| Out of budget | Too many steps, too much money or time | Stop and report what's done |
Retry, replan or stop
This executor handles all three. The first trip hits a timeout (retry), then a sold-out flight (replan). The second trip can't be fixed, so the agent stops and asks a person:
# Executing a plan when the world doesn't cooperate: retry, replan, or stop and ask.
class Transient(Exception): pass # might work if tried again: timeouts, rate limits
class Permanent(Exception): pass # won't work if repeated: sold out, not allowed
calls = {}
def tool(name, arg):
"""Fake tools: the first FL-101 booking times out, then FL-101 turns out to be sold out,
and there are no hotels left in Porto."""
calls[(name, arg)] = calls.get((name, arg), 0) + 1
if (name, arg) == ("book_flight", "FL-101"):
if calls[(name, arg)] == 1:
raise Transient("timeout")
raise Permanent("FL-101 is sold out")
if (name, arg) == ("book_hotel", "Porto, 2 nights"):
raise Permanent("no rooms left in Porto that weekend")
return f"{name}({arg}) ok"
def replan(failed_step, error, done):
"""Stands in for an LLM asked to rewrite the REST of the plan, given what's done and what failed."""
if failed_step == ("book_flight", "FL-101"):
return [("book_flight", "FL-208"), ("book_hotel", "Lisbon, 2 nights"), ("send_itinerary", "Mei")]
return None # no sensible way to recover
def execute(plan, max_retries=2, max_replans=2):
done, replans = [], 0
while plan:
step = plan[0]
for attempt in range(1, max_retries + 2):
try:
print(" ", tool(*step))
done.append(step[0])
plan = plan[1:]
break
except Transient as e:
wait = 2 ** attempt # back off: 2s, 4s... (a real agent would sleep here)
print(f" {step[0]}: {e}, retry {attempt} after {wait}s")
except Permanent as e:
print(f" {step[0]}: {e}")
new_plan = replan(step, e, done) if replans < max_replans else None
if new_plan is None:
print(f" Stopping and asking a person. Done so far: {done}")
return done
replans += 1
print(f" Replanned, keeping {done}; next: {new_plan[0]}")
plan = new_plan
break
else:
print(f" Stopping: {step[0]} still failing after {max_retries} retries.")
return done
return done
print("Trip to Lisbon:")
execute([("search_flights", "LYS-LIS 12 Mar"), ("book_flight", "FL-101"),
("book_hotel", "Lisbon, 2 nights"), ("send_itinerary", "Mei")])
print("Trip to Porto:")
execute([("book_flight", "FL-330"), ("book_hotel", "Porto, 2 nights"), ("send_itinerary", "Mei")])For the Lisbon trip, the replan kept the finished flight search and rewrote only the rest of the plan. The agent didn't start over. For Porto, there was nothing sensible to try, so the agent stopped. Note what it reports: a flight is already booked. Whoever takes over needs to know that, to keep it or cancel it.
Retrying safely
Retries look harmless, but they hide a trap. If a booking request times out, did the booking fail, or did it succeed and only the reply got lost? Retrying blindly can book two flights.
Wait longer between each retry (exponential backoff: 2 seconds, then 4, then 8), so a struggling service gets time to recover, and cap the number of retries. Many teams add a little randomness to the wait so that many clients don't all retry at the same moment.
Limits and loop detection
Agents can get stuck: searching the same query again and again, or switching between two failing approaches. Give every agent hard limits:
- Steps per task, retries per step and replans per task.
- Budget: tokens, money and time.
- Loop detection: stop when the same action with the same input has been tried several times (the exercise below builds one).
When a limit is hit, the agent should stop cleanly and report, not crash or quietly give up.
Half-finished plans and handing over
When a plan stops halfway, some steps have already changed the world. There are three options:
- Finish another way: replan to reach the goal by a different route.
- Undo: run compensating actions that reverse the finished steps, such as cancelling the booked flight.
- Hand over: leave things as they are and ask a person to decide.
A good handover report is short and complete: the goal, what's done, what failed and why, what was tried, and the options with their consequences. “Flight FL-330 is booked (refundable until 10 March). No Porto hotels are available that weekend. Options: book in Vila Nova de Gaia, 10 minutes away; change dates; or cancel the flight.”
Common mistakes
Write a loop detector: agents that keep repeating the same action with the same input are stuck, and should stop or change approach.
actions = ["search(flights LYS-LIS)", "open(result 1)", "search(flights LYS-LIS)",
"open(result 1)", "search(flights LYS-LIS)", "open(result 2)"]
limit = 3
# Go through the actions in order, counting how often each one has been seen.
# As soon as one reaches limit, print "Loop detected at step <n>: <action>" and stop.
# If none does, print "No loop".
A request to book a hotel times out. What should the agent do before retrying it?
Summary
- Respond to failures by type: retry transient errors, replan around permanent ones, stop when stuck or out of budget.
- Retry with backoff and a cap, and make side-effect actions safe to repeat with checks or idempotency keys.
- Replan from the current state; never redo finished steps blindly.
- Set limits on steps, retries, replans and budget, and detect loops.
- For half-finished plans, finish another way, undo with compensating actions, or hand over with a clear report.
Course complete
You can now break goals into validated plans with dependencies, make agents reason and check assumptions before acting, build self-correction loops driven by real feedback, use search when the first idea isn't good enough, and handle failures with retries, replanning, limits and clear handovers. Next: the Multi-Agent Systems course shows how several agents can share this work.
Finished reading? Tick it off to track your progress.