Metadata-Version: 2.5
Name: llm-breaker
Version: 0.2.0
Summary: A circuit breaker and token budget guard for LLM agents.
Project-URL: Homepage, https://github.com/Rival5555/llm-breaker
Project-URL: Repository, https://github.com/Rival5555/llm-breaker
Project-URL: Issues, https://github.com/Rival5555/llm-breaker/issues
Author-email: Hassan Ali <hassanali93r@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Hassan Ali
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Provides-Extra: examples
Requires-Dist: langchain-openai>=0.2; extra == 'examples'
Requires-Dist: langgraph>=0.2; extra == 'examples'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
Requires-Dist: starlette>=0.37; extra == 'fastapi'
Provides-Extra: langgraph
Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
Description-Content-Type: text/markdown

# llm-breaker

[![CI](https://img.shields.io/github/actions/workflow/status/Rival5555/llm-breaker/ci.yml?branch=main&label=CI)](https://github.com/Rival5555/llm-breaker/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/llm-breaker)](https://pypi.org/project/llm-breaker/)
[![Python versions](https://img.shields.io/pypi/pyversions/llm-breaker)](https://pypi.org/project/llm-breaker/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

> 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

```bash
# 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`)

```python
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

```python
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

```python
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`:

```bash
uv run python examples/runaway_agent.py
```

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

```text
=== 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

```bash
# 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
```
