← All Articles

AI Agents

Bounded Retries for LLM Tool Calls: A Deterministic Circuit Breaker in Pure Python

Unbounded retry loops are the most expensive bug in agent systems. A zero-dependency breaker that fails fast, recovers on a schedule, and is testable without a network.

By Tharusha Nuwansara · Nov 19, 2026 · 5 min read

How Retry Storms Start

An agent calls a search tool, the tool times out, the framework retries, the model re-plans and calls the tool again. Multiply by every concurrent run and a ten-second upstream blip becomes thousands of wasted model calls. The fix is not more retries; it is refusing to call a dependency that is known to be failing.

Three States, One Clock

A circuit breaker is closed while calls succeed, opens after a threshold of consecutive failures, and half-opens after a cool-down to let one probe through. Injecting the clock keeps it deterministic.

import time


class CircuitOpen(RuntimeError):
    pass


class Breaker:
    def __init__(self, threshold=3, cooldown_s=30.0, clock=time.monotonic):
        self.threshold = threshold
        self.cooldown_s = cooldown_s
        self.clock = clock
        self.failures = 0
        self.opened_at = None

    @property
    def state(self):
        if self.opened_at is None:
            return "closed"
        if self.clock() - self.opened_at >= self.cooldown_s:
            return "half_open"
        return "open"

    def call(self, fn, *args, **kwargs):
        if self.state == "open":
            raise CircuitOpen("dependency is cooling down")
        try:
            result = fn(*args, **kwargs)
        except Exception:
            self.failures += 1
            if self.failures >= self.threshold or self.state == "half_open":
                self.opened_at = self.clock()
            raise
        self.failures = 0
        self.opened_at = None
        return result

A Deterministic Test With an Injected Clock

now = [0.0]
breaker = Breaker(threshold=2, cooldown_s=10, clock=lambda: now[0])


def flaky():
    raise TimeoutError("upstream timeout")


for _ in range(2):
    try:
        breaker.call(flaky)
    except TimeoutError:
        pass

print(breaker.state)          # open
now[0] = 11.0
print(breaker.state)          # half_open
print(breaker.call(lambda: "ok"), breaker.state)  # ok closed

Every state transition is asserted without sleeping or touching the network, so the test runs in milliseconds inside CI.

Production Takeaways

  • Return a structured tool error to the model when the breaker is open so it can choose another plan instead of retrying.
  • Keep one breaker per dependency, not per call site.
  • Log state transitions; they are the earliest signal of an upstream incident.