08C.2 Dynamic Replanning and Constraint-Aware Planning
A plan is a guess made before the work starts. Pages go missing, APIs time out, policies say no, and the budget runs out. This lesson teaches two linked skills. First, what to do when a step fails: retry it, repair its arguments, replan the rest, or stop and hand over to a person, and how to do each one with a hard cap so the agent cannot thrash. Second, how to plan inside limits: a token budget, a cost budget, a deadline and a set of tools the current user may use. You build both in plain Python, with a scripted fake model and real output.
It follows 08C.1, which built the plan model and the validator. It uses the loop budgets from 08A.3 and the organisation-level budgets of 11B.6, and it hands off to 08C.3 for surviving a crash.
What you'll learn
- A four-way failure classification (retry, repair, replan, escalate) and the rule that picks one
- Replanning triggers: what should and should not cause a replan, and why a replan must keep finished work
- The plan diff: showing exactly what a replan changed, for logs, for approval and for evals
- Bounded replans: a replan budget that stops thrash, and what "escalate" means
- Constraint-aware planning: choosing a plan that fits a token budget, a cost budget and a deadline, with a fallback when none fits
- Permission-filtered tool sets: planning with only the tools this user may call, and checking the plan against permissions
- What to measure when evaluating recovery and constraint compliance
What you don't need
- API keys. The failure handling, the replan loop, the budget fitting and the permission filter all run against scripted fakes using only the standard library. The hosted-model replan sample in Part 2 is labelled illustrative.
- Docker or any service.
- LangGraph. The basic replanner idea (continue, revise or respond after each step) is in 08A.10, Part 3. This lesson adds failure classes, caps, diffs and constraints around it.
Setup
As of 1 December 2026. Python 3.11 or newer. Parts 1 to 4 use only the standard library, so nothing is installed. For the illustrative sample in 2.5:
uv add openai anthropic
# or: pip install openai anthropicEach code block starts with a comment giving its file name. Save the files in one folder and run them with python <file>. The running example is the support assistant from Module 08A: load an order, find the policy, refund or open a ticket, tell the customer.
What you must be able to do after this lesson#
- Classify a step failure as retry, repair, replan or escalate with a small deterministic function
- Cap retries, repairs and replans separately, and escalate with a reason when a cap is used up
- Replan only the remaining steps, keep finished work, and show the change as a plan diff
- Choose a plan that fits a token budget, a cost budget and a deadline, and enforce the budget again at run time
- Filter the tool list by role, validate a plan against permissions and handle a plan that cannot fit
- Test recovery and constraint handling with a fault-injection table
Why this matters for an AI engineer#
Demos show the happy path. Production shows the 503, the "order is 45 days old", the "this user may not issue refunds" and the "you have 12 seconds left". An agent that cannot classify what went wrong either retries a hopeless step forever or abandons a plan that only needed one more try. An agent that ignores its budget finishes the clever plan and then cannot afford the last required step. Both failures are common, both cost real money, and both are easy to prevent with a few hundred lines of ordinary code.
| You'll hear... | You'll understand it after... |
|---|---|
| "Retry, repair, replan or escalate?" | Part 1: Classifying a failure |
| "The agent replanned five times and made it worse." | 2.4 Bounded replans |
| "Show me what the replan changed." | 2.3 The plan diff |
| "The plan has to fit in 4,000 tokens and 12 seconds." | 3.1 Fitting a plan to a budget |
| "The viewer role must never see the refund tool." | 4.1 Permission-filtered tool sets |
| "How do we test recovery?" | Part 5: Evaluate it |
Part 1: Classifying a failure#
1.1 Four responses#
When a step fails, there are four things you can do. They are ordered from cheapest to most expensive.
| Response | Meaning | Use when | Cost |
|---|---|---|---|
| Retry | Run the same step again, after a backoff delay | The failure is transient: timeout, rate limit (HTTP 429), 503 | One more call |
| Repair | Run the step again, but show the model what was wrong | The model's arguments or output were invalid (failed validation) | One more model call with the error text |
| Replan | Keep the finished steps, ask the planner for new remaining steps | The step cannot work as planned: the world contradicts an assumption | A planner call plus a new plan to validate |
| Escalate | Stop and hand over to a person or a safer system | A no that more attempts cannot change: permission denied, policy block, budget exhausted, unknown failure | The run ends here |
The order matters. Do not replan when a retry would do, and do not retry a "permission denied". 08A.2 already teaches returning tool errors as data so the model can route around them and retrying below the loop with backoff, and 08A.14 covers reliability in depth. This lesson adds the decision rule and the plan-level responses.
1.2 The classifier#
The rule is a small function, not a model call. Use typed exceptions so the decision is explicit and testable. The most specific, most final classes come first.
| Failure class | Example | Response | Why |
|---|---|---|---|
PermissionDenied, BudgetExceeded |
"refund needs approval above 100", "token budget used" | Escalate | Another attempt cannot turn a no into a yes |
TransientError |
503, timeout, 429 | Retry (capped, backoff) | Same call, later |
BadArguments |
amount "42 dollars" |
Repair (capped) | Model can fix it if shown the error |
StepImpossible |
"order is 45 days old, window is 30" | Replan | The plan's assumption was wrong |
| anything else | unknown exception | Escalate | Do not guess |
Two escalation rules deserve emphasis. First, an unknown failure escalates, because guessing is how a bug becomes an incident. Second, when retries or repairs run out, the response becomes replan: a step that keeps failing is evidence that the plan, not the luck, is the problem.
Part 2: Replanning#
08A.10, 3.3 has a replanner with a max_replans cap that decides to continue, revise or respond. This part extends it with explicit replan triggers, a rule for what a replan keeps, a plan diff and escalation when the cap is used up.
2.1 Replanning triggers#
A replan means asking the planner for a new list of remaining steps. It costs a model call and risks making things worse, so it needs a clear trigger. Good triggers:
- a step failed with a
StepImpossibleoutcome (the world says no), - a step's
done_whencheck failed even though the tool reported success, - retries or repairs for a step ran out,
- new information contradicts an assumption ("the account is on the legacy plan, so the refund path is different"),
- a forecast shows the remaining plan no longer fits the budget or deadline (Part 3),
- a person edited the goal or the plan.
Bad triggers: a single transient error (retry), a slightly different tool output that still passes the check, or boredom. A replan that fires after every step is the "replanner thrash" failure that 08A.10, 3.4 lists as a plan-and-execute failure mode.
2.2 What a replan keeps and what it gets#
Two rules make replans safe.
- Finished work is final. Completed steps are not reopened or repeated. Their results stay in the plan. A replan changes only what comes after. (If a finished step turns out to be wrong, that is a bigger event: escalate.)
- The planner sees the evidence. Give it the goal, the completed steps with their results, the failed step and the classified error in plain words, the old remaining steps, and the current constraints (tools allowed, budget left, time left). A planner that does not see the constraints will happily plan a refund for a user who cannot refund.
The new tail goes through the same validator as the first plan (08C.1, Part 4). A replan is a plan.
2.3 The plan diff#
Every replan should produce a plan diff: a short list of what was added (+), removed (-) and changed (~). It is worth the ten lines it takes because it is useful in four places:
- Logs and traces: you can see why the run changed course without reading transcripts.
- Approval: for a risky change, a person approves the diff, not the whole plan.
- Evals: you can assert "the replan removed the refund and added a ticket".
- Debugging thrash: a diff that keeps undoing the previous diff is the signature of a loop.
2.4 Bounded replans and thrash#
A replan budget is a hard cap on how many times one run may replan (two or three is typical). It is the plan-level cousin of the step cap in 08A.3, and it needs the same treatment: when it is used up, the run escalates with a clear reason instead of continuing.
Why a cap and not "keep trying until it works"? A planner that failed twice is usually missing a fact or a permission, and a third plan is the same guess in different words. Each replan also costs tokens and time, which the budgets in Part 3 are counting.
Below is the whole mechanism: typed failures, the classifier, a plan diff, and a runner with separate caps for retries, repairs and replans. The model is scripted: execute_* functions raise the failures on cue and replanner_* return canned new tails.
# recovery.py: classify a step failure, then retry, repair, replan or escalate; replans are bounded and diffed
from __future__ import annotations
import time
from dataclasses import dataclass, field
# --- 1. Failure types the executor can see -----------------------------------------------
class TransientError(Exception): ... # timeout, 429, 503: the same call may work later
class BadArguments(Exception): ... # the model's arguments failed validation
class StepImpossible(Exception): ... # the world says this step cannot work as planned
class PermissionDenied(Exception): ... # a policy or permission refused the call
class BudgetExceeded(Exception): ... # tokens, money or time ran out
def classify(exc: Exception) -> str:
"""Map an exception to one recovery action. Order matters: most specific first."""
if isinstance(exc, (PermissionDenied, BudgetExceeded)):
return "escalate" # more attempts cannot fix a "no"
if isinstance(exc, TransientError):
return "retry"
if isinstance(exc, BadArguments):
return "repair"
if isinstance(exc, StepImpossible):
return "replan"
return "escalate" # unknown failure: do not guess
# --- 2. A tiny plan and a plan diff --------------------------------------------------------
@dataclass
class S:
id: str
goal: str
status: str = "pending"
def plan_diff(old: list[S], new: list[S]) -> list[str]:
o = {s.id: s for s in old}
n = {s.id: s for s in new}
out = []
for i in n:
if i not in o:
out.append(f"+ {i}: {n[i].goal}")
elif o[i].goal != n[i].goal:
out.append(f"~ {i}: {o[i].goal!r} -> {n[i].goal!r}")
for i in o:
if i not in n:
out.append(f"- {i}: {o[i].goal}")
return out
@dataclass
class Report:
outcome: str = "running"
replans: int = 0
log: list[str] = field(default_factory=list)
def run_plan(plan: list[S], execute, replanner, *, max_retries=2, max_repairs=1,
max_replans=2, sleep=lambda s: None) -> Report:
rep = Report()
i = 0
while i < len(plan):
step = plan[i]
retries = repairs = 0
feedback = None
while True:
try:
execute(step, feedback)
step.status = "done"
rep.log.append(f"{step.id}: done")
break
except Exception as exc: # noqa: BLE001: we classify every failure
action = classify(exc)
rep.log.append(f"{step.id}: {type(exc).__name__}({exc}) -> {action}")
if action == "retry" and retries < max_retries:
retries += 1
sleep(2 ** retries) # backoff (a no-op in this demo)
continue
if action == "repair" and repairs < max_repairs:
repairs += 1
feedback = str(exc) # show the model its own error
continue
if action in ("retry", "repair"):
action = "replan" # retries used up: the plan is the problem
if action == "replan":
if rep.replans >= max_replans:
step.status = "failed"
rep.outcome = "escalated: replan budget used"
rep.log.append("escalate: replan budget used")
return rep
rep.replans += 1
step.status = "failed"
new_tail = replanner(plan[:i], step, exc)
new_plan = plan[:i] + new_tail
rep.log.append(f"replan #{rep.replans} diff: {plan_diff(plan, new_plan)}")
plan[:] = new_plan
step = plan[i]
retries = repairs = 0
feedback = None
continue
step.status = "failed"
rep.outcome = f"escalated: {type(exc).__name__}"
rep.log.append(f"escalate: {exc}")
return rep
i += 1
rep.outcome = "completed"
return rep
# --- 3. Scenarios -----------------------------------------------------------------------------
def scenario(name, execute, replanner, **kw):
plan = [S("load", "Load order A17"), S("refund", "Refund order A17"), S("notify", "Email the customer")]
rep = run_plan(plan, execute, replanner, **kw)
print(f"== {name}: {rep.outcome} (replans={rep.replans})")
for line in rep.log:
print(" ", line)
calls = {"load": 0}
def execute_a(step, feedback):
if step.id == "load":
calls["load"] += 1
if calls["load"] < 3:
raise TransientError("503 from orders API")
if step.id == "refund":
raise StepImpossible("order is 45 days old; policy window is 30")
if step.id == "ticket":
return
def replanner_a(done, failed, exc):
# a scripted replan: swap the failed refund step for a ticket, keep notify
return [S("ticket", "Open a ticket for a manager to review the refund"),
S("notify", "Email the customer that a manager will review")]
scenario("transient then replan", execute_a, replanner_a)
def execute_b(step, feedback):
if step.id == "refund":
raise PermissionDenied("refund_issue needs approval above 100")
scenario("permission denied", execute_b, replanner_a)
def execute_c(step, feedback):
if step.id == "refund":
raise StepImpossible("still impossible")
if step.id.startswith("alt"):
raise StepImpossible("alternative also impossible")
n = {"k": 0}
def replanner_c(done, failed, exc):
n["k"] += 1
return [S(f"alt{n['k']}", f"Alternative approach {n['k']}")]
scenario("replan thrash is capped", execute_c, replanner_c, max_replans=2)
def execute_d(step, feedback):
if step.id == "refund" and feedback is None:
raise BadArguments("amount must be a number, got '42 dollars'")
scenario("repair with feedback", execute_d, replanner_a)== transient then replan: completed (replans=1)
load: TransientError(503 from orders API) -> retry
load: TransientError(503 from orders API) -> retry
load: done
refund: StepImpossible(order is 45 days old; policy window is 30) -> replan
replan #1 diff: ['+ ticket: Open a ticket for a manager to review the refund', "~ notify: 'Email the customer' -> 'Email the customer that a manager will review'", '- refund: Refund order A17']
ticket: done
notify: done
== permission denied: escalated: PermissionDenied (replans=0)
load: done
refund: PermissionDenied(refund_issue needs approval above 100) -> escalate
escalate: refund_issue needs approval above 100
== replan thrash is capped: escalated: replan budget used (replans=2)
load: done
refund: StepImpossible(still impossible) -> replan
replan #1 diff: ['+ alt1: Alternative approach 1', '- refund: Refund order A17', '- notify: Email the customer']
alt1: StepImpossible(alternative also impossible) -> replan
replan #2 diff: ['+ alt2: Alternative approach 2', '- alt1: Alternative approach 1']
alt2: StepImpossible(alternative also impossible) -> replan
escalate: replan budget used
== repair with feedback: completed (replans=0)
load: done
refund: BadArguments(amount must be a number, got '42 dollars') -> repair
refund: done
notify: doneRead the four scenarios in turn:
- Transient, then replan.
loadfails twice with a 503, is retried and succeeds on the third try. ThenrefundraisesStepImpossible(order too old), the classifier says replan, and the diff shows exactly what changed: aticketstep added,notifyreworded,refundremoved. The finishedloadstep is untouched. - Permission denied. No retry, no replan. The run escalates at once. A different plan would hit the same wall.
- Replan thrash is capped. Every alternative fails too. After two replans the budget is spent and the run escalates with the reason "replan budget used". Without the cap this loop would run until the token budget ended.
- Repair with feedback.
BadArgumentsgives the model its own error asfeedback, and the second attempt succeeds. In a real systemfeedbackis appended to the step prompt.
2.5 Replanning with a real model#
With a hosted model the scripted replanner becomes one structured-output call that returns only the remaining steps. The prompt carries the evidence from 2.2. This sample reuses the plan schema from 08C.1, 4.4 and shows OpenAI and Anthropic.
# replan_call.py: ask a hosted model to rewrite ONLY the remaining steps after a failure (needs keys, not run here)
import json
from anthropic import Anthropic
from openai import OpenAI
from provider_plan import PLAN_SCHEMA # the schema from lesson 08C.1
REPLAN_SYSTEM = (
"You repair plans. Completed steps are final: never change or repeat them. "
"Return ONLY the new list of remaining steps (same JSON shape as before). "
"Respect the constraints. If no safe plan exists, return an empty steps list."
)
def replan_prompt(goal, done, failed, error, remaining, constraints) -> str:
return json.dumps({
"goal": goal,
"completed": done, # [{"id": ..., "result": ...}]
"failed_step": failed, # {"id": ..., "goal": ...}
"error": error, # the classified failure, in plain words
"old_remaining": remaining,
"constraints": constraints, # {"tools_allowed": [...], "tokens_left": 3200, "seconds_left": 40}
})
def replan_openai(prompt: str) -> dict:
r = OpenAI().responses.create(
model="gpt-6-luna",
input=[{"role": "system", "content": REPLAN_SYSTEM}, {"role": "user", "content": prompt}],
text={"format": {"type": "json_schema", "name": "plan", "strict": True, "schema": PLAN_SCHEMA}},
)
return json.loads(r.output_text)
def replan_anthropic(prompt: str) -> dict:
r = Anthropic().messages.create(
model="claude-haiku-5-5", max_tokens=2_000, system=REPLAN_SYSTEM,
messages=[{"role": "user", "content": prompt}],
output_config={"format": {"type": "json_schema", "schema": PLAN_SCHEMA}},
)
return json.loads(next(b.text for b in r.content if b.type == "text"))Output (illustrative, needs keys; your exact output will differ): a JSON object with a steps list such as ticket then notify, or an empty list if the model decides no safe plan exists. An empty list is a valid answer and should be handled as "escalate".
Do not trust the reply. Run it through the validator, check that it did not touch completed ids, and diff it against the old tail before you accept it.
Part 3: Planning inside budgets and deadlines#
Deep-dive
3.1 Fitting a plan to a budget#
A constraint is a limit the plan must respect. Four are common: a token budget (how much context and output the run may use), a cost budget (money), a deadline (wall-clock time) and tool permissions (what the user may call; Part 4). The first three are quantities you can add up. Planning with them has three parts.
- Estimate each step's cost. Tokens, money and seconds, per option. Money follows a formula:
cost = input_tokens x price_per_input_token + output_tokens x price_per_output_token. Prices change, so read them from the provider's pricing page for the model you use (OpenAI: https://platform.openai.com/docs/pricing, Anthropic: https://platform.claude.com/docs/en/about-claude/pricing) instead of hard-coding numbers into a lesson or a plan. The demo below uses made-up round numbers on purpose. - Give steps options. A step such as "find the policy" may have a cheap option (keyword search) and a better, dearer one (search plus rerank). Optional steps may be dropped.
- Choose. Start from the cheapest valid plan. If even that does not fit, drop optional steps, and if the required steps alone do not fit, say so: ask for more budget or escalate. Otherwise spend the leftover budget on the upgrade with the best value per dollar.
Dropping and downgrading are plan changes, so they appear in the plan diff of 2.3 like any other.
# constraints.py: choose a plan that fits token, cost and time budgets, and filter tools by permission
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class Variant:
name: str
tokens: int
cost_usd: float
seconds: float
value: int # how much this variant helps the goal (higher is better)
@dataclass
class PlanStepOpt:
id: str
required: bool
variants: list[Variant] # cheapest first
tool: str
@dataclass(frozen=True)
class Budget:
tokens: int
cost_usd: float
seconds: float
def fits(total: tuple[int, float, float], b: Budget) -> bool:
return total[0] <= b.tokens and total[1] <= b.cost_usd + 1e-9 and total[2] <= b.seconds
def totals(choice: dict[str, Variant]) -> tuple[int, float, float]:
return (sum(v.tokens for v in choice.values()),
round(sum(v.cost_usd for v in choice.values()), 6),
sum(v.seconds for v in choice.values()))
def fit_plan(steps: list[PlanStepOpt], budget: Budget, allowed_tools: set[str]):
"""Return (choice, notes). Start from the cheapest variant of every allowed step,
then spend leftover budget on the upgrade with the best value per dollar."""
notes: list[str] = []
choice: dict[str, Variant] = {}
for s in steps:
if s.tool not in allowed_tools:
if s.required:
return None, [f"cannot plan: required step {s.id!r} needs tool {s.tool!r}, which is not permitted"]
notes.append(f"dropped {s.id}: tool {s.tool!r} not permitted")
continue
choice[s.id] = s.variants[0]
if not fits(totals(choice), budget): # even the cheapest plan is too big: drop optional steps
for s in reversed(steps):
if s.id in choice and not s.required and not fits(totals(choice), budget):
del choice[s.id]
notes.append(f"dropped optional {s.id} to fit the budget")
if not fits(totals(choice), budget):
return None, notes + ["cannot plan: the required steps alone exceed the budget -> ask for more budget"]
while True: # greedy upgrades
best = None
for s in steps:
if s.id not in choice:
continue
cur = choice[s.id]
for v in s.variants:
if v.value <= cur.value:
continue
trial = dict(choice, **{s.id: v})
if not fits(totals(trial), budget):
continue
gain = (v.value - cur.value) / max(v.cost_usd - cur.cost_usd, 1e-6)
if best is None or gain > best[0]:
best = (gain, s.id, v)
if best is None:
break
_, sid, v = best
notes.append(f"upgraded {sid} to {v.name}")
choice[sid] = v
return choice, notes
STEPS = [
PlanStepOpt("load", True, [Variant("direct lookup", 300, 0.0003, 1, 1)], "orders_get"),
PlanStepOpt("policy", True, [Variant("keyword search", 800, 0.0008, 2, 1),
Variant("search + rerank", 3000, 0.004, 6, 3)], "docs_search"),
PlanStepOpt("refund", True, [Variant("issue refund", 600, 0.0006, 2, 1)], "refund_issue"),
PlanStepOpt("summary", False, [Variant("template", 0, 0.0, 0, 1),
Variant("LLM summary", 2500, 0.0030, 5, 2)], "email_send"),
]
def show(title, budget, allowed):
choice, notes = fit_plan(STEPS, budget, allowed)
print(f"== {title}")
if choice is None:
print(" ", notes[-1])
return
t = totals(choice)
print(" plan:", {k: v.name for k, v in choice.items()})
print(f" total: {t[0]} tokens, ${t[1]:.4f}, {t[2]:.0f}s")
for n in notes:
print(" note:", n)
ALL = {"orders_get", "docs_search", "refund_issue", "email_send"}
show("generous budget", Budget(10_000, 0.02, 60), ALL)
show("tight tokens", Budget(2_000, 0.02, 60), ALL)
show("tight deadline", Budget(10_000, 0.02, 8), ALL)
show("too small", Budget(1_000, 0.02, 60), ALL)
show("read-only role (no refund_issue)", Budget(10_000, 0.02, 60), ALL - {"refund_issue"})
show("no email permission", Budget(10_000, 0.02, 60), ALL - {"email_send"})
# --- permission-filtered tool sets: the model only ever sees what the role may call ---------
TOOL_SPECS = [{"name": n} for n in sorted(ALL)]
ROLE_ALLOW = {"viewer": {"orders_get", "docs_search"}, "agent": ALL}
def tools_for(role: str) -> list[str]:
return [t["name"] for t in TOOL_SPECS if t["name"] in ROLE_ALLOW[role]]
print("viewer sees:", tools_for("viewer"))
print("agent sees: ", tools_for("agent"))== generous budget
plan: {'load': 'direct lookup', 'policy': 'search + rerank', 'refund': 'issue refund', 'summary': 'LLM summary'}
total: 6400 tokens, $0.0079, 14s
note: upgraded policy to search + rerank
note: upgraded summary to LLM summary
== tight tokens
plan: {'load': 'direct lookup', 'policy': 'keyword search', 'refund': 'issue refund', 'summary': 'template'}
total: 1700 tokens, $0.0017, 5s
== tight deadline
plan: {'load': 'direct lookup', 'policy': 'keyword search', 'refund': 'issue refund', 'summary': 'template'}
total: 1700 tokens, $0.0017, 5s
== too small
cannot plan: the required steps alone exceed the budget -> ask for more budget
== read-only role (no refund_issue)
cannot plan: required step 'refund' needs tool 'refund_issue', which is not permitted
== no email permission
plan: {'load': 'direct lookup', 'policy': 'search + rerank', 'refund': 'issue refund'}
total: 3900 tokens, $0.0049, 9s
note: dropped summary: tool 'email_send' not permitted
note: upgraded policy to search + rerank
viewer sees: ['docs_search', 'orders_get']
agent sees: ['docs_search', 'email_send', 'orders_get', 'refund_issue']How to read it:
- Generous budget. Both upgrades fit, so the plan uses search plus rerank and an LLM summary.
- Tight tokens and tight deadline. The plan stays on cheap options. Note that the same plan fits both very different limits here; in a real system each constraint can be the binding one.
- Too small. The required steps alone need 1,700 tokens and the budget is 1,000. The honest result is "cannot plan, ask for more budget", not a plan that will fail at step 3.
- Read-only role. A required step needs a tool the role may not call. No plan exists. This is checked before any tool runs.
- No email permission. The optional summary step is dropped and the run goes on with what it may do.
3.2 Planning is not enough: enforce at run time#
Estimates are wrong. A step planned at 800 tokens uses 2,000. So the plan fit is a forecast, and you also need a live budget checked before every step, plus a reserve for the final answer. This is the same budget object as in the loop (08A.3), now applied per plan step. There is one trap, shown below: if you spend on the best option whenever it is affordable right now, an early upgrade can starve a later required step.
# deadline.py: one budget object every step checks; reserving for later required steps stops a fancy step from starving them
from dataclasses import dataclass
Cost = tuple[int, float, float] # (tokens, usd, seconds)
@dataclass
class RunBudget:
tokens_left: int
usd_left: float
seconds_left: float
reserve_tokens: int = 500 # kept back for the final answer
def can_afford(self, cost: Cost, reserved: Cost = (0, 0.0, 0.0)) -> bool:
return (cost[0] + reserved[0] + self.reserve_tokens <= self.tokens_left
and cost[1] + reserved[1] <= self.usd_left
and cost[2] + reserved[2] <= self.seconds_left)
def spend(self, cost: Cost) -> None:
self.tokens_left -= cost[0]
self.usd_left -= cost[1]
self.seconds_left -= cost[2]
# Each step lists its options best-first. The last option is the cheap fallback.
STEPS: list[tuple[str, list[tuple[str, Cost]]]] = [
("load", [("direct lookup", (300, 0.0003, 1))]),
("policy", [("search + rerank", (3000, 0.004, 6)), ("keyword search", (800, 0.0008, 2))]),
("refund", [("issue refund", (600, 0.0006, 2))]),
]
def cheapest(options) -> Cost:
return min((c for _, c in options), key=lambda c: c[0])
def run(label: str, reserve_for_later: bool) -> None:
b = RunBudget(tokens_left=4_000, usd_left=0.01, seconds_left=12)
print(label)
for i, (step, options) in enumerate(STEPS):
later = [cheapest(o) for _, o in STEPS[i + 1:]]
reserved = tuple(map(sum, zip(*later))) if (reserve_for_later and later) else (0, 0.0, 0.0)
for name, cost in options:
if b.can_afford(cost, reserved):
b.spend(cost)
print(f" {step}: {name}, left={b.tokens_left} tokens, {b.seconds_left:.0f}s")
break
else:
print(f" {step}: SKIPPED, nothing affordable ({b.tokens_left} tokens left)")
run("naive (take the best option that is affordable right now):", reserve_for_later=False)
run("reserve what the later steps need:", reserve_for_later=True)naive (take the best option that is affordable right now):
load: direct lookup, left=3700 tokens, 11s
policy: search + rerank, left=700 tokens, 5s
refund: SKIPPED, nothing affordable (700 tokens left)
reserve what the later steps need:
load: direct lookup, left=3700 tokens, 11s
policy: keyword search, left=2900 tokens, 9s
refund: issue refund, left=2300 tokens, 7sThe naive run takes search + rerank because 3,000 tokens was affordable at that moment, and then has nothing left for the required refund step. The second run reserves the cheapest cost of every later step before upgrading, and everything completes. A deadline works the same way: the live remaining seconds are checked before each step, and when time is short the agent must degrade (cheaper option, skip optional steps) or escalate, not just run out.
When the live budget says the remaining plan no longer fits, that is a replan trigger from 2.1. The replanner receives the new tokens_left and seconds_left as constraints and returns a cheaper tail. Budgets and replans are one mechanism seen from two sides.
At organisation level, budgets also exist per team, per key and per month. That belongs to 11B.6; this lesson is the per-run view.
Part 4: Permissions, and when no plan fits#
4.1 Permission-filtered tool sets#
Tool permissions are the fourth constraint, and the cleanest to enforce: the model can only plan with tools it can see. So filter the tool list before the planner and the executor ever see it, based on the user's role.
The last lines of constraints.py do exactly that. tools_for("viewer") returns only docs_search and orders_get. tools_for("agent") returns all four. A planner given the viewer list cannot propose refund_issue because the tool does not exist from its point of view, and the validator from 08C.1 rejects a plan that names it anyway.
This is least privilege applied to planning: give the agent the smallest tool set that does the job. 08A.5 is the neutral home for least privilege, approval gates and allowlists, and 08A.12 teaches approval gates.
Three layers, each catching what the one before missed:
| Layer | Where | Catches |
|---|---|---|
| Filter the tool list | Before the planner runs | The planner proposing a tool the role cannot use |
| Validate the plan against permissions | After the planner, before execution | A plan that names a forbidden tool anyway, and infeasible plans (a required step needs a forbidden tool), as the "read-only role" case in 3.1 |
| Check on every call | Inside the tool layer at run time | Prompt injection, mistakes, and permissions that changed during the run |
Never rely on the first two alone. The last layer is the one that stays true when the model is wrong or has been tricked (08A.5).
4.2 What to do when no plan fits#
Sometimes the constraints and the goal cannot both be met. Do not produce a plan that will fail halfway. Options, in order:
- Degrade: drop optional steps, use cheaper options, accept a lower-quality answer, and say that you did.
- Narrow the goal: do the part that is possible ("open a ticket and tell the customer a manager will review").
- Ask: request more budget, more time or an approval for a higher-permission step (08A.12).
- Escalate with the reason: "the refund step needs
refund_issue, which this role lacks".
Whichever you choose, return the reason as data (as fit_plan does with notes), so a person or a log can see why the agent did less than asked.
4.3 Putting the pieces together#
flowchart TD
G([goal + user + budget]) --> F["filter tools by role"]
F --> P["plan (08C.1)"] --> V{"valid and<br/>fits budget?"}
V -- "no" --> D["degrade / ask / escalate"]
V -- "yes" --> X["run step<br/>check live budget"]
X --> C{"done_when ok?"}
C -- "yes" --> X
C -- "no" --> K{"classify"}
K -- "retry / repair" --> X
K -- "replan" --> R["replan with constraints<br/>(capped)"] --> V
K -- "escalate" --> H([stop and hand over])
X -- "budget low" --> RBoth halves of this lesson fit in that one picture: failures go through the classifier, and the constraints appear twice, once when planning and again when running.
Part 5: Evaluate it#
Recovery and constraint handling are exactly the behaviours that a final-answer check misses, because an agent can recover badly and still get lucky.
Concept lessons first.
- 10A.7, 4.3 Efficiency, loops and recovery defines recovery rate and loop detection. 4.4 Budget, permission and policy compliance is the concept home for constraint compliance, and 4.5 for plan quality.
- 10A.7, Part 5 explains why you repeat each task and report pass^k: recovery behaviour is high-variance.
- 10A.11 covers whether the agent still remembers finished steps after a replan.
- 10A.12 applies when a planner agent and worker agents share the plan.
DeepEval lessons (required track).
- 10B.2 and 10B.4 for the basics and built-in metrics.
- 10B.5, Part 9 for plan adherence, plan quality and step efficiency on traces.
- 10B.6 for datasets and fault-injection scenarios, and 10B.7 for running them in CI.
Inspect AI lessons (optional).
- 10B.15, Part 7 (optional): limits as part of an eval's design, which is the harness-side twin of the budgets here.
- 10B.15, Part 10 (optional): long-horizon agents.
- 10B.16 (optional): trajectories from events.
5.1 What to measure#
| Measure | Question | Pass rule (example) |
|---|---|---|
| Classification accuracy | Does the agent choose the right response (retry, repair, replan, escalate) for each injected fault? | At least 95% on a table of known faults (this one is plain code, no model) |
| Recovery rate | After an injected failure, does the run still reach the goal? | 90% on retryable faults, 70% on replannable ones |
| Wasted attempts | Retries on a permission denial, or replans over the cap | Zero |
| Replan quality | Did the replan keep completed work and respect constraints? | 100% of diffs leave finished ids unchanged |
| Constraint compliance | Did the run stay inside tokens, cost, time and permissions? | 100% for permissions, at least 95% for budgets |
| Correct refusal | When no plan fits, did the agent say so instead of failing midway? | 100% of infeasible tasks end in escalate, with a reason |
5.2 A tiny eval design#
- Inputs: a fault-injection table of 10 scenarios built from the demo's exceptions: 3 transient (503 twice, then ok), 2 bad-arguments, 2 impossible-step (order too old), 2 permission-denied, 1 budget-too-small. Each row lists the injected fault, the expected response and the expected final status.
- Metric 1 (code, no model): call
classifyon each fault; pass rule: all 10 match the expected response. - Metric 2 (code): run the scripted executor through
run_planfor each row; check final status and thatreplansis at most 2. Pass rule: 10 of 10. - Metric 3 (code): for every replan, assert completed step ids are unchanged in the diff. Pass rule: no violations.
- Metric 4 (model in the loop, optional): swap the scripted replanner for a real one and measure recovery rate over 5 runs per row. Report pass^5 (10A.7, Part 5) and the cost per successful task.
A fault table like this runs in milliseconds and belongs in your normal unit tests. The model-in-the-loop version is the slower, costlier eval.
Common misconceptions#
- "If a step fails, replan." Most failures are transient or repairable. Replanning is the third response, not the first.
- "Retry until it works." Retries need a cap, backoff, and a check that the call is safe to repeat. A permission denial never gets better by retrying.
- "A replan can rewrite everything." Finished work is final. A replan changes only the remaining steps.
- "The model can be trusted to stay within budget if we tell it." Telling is context; enforcing is code.
- "Filtering tools in the prompt is enough for security." Filter, validate and check at run time. The last layer is the one that holds under injection.
- "A plan that does not fit should be run anyway; maybe it will work." Say it does not fit, degrade, ask or escalate.
Key takeaways#
- Classify every failure into retry, repair, replan or escalate with a small deterministic function.
- Cap retries, repairs and replans separately. When a cap is used up, escalate with a reason.
- A replan keeps finished steps, sees the evidence and the current constraints, and is validated like any plan.
- Emit a plan diff for every replan.
- Constraints are token budget, cost budget, deadline and permissions. Plan with them, then enforce them live.
- Reserve budget for required later steps before spending on upgrades.
- Filter the tool list by role, validate plans against permissions, and check again on every call.
- When no plan fits, do not start. Degrade, narrow, ask or escalate, and record why.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Failure classification | Mapping a failure to one response: retry, repair, replan or escalate |
| Retry | Running the same step again after a backoff, for transient failures |
| Repair | Re-running a step after showing the model what was invalid |
| Replan | Asking the planner for a new list of remaining steps after a failure or a changed constraint |
| Escalate | Stopping and handing over to a person or a safer system, with a reason |
| Transient failure | A failure likely to disappear on its own (timeout, 429, 503) |
| Backoff | Waiting progressively longer between retries |
| Replan trigger | A condition that justifies a replan, such as an impossible step or a budget forecast overrun |
| Plan diff | The list of steps added, removed and changed by a replan |
| Replan budget | The maximum number of replans one run may do |
| Replan thrash | Repeated replans that do not converge or that undo each other |
| Constraint | A limit the plan must respect: tokens, cost, time or permissions |
| Constraint-aware planning | Choosing and running a plan that fits the active constraints |
| Token budget | The maximum tokens a run may use |
| Cost budget | The maximum money a run may spend (formula: input tokens x input price plus output tokens x output price) |
| Deadline | The wall-clock time by which the run must finish |
| Reserve | Budget held back for later required steps or the final answer |
| Graceful degradation | Doing a cheaper or smaller version of the task instead of failing |
| Permission-filtered tool set | The list of tools shown to the model, reduced to what the user may call |
| Infeasible plan | A plan whose required steps cannot be done under the constraints |
| Fault injection | Deliberately causing failures in tests to check recovery |
Exercises#
- A new failure class. Add
RateLimited(retry_after)torecovery.py. It should retry, but wait forretry_afterseconds (use a recorded fakesleep) instead of the default backoff. Hint: carry the delay on the exception object and read it in the retry branch; assert the recorded sleeps. - Protect finished work. Make
run_planreject any replanner result that changes or removes a step whose status is alreadydone. What should the run do when it happens? Hint: treat it as a failed replan that still counts againstmax_replans, then escalate. - Replan on budget. In
deadline.py, when a required step cannot be afforded, call a scripted replanner with the remaining budget and let it return a cheaper step. Hint: add an "emergency" option with a tiny cost to the step's list and let the planner pick it. - Time as a constraint. Add a
secondscheck tocan_affordusingtime.monotonic()instead of a stored number, with an injectable clock so tests are fast. Hint: passclock=time.monotonicas a parameter and give tests a fake that you advance by hand. - Permission-aware validation. Extend
validate_planfrom 08C.1 to takeallowed_toolsand report any step using a tool outside it. Then makefit_plancall it. Hint: reuse theknown_toolsparameter, passing the role's allowed set instead of all tools. - Fault table. Write the 10-row fault table from 5.2 and run it as a plain unit test. Hint: a list of
(exception_factory, expected_action)pairs and a loop is enough for Metric 1.
Check yourself#
- Name the four responses to a failed step and one failure class for each.Retry:
TransientError(503). Repair:BadArguments(invalid amount). Replan:StepImpossible(order too old). Escalate:PermissionDeniedorBudgetExceeded(or an unknown failure). - Why does an unknown exception escalate instead of retrying?Guessing turns a bug into an incident. An unknown failure may not be safe to repeat, and no rule says another attempt would help.
- What happens to completed steps during a replan, and why?They stay as they are, with their results. Reopening them would repeat side effects and waste work. If a finished step proves wrong, escalate.
- What goes into a replan prompt besides the failed step?The goal, the completed steps and results, the classified error in plain words, the old remaining steps, and the current constraints (tools allowed, tokens and time left).
- What is a plan diff and why produce one?A list of steps added, removed and changed. It makes the change visible in logs, approvals, evals and thrash debugging.
- Why cap replans, and what should happen when the cap is hit?A planner that failed twice is usually missing a fact or permission, and more plans only cost tokens and time. At the cap the run escalates with the reason "replan budget used".
- Give the formula for a step's money cost, and say where the price numbers should come from.
input_tokens x input price + output_tokens x output price. Take the prices from the provider's pricing page for the exact model, not from memory. - In the budget demo, why did the naive run skip the
refundstep?It spent 3,000 tokens onsearch + rerankbecause it was affordable at that moment, leaving 700 tokens, which is less than the 600 needed forrefundplus the 500 reserve. - Why filter the tool list and also check permissions on every call?The filter stops the planner from proposing forbidden tools, but a model can be tricked or wrong and permissions can change mid-run. The run-time check is the layer that always holds.
- What should the agent do when the required steps alone exceed the budget?Say so before starting: degrade only if there is something optional to drop, otherwise ask for more budget or escalate, and return the reason.
Further resources#
- 08A.10 — Agent Patterns: the plan-and-execute pattern and its replanner.
- 08A.2 — The Tool Loop: errors as data, budgets and stop conditions in the raw loop.
- 08A.14 — Reliable and Safe Agents: reliability in depth.
- 03.9 — Async, Concurrency and Batch: retries and backoff for API calls.
- 10A.7 — Evaluating Agents and Multimodal Systems: recovery, budget and permission metrics.
- OpenAI pricing: https://platform.openai.com/docs/pricing
- Anthropic pricing: https://platform.claude.com/docs/en/about-claude/pricing
- Anthropic, "Building effective agents": https://www.anthropic.com/engineering/building-effective-agents
← 08C.1 — Task Decomposition and Plan-as-Artifact | Module 08C overview | 08C.3 — Checkpoint, Resume and Durable Execution (without LangGraph) →