Skip to main content

agentfuse

CI PyPI version Python versions License: MIT

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

agentfuse 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

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

Quickstart

Decorators (@guard and @guard_tool)

from typing import Any

from agentfuse 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 agentfuse import Breaker
from agentfuse.adapters.fastapi import AgentFuseMiddleware


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


app = FastAPI()
app.add_middleware(AgentFuseMiddleware, 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 agentfuse import Breaker
from agentfuse.adapters.langgraph import AgentFuseCallbackHandler


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 = AgentFuseCallbackHandler(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 agentfuse:

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: In v0.1, 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

# 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.1.0

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

Source distribution (sdist)

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

Built distribution (wheel)

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

Total release size: 253.3 kB

Release files / llm_breaker-0.1.0.tar.gz

Download URL llm_breaker-0.1.0.tar.gz
Size 235.9 kB
Tags Source
SHA-256 checksum
How to use checksums
947df62bb28fb30f62730ae5b960ea394ff82f7889aeaa3133aa6621133648ff
BLAKE2b-256 checksum
How to use checksums
f3a29b12f7c9787b15441b3b35a037f003ba787253eb6c50156e79ee33a908fd
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 1, 2026.

Transparency log

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

Download URL llm_breaker-0.1.0-py3-none-any.whl
Size 17.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e2ffe06fb49863f9c1bcdbbad6a17ed07b747c08c37bca24a67713a8f20abc69
BLAKE2b-256 checksum
How to use checksums
6f73a6440df663812daac716a5596f1e537094667ed629a6aaa73229710228ff
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 1, 2026.

Transparency log

Security for llm-breaker 0.1.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for llm_breaker-0.1.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 1, 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