Metadata-Version: 2.4
Name: fuse-breaker
Version: 0.2.1
Summary: Provider-neutral circuit breaker for AI agents: spend, call and failure limits, enforced locally or via the FuseGuard hosted API.
License: MIT
Project-URL: Homepage, https://fuseguard.lovable.app
Project-URL: Documentation, https://fuseguard.lovable.app
Project-URL: Source, https://fuseguard.lovable.app
Keywords: ai,agents,circuit-breaker,rate-limit,budget,llm,fuseguard
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# fuse-breaker (Python SDK)

Provider-neutral circuit breaker for AI agents. Enforces a spend budget, a call limit and a
consecutive-failure limit around any model or tool callable. No dependencies. Python 3.9+.

## 1. Install (clean environment)
```sh
python3 -m venv .venv && . .venv/bin/activate
pip install fuse-breaker            # from PyPI
# or, from a checkout of this repository:
pip install ./sdk/python
python sdk/python/examples/quickstart.py
# ALLOWED: tool ran
# BLOCKED: Tool-call limit reached
```

## 2. Local mode (free, offline)
```python
from fuse_breaker import CircuitBreaker, Limits, CircuitOpenError, JsonlAuditLog

breaker = CircuitBreaker(Limits(budget=5.0, steps=100, failures=3),
                         audit=JsonlAuditLog("fuse-audit.jsonl"),
                         approver=lambda req: input(f"Allow {req['action']}? [y/N] ") == "y")

reply = breaker.guard(lambda: my_model(prompt), estimated_cost=0.02,
                      actual_cost=lambda r: r.cost, timeout=30)
breaker.guard(lambda: delete_rows(), estimated_cost=0, action="delete_rows", consequential=True)
# async: await breaker.aguard(lambda: my_async_call(), estimated_cost=0.02)
breaker.stop(); breaker.reset()
```

## 3. Hosted mode (dashboard)
1. Sign in to the Fuse app, register an agent, set its limits, and create a runtime key
   (shown once; only a hash is stored).
2. Point the SDK at the **published** app — preview links require a Lovable login and will
   return 401 to external machines:
```sh
export FUSE_API_URL=https://<published-app-domain>/api/public/v1
export FUSE_AGENT_KEY=fuse_...
python sdk/python/examples/quickstart.py --hosted   # set max calls = 1 first to see a block
```
```python
from fuse_breaker import RemoteBreaker
breaker = RemoteBreaker()          # same guard() signature; limits set in the dashboard
```
The dashboard shows the agent as *protected* once it has checked in within 5 minutes.

## 4. Cost accounting — actual vs estimated

Every call **reserves** `estimated_cost` before it runs (so concurrent calls can never
overshoot the budget) and is then **settled** with a cost tagged with its source:

| `cost_source` | Meaning |
|---|---|
| `provider_reported` | the provider's response contained a monetary `usage.cost` |
| `computed` | provider-reported token counts × a price table **you** configured |
| `caller_reported` | your `actual_cost` callback returned a number |
| `estimate` | nothing better was available — the reserved estimate was charged |

The audit log and dashboard record the source; dashboard costs without an actual source show
**"est."**. Only `provider_reported` is a provider's own figure; `computed` is as accurate as the
rates you entered. Neither is your provider invoice.

**No prices are bundled.** Rates change and vary by account, so the SDK never guesses. Copy
them from your provider's pricing page into a versioned file:
```json
{ "version": "my-prices-2026-10-15",
  "models": { "openai/gpt-6-astra": { "input_per_mtok": 0.0, "output_per_mtok": 0.0,
      "cached_input_per_mtok": 0.0, "source_url": "https://…", "effective_date": "2026-10-15" } } }
```
(USD per 1M tokens; the zeros are placeholders you must replace.) Then
`export FUSE_PRICING_FILE=prices.json` or pass `pricing=PriceTable.from_file(...)`.
`pricing_version` is recorded with each computed cost.

**Unknown tool costs.** Tools (search APIs, code runners, etc.) rarely report spend. If you
pass no `actual_cost`, the full `estimated_cost` is charged and labelled `estimate` — so set
the estimate to a realistic *upper bound*. Failed calls charge `0` (labelled `estimate`) unless
you pass `failure_cost`. A crashing `actual_cost` callback falls back to the estimate.

If actual cost exceeds the reservation, it is still recorded and the breaker trips
("Budget limit exceeded by actual cost") — the overshoot is bounded by one call.

## 5. Real model integration
```python
from fuse_breaker.integrations.openai_compat import guarded_chat
r = guarded_chat(breaker, [{"role": "user", "content": "hi"}], estimated_cost=0.02)
r["text"], r["usage"], r["cost"], r["cost_source"], r["pricing_version"]
```
Calls any OpenAI-compatible Chat Completions endpoint (default: Lovable AI Gateway, key in
`LOVABLE_API_KEY`; override with `base_url`, `api_key_env`, `FUSE_BASE_URL`). Token counts come
from the provider's streamed `usage`.

## Environment variables
| Name | Used by |
|---|---|
| `FUSE_API_URL`, `FUSE_AGENT_KEY` | `RemoteBreaker` |
| `FUSE_PRICING_FILE` | optional price table for `guarded_chat` |
| `LOVABLE_API_KEY` (or your `api_key_env`) | `guarded_chat` |
| `FUSE_BASE_URL` | optional model endpoint override |

## Tests
```sh
cd sdk/python && python3 -m unittest discover -s tests       # offline tests
PYTHONPATH=. python3 examples/live_demo.py                     # real model: allowed then blocked
PYTHONPATH=. python3 examples/hosted_e2e.py                    # hosted: real call, 10 concurrent, blocked
```

## Limitations
- Costs are only as accurate as their source (see table above); estimates are not invoices.
- Sync `timeout` stops waiting but cannot kill a running Python thread.
- Hosted mode adds one round trip before and after each call and fails closed if the API is
  unreachable (`fail_open=True` runs unprotected only when the API is unreachable — network, timeout or 5xx; auth errors always refuse). Settlement is retried; if it still fails the
  result is returned and the id is kept in `breaker.unsettled`.
- A crashed process leaves its reservation open; the server expires it after 10 minutes and
  charges its estimate (reset also clears reservations older than 5 minutes).
- Human approval is local-only for now. TypeScript: `@ronwey140/fuseguard-hosted` and
  `@ronwey140/fuseguard-langchain` on npm.
