llm-breaker 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llm_breaker-0.1.0/.github/workflows/ci.yml +63 -0
- llm_breaker-0.1.0/.github/workflows/release.yml +49 -0
- llm_breaker-0.1.0/.gitignore +18 -0
- llm_breaker-0.1.0/.python-version +1 -0
- llm_breaker-0.1.0/CHANGELOG.md +17 -0
- llm_breaker-0.1.0/LICENSE +21 -0
- llm_breaker-0.1.0/PKG-INFO +230 -0
- llm_breaker-0.1.0/README.md +179 -0
- llm_breaker-0.1.0/examples/real_langgraph_check.py +126 -0
- llm_breaker-0.1.0/examples/runaway_agent.py +127 -0
- llm_breaker-0.1.0/pyproject.toml +66 -0
- llm_breaker-0.1.0/src/agentfuse/__init__.py +26 -0
- llm_breaker-0.1.0/src/agentfuse/adapters/__init__.py +17 -0
- llm_breaker-0.1.0/src/agentfuse/adapters/decorator.py +197 -0
- llm_breaker-0.1.0/src/agentfuse/adapters/fastapi.py +77 -0
- llm_breaker-0.1.0/src/agentfuse/adapters/langgraph.py +199 -0
- llm_breaker-0.1.0/src/agentfuse/alerts/__init__.py +8 -0
- llm_breaker-0.1.0/src/agentfuse/alerts/webhook.py +77 -0
- llm_breaker-0.1.0/src/agentfuse/core/__init__.py +18 -0
- llm_breaker-0.1.0/src/agentfuse/core/breaker.py +184 -0
- llm_breaker-0.1.0/src/agentfuse/core/loops.py +59 -0
- llm_breaker-0.1.0/src/agentfuse/core/pricing.py +53 -0
- llm_breaker-0.1.0/src/agentfuse/py.typed +1 -0
- llm_breaker-0.1.0/tests/test_breaker.py +345 -0
- llm_breaker-0.1.0/tests/test_decorator.py +162 -0
- llm_breaker-0.1.0/tests/test_fastapi.py +118 -0
- llm_breaker-0.1.0/tests/test_langgraph.py +240 -0
- llm_breaker-0.1.0/tests/test_loops.py +96 -0
- llm_breaker-0.1.0/tests/test_pricing.py +50 -0
- llm_breaker-0.1.0/tests/test_webhook.py +114 -0
- llm_breaker-0.1.0/uv.lock +3024 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: ["main"]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: ["main"]
|
|
8
|
+
|
|
9
|
+
permissions:
|
|
10
|
+
contents: read
|
|
11
|
+
|
|
12
|
+
jobs:
|
|
13
|
+
test:
|
|
14
|
+
name: Test (Python ${{ matrix.python-version }})
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
strategy:
|
|
17
|
+
fail-fast: false
|
|
18
|
+
matrix:
|
|
19
|
+
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
|
20
|
+
steps:
|
|
21
|
+
- name: Checkout repository
|
|
22
|
+
uses: actions/checkout@v4
|
|
23
|
+
|
|
24
|
+
- name: Set up uv
|
|
25
|
+
uses: astral-sh/setup-uv@v5
|
|
26
|
+
with:
|
|
27
|
+
python-version: ${{ matrix.python-version }}
|
|
28
|
+
|
|
29
|
+
- name: Sync dependencies
|
|
30
|
+
run: uv sync --all-extras
|
|
31
|
+
|
|
32
|
+
- name: Lint with ruff
|
|
33
|
+
run: uv run ruff check .
|
|
34
|
+
|
|
35
|
+
- name: Check formatting with ruff
|
|
36
|
+
run: uv run ruff format --check .
|
|
37
|
+
|
|
38
|
+
- name: Type-check with mypy
|
|
39
|
+
run: uv run mypy src
|
|
40
|
+
|
|
41
|
+
- name: Run pytest
|
|
42
|
+
run: uv run pytest -q
|
|
43
|
+
|
|
44
|
+
build:
|
|
45
|
+
name: Build & Verify Wheel
|
|
46
|
+
runs-on: ubuntu-latest
|
|
47
|
+
steps:
|
|
48
|
+
- name: Checkout repository
|
|
49
|
+
uses: actions/checkout@v4
|
|
50
|
+
|
|
51
|
+
- name: Set up uv
|
|
52
|
+
uses: astral-sh/setup-uv@v5
|
|
53
|
+
with:
|
|
54
|
+
python-version: "3.12"
|
|
55
|
+
|
|
56
|
+
- name: Build sdist and wheel
|
|
57
|
+
run: uv build
|
|
58
|
+
|
|
59
|
+
- name: Check distribution metadata with twine
|
|
60
|
+
run: uvx twine check dist/*
|
|
61
|
+
|
|
62
|
+
- name: Verify py.typed is packaged in wheel
|
|
63
|
+
run: unzip -l dist/*.whl | grep "agentfuse/py.typed"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Manual setup required before pushing your first release tag:
|
|
2
|
+
#
|
|
3
|
+
# 1. On https://pypi.org/manage/account/publishing/ (under "Add a new pending publisher",
|
|
4
|
+
# or under Project -> Publishing if "llm-breaker" already exists on PyPI), register a
|
|
5
|
+
# GitHub Actions Trusted Publisher with:
|
|
6
|
+
# - PyPI Project Name: llm-breaker
|
|
7
|
+
# - Owner: Rival5555
|
|
8
|
+
# - Repository name: agentfuse
|
|
9
|
+
# - Workflow name: release.yml
|
|
10
|
+
# - Environment name: pypi
|
|
11
|
+
# 2. On GitHub, go to Repository -> Settings -> Environments and create the "pypi"
|
|
12
|
+
# environment (optionally adding required reviewers or tag protection rules).
|
|
13
|
+
# 3. Bump version in pyproject.toml + src/agentfuse/__init__.py + CHANGELOG.md, commit,
|
|
14
|
+
# then push a matching tag (e.g., `git tag v0.1.0 && git push origin v0.1.0`).
|
|
15
|
+
|
|
16
|
+
name: Release to PyPI
|
|
17
|
+
|
|
18
|
+
on:
|
|
19
|
+
push:
|
|
20
|
+
tags:
|
|
21
|
+
- "v*"
|
|
22
|
+
|
|
23
|
+
permissions:
|
|
24
|
+
contents: read
|
|
25
|
+
|
|
26
|
+
jobs:
|
|
27
|
+
publish:
|
|
28
|
+
name: Build and publish to PyPI
|
|
29
|
+
runs-on: ubuntu-latest
|
|
30
|
+
environment:
|
|
31
|
+
name: ${{ 'pypi' }}
|
|
32
|
+
url: https://pypi.org/p/llm-breaker
|
|
33
|
+
permissions:
|
|
34
|
+
contents: read
|
|
35
|
+
id-token: write
|
|
36
|
+
steps:
|
|
37
|
+
- name: Checkout repository
|
|
38
|
+
uses: actions/checkout@v4
|
|
39
|
+
|
|
40
|
+
- name: Set up uv
|
|
41
|
+
uses: astral-sh/setup-uv@v5
|
|
42
|
+
with:
|
|
43
|
+
python-version: "3.12"
|
|
44
|
+
|
|
45
|
+
- name: Build sdist and wheel
|
|
46
|
+
run: uv build
|
|
47
|
+
|
|
48
|
+
- name: Publish distributions to PyPI via Trusted Publishing
|
|
49
|
+
uses: pypa/gh-action-pypi-publish@v1.14.3
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.10
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.1.0] - 2026-12-01
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- Thread-safe and asyncio-safe per-run `Breaker` state machine (`CLOSED`, `OPEN`, `HALF_OPEN`) with per-run USD spend caps, soft-budget model degradation (`soft_ratio`), per-node token caps, and cooldown/probe recovery.
|
|
12
|
+
- Token usage and pricing primitives (`Usage`, `PriceTable`, `PRICES`, `cost_usd`) with one-time warnings for unknown models.
|
|
13
|
+
- Sliding-window `LoopDetector` and canonical SHA-1 tool-call `signature` detecting identical repeated tool calls and 2-step / 3-step call cycles.
|
|
14
|
+
- Fault-tolerant `WebhookAlert` dispatcher supporting structured JSON and Slack payloads synchronously or on a background daemon thread.
|
|
15
|
+
- Sync and async `@guard` and `@guard_tool` decorators with `ContextVar` binding (`use_breaker`, `current_breaker`), automatic fallback model swapping when degraded, and OpenAI/Anthropic usage extraction.
|
|
16
|
+
- Pure ASGI `AgentFuseMiddleware` for FastAPI and Starlette (`agentfuse[fastapi]`) returning HTTP 429 JSON on `CircuitOpen`.
|
|
17
|
+
- `AgentFuseCallbackHandler` for LangChain and LangGraph (`agentfuse[langgraph]`) tracking per-node token usage and tool-call loops.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hassan Ali
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: llm-breaker
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A circuit breaker and token budget guard for LLM agents.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Rival5555/agentfuse
|
|
6
|
+
Project-URL: Repository, https://github.com/Rival5555/agentfuse
|
|
7
|
+
Project-URL: Issues, https://github.com/Rival5555/agentfuse/issues
|
|
8
|
+
Author-email: Hassan Ali <hassanali93r@gmail.com>
|
|
9
|
+
License: MIT License
|
|
10
|
+
|
|
11
|
+
Copyright (c) 2026 Hassan Ali
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
14
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
15
|
+
in the Software without restriction, including without limitation the rights
|
|
16
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
17
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
18
|
+
furnished to do so, subject to the following conditions:
|
|
19
|
+
|
|
20
|
+
The above copyright notice and this permission notice shall be included in all
|
|
21
|
+
copies or substantial portions of the Software.
|
|
22
|
+
|
|
23
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
24
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
26
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
27
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
|
+
SOFTWARE.
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Classifier: Development Status :: 3 - Alpha
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Programming Language :: Python :: 3
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
39
|
+
Classifier: Typing :: Typed
|
|
40
|
+
Requires-Python: >=3.10
|
|
41
|
+
Requires-Dist: httpx>=0.27
|
|
42
|
+
Provides-Extra: examples
|
|
43
|
+
Requires-Dist: langchain-openai>=0.2; extra == 'examples'
|
|
44
|
+
Requires-Dist: langgraph>=0.2; extra == 'examples'
|
|
45
|
+
Provides-Extra: fastapi
|
|
46
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
47
|
+
Requires-Dist: starlette>=0.37; extra == 'fastapi'
|
|
48
|
+
Provides-Extra: langgraph
|
|
49
|
+
Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
|
|
50
|
+
Description-Content-Type: text/markdown
|
|
51
|
+
|
|
52
|
+
# agentfuse
|
|
53
|
+
|
|
54
|
+
[](https://github.com/Rival5555/agentfuse/actions/workflows/ci.yml)
|
|
55
|
+
[](https://pypi.org/project/llm-breaker/)
|
|
56
|
+
[](https://pypi.org/project/llm-breaker/)
|
|
57
|
+
[](LICENSE)
|
|
58
|
+
|
|
59
|
+
> A fuse for your agents. It trips when they loop or overspend, so you don't wake up to a surprise API bill.
|
|
60
|
+
|
|
61
|
+
`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.
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Core library (only depends on httpx)
|
|
67
|
+
uv add llm-breaker
|
|
68
|
+
|
|
69
|
+
# Optional adapters
|
|
70
|
+
uv add "llm-breaker[fastapi]"
|
|
71
|
+
uv add "llm-breaker[langgraph]"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Quickstart
|
|
75
|
+
|
|
76
|
+
### Decorators (`@guard` and `@guard_tool`)
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from typing import Any
|
|
80
|
+
|
|
81
|
+
from agentfuse import (
|
|
82
|
+
Breaker,
|
|
83
|
+
CircuitOpen,
|
|
84
|
+
WebhookAlert,
|
|
85
|
+
guard,
|
|
86
|
+
guard_tool,
|
|
87
|
+
use_breaker,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@guard("planner", fallback_model="gpt-4o-mini")
|
|
92
|
+
def call_llm(prompt: str, *, model: str = "gpt-4o") -> dict[str, Any]:
|
|
93
|
+
# Return any OpenAI/Anthropic response object or dict with a "usage" key.
|
|
94
|
+
return {
|
|
95
|
+
"text": f"Summary for: {prompt}",
|
|
96
|
+
"usage": {"prompt_tokens": 800, "completion_tokens": 200},
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@guard_tool()
|
|
101
|
+
def search_docs(query: str) -> str:
|
|
102
|
+
return f"Found docs for {query}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
breaker = Breaker(
|
|
106
|
+
max_cost_usd=5.0,
|
|
107
|
+
max_node_tokens=200_000,
|
|
108
|
+
soft_ratio=0.8,
|
|
109
|
+
on_trip=WebhookAlert("https://hooks.slack.com/services/...", slack=True),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
with use_breaker(breaker):
|
|
113
|
+
try:
|
|
114
|
+
reply = call_llm("Summarize Q4 metrics", model="gpt-4o")
|
|
115
|
+
docs = search_docs("Q4 revenue")
|
|
116
|
+
except CircuitOpen as exc:
|
|
117
|
+
print(f"Agent halted: {exc.reason} (spent ${breaker.cost_usd:.4f})")
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### FastAPI Middleware
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from fastapi import FastAPI
|
|
124
|
+
from starlette.requests import Request
|
|
125
|
+
|
|
126
|
+
from agentfuse import Breaker
|
|
127
|
+
from agentfuse.adapters.fastapi import AgentFuseMiddleware
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def breaker_for_request(request: Request) -> Breaker:
|
|
131
|
+
return Breaker(max_cost_usd=1.0)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
app = FastAPI()
|
|
135
|
+
app.add_middleware(AgentFuseMiddleware, breaker_factory=breaker_for_request)
|
|
136
|
+
# Any CircuitOpen raised in a route returns HTTP 429:
|
|
137
|
+
# {"error": "circuit_open", "reason": "..."}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### LangGraph Callback Handler
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from typing import TypedDict
|
|
144
|
+
|
|
145
|
+
from langchain_core.messages import AIMessage
|
|
146
|
+
from langgraph.graph import END, START, StateGraph
|
|
147
|
+
|
|
148
|
+
from agentfuse import Breaker
|
|
149
|
+
from agentfuse.adapters.langgraph import AgentFuseCallbackHandler
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class State(TypedDict):
|
|
153
|
+
messages: list[object]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
builder = StateGraph(State)
|
|
157
|
+
builder.add_node("agent", lambda state: {"messages": [AIMessage(content="ok")]})
|
|
158
|
+
builder.add_edge(START, "agent")
|
|
159
|
+
builder.add_edge("agent", END)
|
|
160
|
+
graph = builder.compile()
|
|
161
|
+
|
|
162
|
+
breaker = Breaker(max_cost_usd=2.0)
|
|
163
|
+
handler = AgentFuseCallbackHandler(breaker)
|
|
164
|
+
|
|
165
|
+
result = graph.invoke(
|
|
166
|
+
{"messages": [("user", "Investigate the outage")]},
|
|
167
|
+
config={"callbacks": [handler]},
|
|
168
|
+
)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Behavior
|
|
172
|
+
|
|
173
|
+
| Signal | Threshold / Condition | Response |
|
|
174
|
+
| --- | --- | --- |
|
|
175
|
+
| **Soft budget warning** | `cost_usd >= max_cost_usd * soft_ratio` | Sets `breaker.degraded = True`; `@guard(..., fallback_model=...)` swaps to the cheaper fallback model |
|
|
176
|
+
| **Hard cost cap** | `cost_usd >= max_cost_usd` | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
177
|
+
| **Per-node token cap** | `node_tokens[node] > max_node_tokens` | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
178
|
+
| **Identical tool loop** | Same tool + args repeated `>= max_repeats` times in sliding `window` | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
179
|
+
| **Cyclic tool loop** | 2-call or 3-call sequence repeated 3x consecutively | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
180
|
+
| **Call while open** | `state == OPEN` and elapsed `< cooldown_s` | Immediately raises `CircuitOpen("circuit breaker is open")` before running the call |
|
|
181
|
+
| **Cooldown elapsed** | `state == OPEN` and elapsed `>= cooldown_s` | Transitions to `HALF_OPEN` and allows one probe call |
|
|
182
|
+
| **Half-open probe succeeds** | Probe call finishes without tripping | Transitions back to `CLOSED` and resets `LoopDetector` |
|
|
183
|
+
| **Half-open probe fails** | Probe call trips any guard | Reopens to `OPEN`, restarts cooldown, invokes `on_trip`, raises `CircuitOpen` |
|
|
184
|
+
|
|
185
|
+
## Example (Simulated Run)
|
|
186
|
+
|
|
187
|
+
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`:
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
uv run python examples/runaway_agent.py
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Simulated output (synthetic token counts, no real API calls or real billing savings):
|
|
194
|
+
|
|
195
|
+
```text
|
|
196
|
+
=== Runaway Agent Comparison (Simulated Run — No Real API Calls) ===
|
|
197
|
+
Unguarded (simulated) : stopped after 84 steps | simulated_cost=$10.0800 | reason=simulated spend cap ($10.00)
|
|
198
|
+
Guarded (simulated) : stopped after 4 steps | simulated_cost=$0.4800 | reason=loop detected: identical tool call repeated 4x
|
|
199
|
+
Simulated cost avoided: $9.6000 (based on synthetic token counts)
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Limitations
|
|
203
|
+
|
|
204
|
+
- **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.
|
|
205
|
+
- **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.
|
|
206
|
+
- **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.
|
|
207
|
+
|
|
208
|
+
## Roadmap
|
|
209
|
+
|
|
210
|
+
- **Pre-call cost estimation:** Input-token counting and max-output reservation for a true pre-flight hard stop.
|
|
211
|
+
- **Fuzzy loop detection:** Similarity-based detection for near-duplicate tool arguments.
|
|
212
|
+
- **Distributed Redis state store:** Shared breaker budgets across multi-process and multi-worker deployments.
|
|
213
|
+
- **OpenTelemetry export:** Native spans, metrics, and trip events for observability pipelines.
|
|
214
|
+
|
|
215
|
+
## Development
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
# Install dependencies (including dev tools and adapter extras)
|
|
219
|
+
uv sync
|
|
220
|
+
|
|
221
|
+
# Run tests
|
|
222
|
+
uv run pytest -q
|
|
223
|
+
|
|
224
|
+
# Lint and format check
|
|
225
|
+
uv run ruff check .
|
|
226
|
+
uv run ruff format --check .
|
|
227
|
+
|
|
228
|
+
# Strict type checking
|
|
229
|
+
uv run mypy src
|
|
230
|
+
```
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# agentfuse
|
|
2
|
+
|
|
3
|
+
[](https://github.com/Rival5555/agentfuse/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/llm-breaker/)
|
|
5
|
+
[](https://pypi.org/project/llm-breaker/)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
> A fuse for your agents. It trips when they loop or overspend, so you don't wake up to a surprise API bill.
|
|
9
|
+
|
|
10
|
+
`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.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
# Core library (only depends on httpx)
|
|
16
|
+
uv add llm-breaker
|
|
17
|
+
|
|
18
|
+
# Optional adapters
|
|
19
|
+
uv add "llm-breaker[fastapi]"
|
|
20
|
+
uv add "llm-breaker[langgraph]"
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quickstart
|
|
24
|
+
|
|
25
|
+
### Decorators (`@guard` and `@guard_tool`)
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from agentfuse import (
|
|
31
|
+
Breaker,
|
|
32
|
+
CircuitOpen,
|
|
33
|
+
WebhookAlert,
|
|
34
|
+
guard,
|
|
35
|
+
guard_tool,
|
|
36
|
+
use_breaker,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@guard("planner", fallback_model="gpt-4o-mini")
|
|
41
|
+
def call_llm(prompt: str, *, model: str = "gpt-4o") -> dict[str, Any]:
|
|
42
|
+
# Return any OpenAI/Anthropic response object or dict with a "usage" key.
|
|
43
|
+
return {
|
|
44
|
+
"text": f"Summary for: {prompt}",
|
|
45
|
+
"usage": {"prompt_tokens": 800, "completion_tokens": 200},
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@guard_tool()
|
|
50
|
+
def search_docs(query: str) -> str:
|
|
51
|
+
return f"Found docs for {query}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
breaker = Breaker(
|
|
55
|
+
max_cost_usd=5.0,
|
|
56
|
+
max_node_tokens=200_000,
|
|
57
|
+
soft_ratio=0.8,
|
|
58
|
+
on_trip=WebhookAlert("https://hooks.slack.com/services/...", slack=True),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
with use_breaker(breaker):
|
|
62
|
+
try:
|
|
63
|
+
reply = call_llm("Summarize Q4 metrics", model="gpt-4o")
|
|
64
|
+
docs = search_docs("Q4 revenue")
|
|
65
|
+
except CircuitOpen as exc:
|
|
66
|
+
print(f"Agent halted: {exc.reason} (spent ${breaker.cost_usd:.4f})")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### FastAPI Middleware
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from fastapi import FastAPI
|
|
73
|
+
from starlette.requests import Request
|
|
74
|
+
|
|
75
|
+
from agentfuse import Breaker
|
|
76
|
+
from agentfuse.adapters.fastapi import AgentFuseMiddleware
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def breaker_for_request(request: Request) -> Breaker:
|
|
80
|
+
return Breaker(max_cost_usd=1.0)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
app = FastAPI()
|
|
84
|
+
app.add_middleware(AgentFuseMiddleware, breaker_factory=breaker_for_request)
|
|
85
|
+
# Any CircuitOpen raised in a route returns HTTP 429:
|
|
86
|
+
# {"error": "circuit_open", "reason": "..."}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### LangGraph Callback Handler
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from typing import TypedDict
|
|
93
|
+
|
|
94
|
+
from langchain_core.messages import AIMessage
|
|
95
|
+
from langgraph.graph import END, START, StateGraph
|
|
96
|
+
|
|
97
|
+
from agentfuse import Breaker
|
|
98
|
+
from agentfuse.adapters.langgraph import AgentFuseCallbackHandler
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class State(TypedDict):
|
|
102
|
+
messages: list[object]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
builder = StateGraph(State)
|
|
106
|
+
builder.add_node("agent", lambda state: {"messages": [AIMessage(content="ok")]})
|
|
107
|
+
builder.add_edge(START, "agent")
|
|
108
|
+
builder.add_edge("agent", END)
|
|
109
|
+
graph = builder.compile()
|
|
110
|
+
|
|
111
|
+
breaker = Breaker(max_cost_usd=2.0)
|
|
112
|
+
handler = AgentFuseCallbackHandler(breaker)
|
|
113
|
+
|
|
114
|
+
result = graph.invoke(
|
|
115
|
+
{"messages": [("user", "Investigate the outage")]},
|
|
116
|
+
config={"callbacks": [handler]},
|
|
117
|
+
)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Behavior
|
|
121
|
+
|
|
122
|
+
| Signal | Threshold / Condition | Response |
|
|
123
|
+
| --- | --- | --- |
|
|
124
|
+
| **Soft budget warning** | `cost_usd >= max_cost_usd * soft_ratio` | Sets `breaker.degraded = True`; `@guard(..., fallback_model=...)` swaps to the cheaper fallback model |
|
|
125
|
+
| **Hard cost cap** | `cost_usd >= max_cost_usd` | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
126
|
+
| **Per-node token cap** | `node_tokens[node] > max_node_tokens` | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
127
|
+
| **Identical tool loop** | Same tool + args repeated `>= max_repeats` times in sliding `window` | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
128
|
+
| **Cyclic tool loop** | 2-call or 3-call sequence repeated 3x consecutively | Transitions to `OPEN`, invokes `on_trip(TripEvent)`, raises `CircuitOpen` |
|
|
129
|
+
| **Call while open** | `state == OPEN` and elapsed `< cooldown_s` | Immediately raises `CircuitOpen("circuit breaker is open")` before running the call |
|
|
130
|
+
| **Cooldown elapsed** | `state == OPEN` and elapsed `>= cooldown_s` | Transitions to `HALF_OPEN` and allows one probe call |
|
|
131
|
+
| **Half-open probe succeeds** | Probe call finishes without tripping | Transitions back to `CLOSED` and resets `LoopDetector` |
|
|
132
|
+
| **Half-open probe fails** | Probe call trips any guard | Reopens to `OPEN`, restarts cooldown, invokes `on_trip`, raises `CircuitOpen` |
|
|
133
|
+
|
|
134
|
+
## Example (Simulated Run)
|
|
135
|
+
|
|
136
|
+
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`:
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
uv run python examples/runaway_agent.py
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Simulated output (synthetic token counts, no real API calls or real billing savings):
|
|
143
|
+
|
|
144
|
+
```text
|
|
145
|
+
=== Runaway Agent Comparison (Simulated Run — No Real API Calls) ===
|
|
146
|
+
Unguarded (simulated) : stopped after 84 steps | simulated_cost=$10.0800 | reason=simulated spend cap ($10.00)
|
|
147
|
+
Guarded (simulated) : stopped after 4 steps | simulated_cost=$0.4800 | reason=loop detected: identical tool call repeated 4x
|
|
148
|
+
Simulated cost avoided: $9.6000 (based on synthetic token counts)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Limitations
|
|
152
|
+
|
|
153
|
+
- **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.
|
|
154
|
+
- **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.
|
|
155
|
+
- **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.
|
|
156
|
+
|
|
157
|
+
## Roadmap
|
|
158
|
+
|
|
159
|
+
- **Pre-call cost estimation:** Input-token counting and max-output reservation for a true pre-flight hard stop.
|
|
160
|
+
- **Fuzzy loop detection:** Similarity-based detection for near-duplicate tool arguments.
|
|
161
|
+
- **Distributed Redis state store:** Shared breaker budgets across multi-process and multi-worker deployments.
|
|
162
|
+
- **OpenTelemetry export:** Native spans, metrics, and trip events for observability pipelines.
|
|
163
|
+
|
|
164
|
+
## Development
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
# Install dependencies (including dev tools and adapter extras)
|
|
168
|
+
uv sync
|
|
169
|
+
|
|
170
|
+
# Run tests
|
|
171
|
+
uv run pytest -q
|
|
172
|
+
|
|
173
|
+
# Lint and format check
|
|
174
|
+
uv run ruff check .
|
|
175
|
+
uv run ruff format --check .
|
|
176
|
+
|
|
177
|
+
# Strict type checking
|
|
178
|
+
uv run mypy src
|
|
179
|
+
```
|