Skip to main content
Change of provenance

The repository or configuration that created this release differ from a previous release. View details.

llm-breaker

CI PyPI version Python versions License: MIT

A circuit breaker for your LLM agents. It trips when they loop or overspend, so you don't wake up to a surprise API bill.

llm-breaker is a lightweight, thread-safe, framework-agnostic circuit breaker and token budget guard for LLM agents. It tracks per-run spend and per-node token usage, detects repetitive tool-call loops, downgrades to a cheaper fallback model on a soft threshold, and trips with an optional webhook alert on hard limits.

Installation

# Core library (only depends on httpx)
uv add llm-breaker
# or: pip install llm-breaker

# Optional adapters
uv add "llm-breaker[fastapi]"
uv add "llm-breaker[langgraph]"

Quickstart

Decorators (@guard and @guard_tool)

from typing import Any

from llm_breaker import (
    Breaker,
    CircuitOpen,
    WebhookAlert,
    guard,
    guard_tool,
    use_breaker,
)


@guard("planner", fallback_model="gpt-4o-mini")
def call_llm(prompt: str, *, model: str = "gpt-4o") -> dict[str, Any]:
    # Return any OpenAI/Anthropic response object or dict with a "usage" key.
    return {
        "text": f"Summary for: {prompt}",
        "usage": {"prompt_tokens": 800, "completion_tokens": 200},
    }


@guard_tool()
def search_docs(query: str) -> str:
    return f"Found docs for {query}"


breaker = Breaker(
    max_cost_usd=5.0,
    max_node_tokens=200_000,
    soft_ratio=0.8,
    on_trip=WebhookAlert("https://hooks.slack.com/services/...", slack=True),
)

with use_breaker(breaker):
    try:
        reply = call_llm("Summarize Q4 metrics", model="gpt-4o")
        docs = search_docs("Q4 revenue")
    except CircuitOpen as exc:
        print(f"Agent halted: {exc.reason} (spent ${breaker.cost_usd:.4f})")

FastAPI Middleware

from fastapi import FastAPI
from starlette.requests import Request

from llm_breaker import Breaker
from llm_breaker.adapters.fastapi import LLMBreakerMiddleware


def breaker_for_request(request: Request) -> Breaker:
    return Breaker(max_cost_usd=1.0)


app = FastAPI()
app.add_middleware(LLMBreakerMiddleware, breaker_factory=breaker_for_request)
# Any CircuitOpen raised in a route returns HTTP 429:
# {"error": "circuit_open", "reason": "..."}

LangGraph Callback Handler

from typing import TypedDict

from langchain_core.messages import AIMessage
from langgraph.graph import END, START, StateGraph

from llm_breaker import Breaker
from llm_breaker.adapters.langgraph import LLMBreakerCallbackHandler


class State(TypedDict):
    messages: list[object]


builder = StateGraph(State)
builder.add_node("agent", lambda state: {"messages": [AIMessage(content="ok")]})
builder.add_edge(START, "agent")
builder.add_edge("agent", END)
graph = builder.compile()

breaker = Breaker(max_cost_usd=2.0)
handler = LLMBreakerCallbackHandler(breaker)

result = graph.invoke(
    {"messages": [("user", "Investigate the outage")]},
    config={"callbacks": [handler]},
)

Behavior

Signal Threshold / Condition Response
Soft budget warning cost_usd >= max_cost_usd * soft_ratio Sets breaker.degraded = True; @guard(..., fallback_model=...) swaps to the cheaper fallback model
Hard cost cap cost_usd >= max_cost_usd Transitions to OPEN, invokes on_trip(TripEvent), raises CircuitOpen
Per-node token cap node_tokens[node] > max_node_tokens Transitions to OPEN, invokes on_trip(TripEvent), raises CircuitOpen
Identical tool loop Same tool + args repeated >= max_repeats times in sliding window Transitions to OPEN, invokes on_trip(TripEvent), raises CircuitOpen
Cyclic tool loop 2-call or 3-call sequence repeated 3x consecutively Transitions to OPEN, invokes on_trip(TripEvent), raises CircuitOpen
Call while open state == OPEN and elapsed < cooldown_s Immediately raises CircuitOpen("circuit breaker is open") before running the call
Cooldown elapsed state == OPEN and elapsed >= cooldown_s Transitions to HALF_OPEN and allows one probe call
Half-open probe succeeds Probe call finishes without tripping Transitions back to CLOSED and resets LoopDetector
Half-open probe fails Probe call trips any guard Reopens to OPEN, restarts cooldown, invokes on_trip, raises CircuitOpen

Example (Simulated Run)

Run the offline simulation comparing an unguarded looping agent (halted by a synthetic $10.00 spend counter) against the same simulated loop protected by llm-breaker:

uv run python examples/runaway_agent.py

Simulated output (synthetic token counts, no real API calls or real billing savings):

=== Runaway Agent Comparison (Simulated Run — No Real API Calls) ===
Unguarded (simulated) : stopped after 84 steps | simulated_cost=$10.0800 | reason=simulated spend cap ($10.00)
Guarded   (simulated) : stopped after  4 steps | simulated_cost=$0.4800 | reason=loop detected: identical tool call repeated 4x
Simulated cost avoided: $9.6000 (based on synthetic token counts)

Limitations

  • Post-call budget enforcement: Token usage and cost are checked after each LLM call completes, so the call that crosses max_cost_usd or max_node_tokens finishes and is billed by your provider; subsequent calls are blocked.
  • Price-table accuracy: Computed USD spend depends on the configured PriceTable. Provider prices change over time, and unknown model names record $0.00 while logging a one-time warning—pass your own prices table in production.
  • Exact-match loop detection: Currently, LoopDetector hashes canonicalized tool names and exact JSON arguments (signature()). Near-duplicate arguments (such as slightly rephrased search queries) are not treated as identical calls yet.

Roadmap

  • Pre-call cost estimation: Input-token counting and max-output reservation for a true pre-flight hard stop.
  • Fuzzy loop detection: Similarity-based detection for near-duplicate tool arguments.
  • Distributed Redis state store: Shared breaker budgets across multi-process and multi-worker deployments.
  • OpenTelemetry export: Native spans, metrics, and trip events for observability pipelines.

Development

# Install dependencies (including dev tools and adapter extras)
uv sync --all-extras

# Run tests
uv run pytest -q

# Lint and format check
uv run ruff check .
uv run ruff format --check .

# Strict type checking
uv run mypy src

Metadata

Release files for llm-breaker 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Change of provenance

The repository or configuration that created these release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Source distribution (sdist)

Source distribution for llm-breaker 0.2.0
File Size Uploaded Provenance Actions
llm_breaker-0.2.0.tar.gz 236.8 kB With provenance Details for llm_breaker-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for llm-breaker 0.2.0
File Interpreter ABI Platform Actions
llm_breaker-0.2.0-py3-none-any.whl Python 3 none any Details for llm_breaker-0.2.0-py3-none-any.whl

Total release size: 254.3 kB

Release files / llm_breaker-0.2.0.tar.gz

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL llm_breaker-0.2.0.tar.gz
Size 236.8 kB
Tags Source
SHA-256 checksum
How to use checksums
d22aeef1ebd009e46625e8a9aea9dff3aa00cd89aa1aebfc764ead4939a5c4c4
BLAKE2b-256 checksum
How to use checksums
c3307c4797ab863ce051782aeeb8370cbe7db549d5b0b0b502c6ee52d710738b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Release files / llm_breaker-0.2.0-py3-none-any.whl

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL llm_breaker-0.2.0-py3-none-any.whl
Size 17.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7b65e3cb7313b543c8e0e8aadfbbeb7a74e5a7cc71570d8e8ab15b54991e6da7
BLAKE2b-256 checksum
How to use checksums
5d1cef1523952b5543a0c8a3569777d7f7a9961626f47056d2b1218dce8d5071
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Security for llm-breaker 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Change of provenance

The repository and configuration that created this release differ from a previous release.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Select from 2 files

Attestation for llm_breaker-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page