Lesson 2's loop ends when the model says it is done, or at a safety cap of 25 steps that throws the run's trace away. This lesson makes the harness bound every run, whatever the model does. By the end you will be able to:
- end a run when it uses up its step, token, cost or wall-clock budget, returning the reason and the partial work instead of raising (proved by
test_step_budget_ends_the_run_cleanly,test_token_budget_stops_and_skips_the_crossing_steps_tools,test_cost_budget_uses_real_model_prices,test_time_budget,test_cached_tokens_count_against_the_token_budgetandtest_budget_exhausted_keeps_the_partial_work) - stop calling a tool that keeps failing, with a circuit breaker per tool (
test_breaker_opens_and_stops_calling_a_dead_tool,test_breaker_half_opens_after_the_cooldown,test_breakers_are_per_tool) - retry only tools that only read, and only on failures that might go away (
test_read_tool_is_retried_then_succeeds,test_writes_are_never_retried,test_a_tool_error_with_a_hint_is_not_retried) - refuse the same call made a third time, with repeated-call detection (
test_third_identical_call_is_refused)
That closes three rows of Lesson 1's checklist: runaway loop, repeated identical calls and cost blow-up.
Before you start. You need Lesson 2. If you are following along in your own copy, start from Lesson 2's folder and add the files below; or use the finished folder:
cd tutorials-code/build-a-bounded-agent/02-keeping-it-bounded/03-budgets-and-circuit-breakers
uv sync
uv run pytest testsThe finished folder (companion folder) is Lesson 2's code with three new files, agent/budgets.py, agent/breaker.py and agent/faults.py. It also changes agent/loop.py (the bounded loop and guarded_call) and agent/tools.py (the retry list and transient failures). It has 27 tests, and every number below comes from running it.
1. Budgets the harness enforces
A budget is a hard limit on one run, checked by the harness on every step. The model is never asked to respect it, so it can't talk its way past one.
@dataclass(frozen=True)
class Budget:
max_steps: int = 12
max_tokens: int = 60_000 # input (cached or not) + output, summed over the run
max_cost_usd: float = 0.50
max_seconds: float = 120.0
class BudgetTracker:
def __init__(self, budget: Budget, model: str, clock: Callable[[], float] = time.monotonic):
self.budget = budget
self.model = model
self.clock = clock
self.started = clock()
self.steps = 0
self.usage = Usage()
@property
def cost(self) -> float:
return cost_usd(self.model, self.usage)
def before_step(self) -> str | None:
"""Checked before each model call: may we start another step?"""
if self.steps >= self.budget.max_steps:
return f"step budget of {self.budget.max_steps} used"
elapsed = self.clock() - self.started
if elapsed >= self.budget.max_seconds:
return f"time budget of {self.budget.max_seconds:g}s used ({elapsed:.1f}s)"
return None
def charge(self, usage: Usage) -> str | None:
"""Checked after each model call, with what it actually cost."""
self.steps += 1
self.usage = self.usage + usage
u = self.usage
# Every token the model read or wrote counts, cached or not.
tokens = u.input_tokens + u.cache_read + u.cache_write + u.output_tokens
if tokens > self.budget.max_tokens:
return f"token budget of {self.budget.max_tokens:,} exceeded ({tokens:,})"
if self.cost > self.budget.max_cost_usd:
return f"cost budget of ${self.budget.max_cost_usd:.2f} exceeded (${self.cost:.4f})"
return NoneThe defaults are sized for one triage: room for a ticket that needs several searches, and a stop for a stuck run long before Lesson 1's runaway would have reached its safety net.
Steps and time are known before a model call, so before_step checks them first. Tokens and cost are only known afterwards, from the usage the response reports, so charge adds that usage and then checks them. The token count includes every token the model read, cached or not, plus what it wrote. A run with prompt caching reads most of its input from cache, and leaving those tokens out would let it run far past its budget; test_cached_tokens_count_against_the_token_budget checks it.
The cost uses Lesson 2's pricing.py. On the Claude pricing page, checked on 2026-11-21 (https://platform.claude.com/docs/en/about-claude/pricing), claude-opus-5-5 costs $4 per million input tokens and $20 per million output tokens. 5-minute cache writes cost $5 per million and cache hits $0.20 per million. Read that table per model. Cache hits on claude-opus-5-5 are 0.05x the input price, where most models charge 0.1x. A cost budget built on the wrong multiplier is wrong by the same factor.
2. The budget-exhausted outcome
A run that hits a budget doesn't raise. It returns a RunResult with the outcome budget_exhausted, so the caller still gets everything the run did:
@dataclass
class RunResult:
outcome: str # done | budget_exhausted | truncated | refused | stopped:<reason>
final_text: str
steps: int
usage: Usage
cost_usd: float = 0.0
reason: str = ""
trace: list[dict[str, Any]] = field(default_factory=list)
@dataclass
class Limits:
budget: Budget = field(default_factory=Budget)
breakers: Breakers = field(default_factory=Breakers)
clock: Callable[[], float] = time.monotonic
sleep: Callable[[float], Awaitable[None]] = anyio.sleepHere is the bounded loop. Every stop_reason from Lesson 2 is still handled, and the model's own stop, end_turn, sits next to the stops the harness imposes:
async def run_agent(
model: Model,
tools: McpTools,
task: str,
*,
system: str,
limits: Limits | None = None,
) -> RunResult:
limits = limits or Limits()
definitions = await tools.definitions()
tracker = BudgetTracker(limits.budget, model.name, limits.clock)
messages: list[dict[str, Any]] = [{"role": "user", "content": task}]
trace: list[dict[str, Any]] = []
seen: Counter[str] = Counter()
last_text = ""
def finish(outcome: str, text: str, reason: str = "") -> RunResult:
return RunResult(outcome, text, tracker.steps, tracker.usage, tracker.cost, reason, trace)
while True:
if reason := tracker.before_step():
return finish("budget_exhausted", last_text, reason)
turn: Turn = await model.complete(system=system, tools=definitions, messages=messages)
over = tracker.charge(turn.usage)
record: dict[str, Any] = {
"step": tracker.steps,
"stop_reason": turn.stop_reason,
"usage": vars(turn.usage),
"tool_calls": [],
}
trace.append(record)
if turn.stop_reason == "end_turn":
return finish("done", turn.text())
if turn.stop_reason in ("max_tokens", "model_context_window_exceeded"):
return finish("truncated", turn.text())
if turn.stop_reason == "refusal":
return finish("refused", turn.text())
if over:
# The step that crossed the line is paid for; its tool calls do not run.
return finish("budget_exhausted", turn.text() or last_text, over)
if turn.stop_reason == "pause_turn":
messages.append({"role": "assistant", "content": turn.content})
continue
if turn.stop_reason != "tool_use":
return finish(f"stopped:{turn.stop_reason}", turn.text())
# Only now, with stop_reason known to be tool_use, is the content read.
last_text = turn.text() or last_text
messages.append({"role": "assistant", "content": turn.content})
results = []
for call in turn.tool_calls():
outcome, note = await guarded_call(tools, limits, seen, call["name"], call["input"])
record["tool_calls"].append(
{
"name": call["name"],
"input": call["input"],
"is_error": outcome.is_error,
"note": note,
}
)
results.append(
{
"type": "tool_result",
"tool_use_id": call["id"],
"content": outcome.text,
"is_error": outcome.is_error,
}
)
messages.append({"role": "user", "content": results})Three details are deliberate:
stop_reasonis checked before any content is read. Each branch decides on the reason first, then reads only the text it needs.- A step that crosses a budget is paid for, but its tool calls don't run. If that same response was the model finishing (
end_turn), the answer is kept, because using it costs nothing more. - Nothing is lost.
finishreturns the outcome, the reason, the steps, the usage, the cost and the trace.
Every stop_reason the Claude docs list gets a decision:
stop_reason | Outcome |
|---|---|
end_turn | done, with the final text, even if this step crossed a budget |
max_tokens, model_context_window_exceeded | truncated; the cut-off response's tool calls don't run |
refusal | refused |
pause_turn | continue, unless a budget was crossed |
tool_use | run the calls through guarded_call, unless a budget was crossed |
stop_sequence, or anything new | stopped:<reason> |
A crossed budget is checked after the model's own stops and the cut-offs, and before any tool runs.
This test checks the partial work:
async def test_budget_exhausted_keeps_the_partial_work(tools):
script = [
calls(tool_use("search_tickets", query=f"q{i}"), text=f"Searching, pass {i}.")
for i in range(10)
]
limits = Limits(budget=Budget(max_steps=3), sleep=no_sleep)
result = await run_agent(FakeModel(script), tools, "Go.", system=SYSTEM, limits=limits)
assert (result.outcome, result.reason) == ("budget_exhausted", "step budget of 3 used")
assert result.steps == 3 and len(result.trace) == 3
assert result.final_text == "Searching, pass 2." # the last thing the model said
assert result.usage == Usage(3 * 1200, 3 * 80)The budget tests drive a scripted model that never finishes:
| Test | Budget | Reason returned |
|---|---|---|
test_step_budget_ends_the_run_cleanly | max_steps=5 | step budget of 5 used |
test_token_budget_stops_and_skips_the_crossing_steps_tools | max_tokens=50_000, 30,500 tokens a step | token budget of 50,000 exceeded (61,000) |
test_cached_tokens_count_against_the_token_budget | the same, with 29,000 of each step's tokens from cache | token budget of 50,000 exceeded (61,000) |
test_cost_budget_uses_real_model_prices | max_cost_usd=0.30, $0.12 a step | cost budget of $0.30 exceeded ($0.3600) |
test_time_budget | max_seconds=120, 50 s a step on a fake clock | time budget of 120s used (150.0s) |
The time test injects a clock, so it takes no real time:
async def test_time_budget(tools):
clock = Clock()
def slow_step(messages):
clock.now += 50
return calls(tool_use("search_tickets", query=f"q{clock.now}"))
model = FakeModel([slow_step] * 10)
limits = Limits(budget=Budget(max_seconds=120), clock=clock, sleep=no_sleep)
result = await run_agent(model, tools, "Go.", system=SYSTEM, limits=limits)
assert result.reason == "time budget of 120s used (150.0s)"
assert result.steps == 33. A circuit breaker per tool
When a tool is down, a model tends to try it again with slightly different arguments, which repeated-call detection won't catch. A circuit breaker stops calling the tool after repeated failures:
@dataclass
class CircuitBreaker:
failure_threshold: int = 3
cooldown: float = 30.0
clock: Callable[[], float] = time.monotonic
failures: int = 0
opened_at: float | None = None
@property
def state(self) -> str:
if self.opened_at is None:
return "closed"
if self.clock() - self.opened_at >= self.cooldown:
return "half-open"
return "open"
def allow(self) -> bool:
return self.state != "open"
def record(self, ok: bool) -> None:
if ok:
self.failures, self.opened_at = 0, None
return
self.failures += 1
if self.state == "half-open" or self.failures >= self.failure_threshold:
self.opened_at = self.clock()stateDiagram-v2
[*] --> closed
closed --> open: 3 failures in a row
open --> half_open: 30 s cooldown
half_open --> closed: trial call succeeds
half_open --> open: trial call failsWhile the breaker is closed, calls go through and failures are counted. After three failures in a row it is open, and calls are refused without touching the tool. After the 30-second cooldown it is half-open: the next call goes through as a trial, and its result decides whether the breaker closes or opens again. allow() itself doesn't limit the trial to one call. It is effectively one because the loop runs a step's calls in order and records each result before the next. Breakers keeps one breaker per tool, so a dead knowledge base never blocks ticket searches.
What counts as a breaker failure needs care, because MCP reports both kinds of tool failure the same way, as a result flagged isError. Helpline's crash and Helpline's "no such ticket" are both isError results. The difference is in the text. An unhandled crash on the server reaches the client as exactly Error executing tool <name>, with nothing after it. A failure Helpline anticipated carries a hint for the model. tools.py marks only the first kind as transient, plus timeouts and transport failures:
# An unhandled crash on the server ("Error executing tool X", nothing after it)
# or a timeout may go away on a retry. A ToolError with a hint will not.
_CRASH = re.compile(r"^Error executing tool \w+$")
_TIMEOUT = "did not answer within"
# Safe to retry: they only read. Everything else is called at most once.
READ_ONLY_TOOLS = {"search_tickets", "get_ticket", "search_knowledge_base"} async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome:
try:
result = await self.client.call_tool(name, arguments)
except MCPError as exc: # a protocol error: report it to the model as a failed call
return ToolOutcome(f"Protocol error {exc.error.code}: {exc.error.message[:200]}", True)
except Exception as exc: # transport failure: a short, safe message, no server detail
return ToolOutcome(
f"{name} could not be reached ({type(exc).__name__}).", True, transient=True
)
text = "\n".join(c.text for c in result.content if getattr(c, "text", None))
if not result.is_error:
return ToolOutcome(text, False)
return ToolOutcome(text, True, bool(_CRASH.match(text)) or _TIMEOUT in text)Only transient failures count against a breaker or earn a retry. A tool_result with is_error and a hint means the tool works and the arguments were wrong; counting it would open the breaker on a healthy tool.
When the breaker is open, the model gets a tool_result with is_error and a short message it can act on: "search_knowledge_base is unavailable: it failed 3 times in a row. Continue without it, or finish and say what you could not check."
4. Retries only where they are safe
Some failures go away on a second try. Which tools may you call twice?
- The three read tools can be retried: two searches have the same effect as one.
draft_replycan't. It is a write, and each call saves a new draft in Helpline, so a retry after a lost response would leave two drafts.escalate_ticketis idempotent: Helpline returns the existing escalation instead of creating another. But it is irreversible, because it pages a person, and from Lesson 4 a person approves every call. So it isn't retried either.
Retries happen inside a step, so they don't add steps, tokens or cost: the model isn't called again. What they do spend is time. Each backoff wait, and each slow attempt, comes out of the wall-clock budget, which is checked before the next step. A step with several read calls can spend up to three attempts and 1.5 s of backoff on each, so give the time budget room for that.
The list of retryable tools is the agent's own configuration, READ_ONLY_TOOLS, which McpTools copies into its read_only set. Helpline marks the same three tools with the MCP readOnlyHint annotation, and test_retry_config_agrees_with_the_servers_read_only_hints checks that the two agree. The agent still doesn't read its retry policy from the annotations, because the MCP specification says clients must treat tool annotations as untrusted unless they come from trusted servers. Helpline is trusted here, but the next server might not be.
5. The guarded call
Every tool call goes through guarded_call. It uses one breaker per tool from Breakers, the call key for repeated-call detection, and three constants:
@dataclass
class Breakers:
"""One breaker per tool name, created on first use."""
failure_threshold: int = 3
cooldown: float = 30.0
clock: Callable[[], float] = time.monotonic
by_tool: dict[str, CircuitBreaker] = field(default_factory=dict)
def for_tool(self, name: str) -> CircuitBreaker:
if name not in self.by_tool:
self.by_tool[name] = CircuitBreaker(self.failure_threshold, self.cooldown, self.clock)
return self.by_tool[name]def call_key(name: str, arguments: dict[str, Any]) -> str:
return name + json.dumps(arguments, sort_keys=True)The constants:
MAX_RETRIES = 2
BACKOFF_SECONDS = (0.5, 1.0)
REPEAT_LIMIT = 2 # the third identical call is refusedasync def guarded_call(
tools: McpTools, limits: Limits, seen: Counter[str], name: str, arguments: dict[str, Any]
) -> tuple[ToolOutcome, str]:
"""Run one tool call through the repeat check, the breaker and the retry policy."""
key = call_key(name, arguments)
if seen[key] >= REPEAT_LIMIT:
return (
ToolOutcome(
f"Refused: you already called {name} with these exact arguments "
f"{seen[key]} times and the result will not change. Use what you have, "
"try different arguments, or finish.",
True,
),
"repeat_refused",
)
seen[key] += 1
breaker = limits.breakers.for_tool(name)
if not breaker.allow():
return (
ToolOutcome(
f"{name} is unavailable: it failed {breaker.failures} times in a row. "
"Continue without it, or finish and say what you could not check.",
True,
),
"breaker_open",
)
attempts = 1 + (MAX_RETRIES if name in tools.read_only else 0)
for attempt in range(1, attempts + 1):
outcome = await tools.call(name, arguments)
failed = outcome.is_error and outcome.transient
breaker.record(not failed)
note = f"attempts={attempt}" + ("" if breaker.allow() else ", breaker opened")
if not failed or attempt == attempts or not breaker.allow():
return outcome, note
await limits.sleep(BACKOFF_SECONDS[min(attempt - 1, len(BACKOFF_SECONDS) - 1)])
raise AssertionError("unreachable")Repeated-call detection comes first. call_key is the tool name plus its arguments as JSON with sorted keys, so argument order doesn't matter. The third identical call in a run is refused with a tool_result flagged is_error that tells the model why. Refusing, rather than ending the run, gives the model a chance to change course; if it doesn't, the step budget ends the run. Then the breaker is checked, then the call runs. Read-only tools get up to two retries, with backoff of 0.5 s and then 1.0 s, and the retries stop early if the breaker opens. The note on each call records what happened and lands in the trace.
6. Watching it work
FaultyTools wraps the real tools and makes one fail exactly the way Helpline does when a tool crashes:
@dataclass
class FaultyTools:
inner: McpTools
failures: dict[str, int] = field(default_factory=dict) # tool -> how many calls fail
calls: Counter[str] = field(default_factory=Counter) # calls that reached the tool
@property
def read_only(self) -> set[str]:
return self.inner.read_only
async def definitions(self) -> list[dict[str, Any]]:
return await self.inner.definitions()
async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome:
self.calls[name] += 1
if self.calls[name] <= self.failures.get(name, 0):
return ToolOutcome(f"Error executing tool {name}", True, transient=True)
return await self.inner.call(name, arguments)Here is the dead-tool test. Knowledge-base search always fails, and the model tries it four times with different queries:
async def test_breaker_opens_and_stops_calling_a_dead_tool(tools):
faulty = FaultyTools(tools, failures={"search_knowledge_base": 100})
model = FakeModel(
[calls(tool_use("search_knowledge_base", query=f"try {i}")) for i in range(4)]
+ [answer("Could not reach the knowledge base.")]
)
result = await run_agent(model, faulty, "Go.", system=SYSTEM, limits=Limits(sleep=no_sleep))
notes = [s["tool_calls"][0]["note"] for s in result.trace[:4]]
assert notes == ["attempts=3, breaker opened", "breaker_open", "breaker_open", "breaker_open"]
assert faulty.calls["search_knowledge_base"] == 3 # never touched again once open
assert result.outcome == "done"The first call is tried three times and opens the breaker; the next three are refused without touching the tool. The tool ran exactly three times, and the run still finished. The full cycle runs inside the loop too. Here the knowledge base fails three times and then recovers. The breaker opens, refuses the next call, and after the cooldown on an injected clock the trial call goes through and closes it:
async def test_breaker_recovers_through_half_open_inside_the_loop(tools):
clock = Clock()
faulty = FaultyTools(tools, failures={"search_knowledge_base": 3}) # down, then back
def kb(query):
return calls(tool_use("search_knowledge_base", query=query))
def later(step):
def advance(messages):
clock.now += 31 # past the 30 s cooldown
return step
return advance
model = FakeModel([kb("first"), kb("second"), later(kb("third")), answer("done")])
limits = Limits(breakers=Breakers(clock=clock), clock=clock, sleep=no_sleep)
result = await run_agent(model, faulty, "Go.", system=SYSTEM, limits=limits)
notes = [s["tool_calls"][0]["note"] for s in result.trace[:3]]
assert notes == ["attempts=3, breaker opened", "breaker_open", "attempts=1"]
assert result.trace[2]["tool_calls"][0]["is_error"] is False # the trial call worked
assert limits.breakers.for_tool("search_knowledge_base").state == "closed"The breaker's state machine on its own, open, then half-open after the cooldown, then open or closed by the trial call:
def test_breaker_half_opens_after_the_cooldown():
clock = Clock()
breaker = CircuitBreaker(failure_threshold=3, cooldown=30, clock=clock)
for _ in range(3):
breaker.record(False)
assert breaker.state == "open" and not breaker.allow()
clock.now = 31
assert breaker.state == "half-open" and breaker.allow()
breaker.record(False) # the trial call fails: open again
assert breaker.state == "open"
clock.now = 62
breaker.record(True) # a trial succeeds: closed
assert breaker.state == "closed"The retry rules, each in one test:
async def test_read_tool_is_retried_then_succeeds(tools):
faulty = FaultyTools(tools, failures={"search_knowledge_base": 2})
model = FakeModel(
[calls(tool_use("search_knowledge_base", query="webhook secret")), answer("ok")]
)
no_sleep.waits.clear()
result = await run_agent(model, faulty, "Go.", system=SYSTEM, limits=Limits(sleep=no_sleep))
call = result.trace[0]["tool_calls"][0]
assert call["is_error"] is False
assert call["note"] == "attempts=3"
assert no_sleep.waits == [0.5, 1.0]
async def test_writes_are_never_retried(tools):
faulty = FaultyTools(tools, failures={"draft_reply": 1})
model = FakeModel(
[calls(tool_use("draft_reply", ticket_id="HL-1003", message="Hello")), answer("ok")]
)
result = await run_agent(model, faulty, "Go.", system=SYSTEM, limits=Limits(sleep=no_sleep))
assert result.trace[0]["tool_calls"][0] == {
"name": "draft_reply",
"input": {"ticket_id": "HL-1003", "message": "Hello"},
"is_error": True,
"note": "attempts=1",
}
assert faulty.calls["draft_reply"] == 1
async def test_a_tool_error_with_a_hint_is_not_retried(tools):
model = FakeModel([calls(tool_use("get_ticket", ticket_id="HL-9999")), answer("ok")])
result = await run_agent(model, tools, "Go.", system=SYSTEM, limits=Limits(sleep=no_sleep))
assert result.trace[0]["tool_calls"][0]["note"] == "attempts=1"And repeated-call detection:
async def test_third_identical_call_is_refused(tools):
faulty = FaultyTools(tools)
same = calls(tool_use("search_tickets", query="invoice export"))
model = FakeModel([same, same, same, answer("stopping")])
result = await run_agent(model, faulty, "Go.", system=SYSTEM, limits=Limits(sleep=no_sleep))
notes = [s["tool_calls"][0]["note"] for s in result.trace[:3]]
assert notes == ["attempts=1", "attempts=1", "repeat_refused"]
assert faulty.calls["search_tickets"] == 2
refused = model.requests[3]["messages"][-1]["content"][0]
assert refused["is_error"] is True
assert "2 times and the result will not change" in refused["content"]A guardrail is only as good as the test that catches its removal. Change the breaker check in guarded_call from if not breaker.allow(): to if False: and the dead-tool test fails:
E AssertionError: assert ['attempts=3,...eaker opened'] == ['attempts=3,...breaker_open']
E At index 1 diff: 'attempts=1, breaker opened' != 'breaker_open'
FAILED tests/test_limits.py::test_breaker_opens_and_stops_calling_a_dead_toolPut it back and the lesson's tests pass:
uv run pytest -v tests/test_limits.pytests/test_limits.py::test_step_budget_ends_the_run_cleanly PASSED
tests/test_limits.py::test_token_budget_stops_and_skips_the_crossing_steps_tools PASSED
tests/test_limits.py::test_cost_budget_uses_real_model_prices PASSED
tests/test_limits.py::test_time_budget PASSED
tests/test_limits.py::test_read_tool_is_retried_then_succeeds PASSED
tests/test_limits.py::test_writes_are_never_retried PASSED
tests/test_limits.py::test_a_tool_error_with_a_hint_is_not_retried PASSED
tests/test_limits.py::test_breaker_opens_and_stops_calling_a_dead_tool PASSED
tests/test_limits.py::test_breaker_half_opens_after_the_cooldown PASSED
tests/test_limits.py::test_breakers_are_per_tool PASSED
tests/test_limits.py::test_third_identical_call_is_refused PASSED
tests/test_limits.py::test_retry_config_agrees_with_the_servers_read_only_hints PASSED
tests/test_limits.py::test_cached_tokens_count_against_the_token_budget PASSED
tests/test_limits.py::test_budget_exhausted_keeps_the_partial_work PASSED
tests/test_limits.py::test_breaker_recovers_through_half_open_inside_the_loop PASSED
============================== 15 passed in 0.69s ==============================uv run pytest tests runs these together with Lesson 2's tests: 27 passed. Lesson 2's safety-cap test is gone, because the step budget replaced the cap.
7. Trade-offs to know
- The time budget is checked between steps. A step that starts at 119 seconds can run past 120, and a slow tool call isn't interrupted. Helpline's knowledge-base search has its own timeout; a tool without one needs a per-call timeout around
tools.call. - One unlucky read call can open its breaker by itself. With a threshold of 3 failures and up to 3 attempts per read call, one call that fails three times in a row opens the breaker. That is intended for a dead tool and too eager for a flaky one; raise
failure_thresholdfor tools you expect to blip. - The SDK's tool runner can't host these checks. They sit before each model call and each tool call, inside a loop you own. That is why Lesson 2 wrote the loop by hand.
8. The checklist so far
| Failure | Status |
|---|---|
| Runaway loop | Closed: step, token, cost and time budgets |
| Repeated identical calls | Closed: repeated-call detection |
| Cost blow-up | Closed: cost budget, breakers, read-only retries |
| Indirect prompt injection | Open: Lesson 4 |
| Unapproved irreversible action | Open: Lesson 4 |
9. Common problems
Every run ends with budget_exhausted straight away. Check the units. max_tokens counts tokens summed over the whole run, cached input included, not per call, and max_cost_usd is in dollars.
The cost budget never triggers in tests. The fake model's name is fake, which is priced at zero. Give the scripted model the real model's name when a test needs real prices, as test_cost_budget_uses_real_model_prices does.
The breaker opens on a healthy tool. A failure with a hint is being treated as transient. Only the bare crash message, timeouts and transport failures count.
A write was retried. The tool is in READ_ONLY_TOOLS. Keep that set to tools that only read, whatever the server's annotations say.
10. Exercise: a per-tool call budget
Add a cap of 4 calls per tool per run: the fifth call to the same tool, with any arguments, is refused like a repeated call. Write a test where a scripted model calls search_tickets five times with different queries and then finishes. Assert that the fifth note is your new refusal and that the tool ran four times.
Hint. guarded_call already counts identical calls in seen; a second Counter keyed by tool name works the same way.
Verify. uv run pytest tests should report 28 passed.
11. What comes next
None of these budgets looks at what a tool call does. A model that reads planted instructions in a ticket and escalates another customer's ticket stays inside every budget. Lesson 4 adds the guardrails that look at the calls themselves: what each task may use, which ticket a write may touch, what a draft may say, and a person who approves every escalation.

