toolcircuit
toolcircuit

how toolcircuit fits in

Install

consolepip install toolcircuit

Use

pythonfrom toolcircuit import CircuitOpen, Policy, ToolCircuit

circuit = ToolCircuit(
    default=Policy(failure_threshold=3, cooldown=30),
    policies={"search": Policy(failure_threshold=2, cooldown=120)},
)

def call_tool(name, tool, **arguments):
    try:
        return circuit.call(name, tool, **arguments)
    except CircuitOpen as error:
        return {"error": str(error), "retry_after": error.retry_after}
    except Exception as error:
        return {"error": f"{name} failed: {error}"}

Reading it back:

pythoncircuit.state("search")        # 'closed' | 'open' | 'half-open'
circuit.allow("search")        # False while open
circuit.failures("search")     # consecutive failures
circuit.retry_after("search")  # seconds until the next trial
circuit.report()               # {"search": {"state": "open", "failures": 3, …}}
circuit.reset()                # new run

How the states work

state meaning calls allowed
closedhealthy, failures below the thresholdyes
openthreshold reachedno, CircuitOpen with a wait time
half-opencooldown has passedone trial

A success anywhere closes the circuit and resets the failure count. A failure in half-open reopens it for another full cooldown — the service had its chance.

The clock is injectable, which is how the tests avoid sleeping:

pythonnow = 0.0
circuit = ToolCircuit(clock=lambda: now)

Rules

shared store, which is a different library on purpose: a breaker that needs a network round trip is a breaker that breaks the run when that network is down.

keeps working; only the refusal case is a new exception type.

outage, so catch that before calling call, not after.

on the first success after a cooldown, or on reset().

Limits

either, wrap Policy and replace the breaker object.

once.

a long-lived service — persist report() if you need that.

Development

consolepython -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest

The suite covers every line of the package (pytest --cov --cov-branch), and the examples in the docstrings run as tests through --doctest-modules.

License

MIT.

Other libraries here

One problem each, standard library only, no runtime dependencies.