A lightweight circuit breaker for AI Agents to prevent infinite loops
一个轻量级的 AI Agent 循环检测和熔断库,防止陷入死循环
- 🛡️ Decorator Pattern - Add loop detection with a single line of code | 装饰器模式 - 一行代码添加循环检测
- 🔍 Smart Detection - Uses sliding window + MD5 fingerprint to detect repeated operations | 智能检测 - 使用滚动窗口 + MD5 哈希指纹检测重复操作
- 🚨 Visual Warnings - Rich terminal UI with red alerts and loop history | 可视化警告 - 使用 rich 库显示红色警告和循环历史
- 💾 Auto Logging - Automatically saves logs to
.loop-fuse-logs/on circuit break | 自动日志 - 熔断时自动保存日志 - 💰 Cost Estimation - Shows saved API call costs | 成本估算 - 显示节省的 API 调用成本
- 🔧 Custom Callbacks - Support for custom circuit break handlers | 自定义回调 - 支持自定义熔断处理逻辑
pip install "git+https://github.com/PerryLink/Loop-Fuse.git"
# (PyPI 未发布,源码直装)from loop_fuse import loop_fuse
@loop_fuse(window_size=5, threshold=3)
def agent_loop(action):
print(f"Executing: {action}")
return f"Completed: {action}"
# Simulate infinite loop | 模拟死循环
actions = ["search weather", "search news", "search news", "search news"]
for action in actions:
agent_loop(action) # Will trigger circuit break on 4th call | 第 4 次会触发熔断@loop_fuse(window_size=5, threshold=3)
def agent_loop(action):
# Your agent logic here
pass@loop_fuse(threshold=3, cost_per_call=0.01)
def expensive_agent_call(query):
# Expensive API call (e.g., GPT-4)
passdef my_callback(history, fingerprint, cost_saved):
# Custom handling logic
print(f"Saved cost: ${cost_saved:.4f}")
@loop_fuse(threshold=3, on_loop_detected=my_callback)
def agent_loop(action):
passwindow_size(int): Sliding window size, default 5 | 滚动窗口大小,默认 5threshold(int): Repetition threshold, default 3 | 重复次数阈值,默认 3cost_per_call(float): Cost per call in USD, default 0.0 | 每次调用成本(美元),默认 0.0on_loop_detected(Callable): Custom circuit break callback | 自定义熔断回调函数
loop-fuse/
├── src/loop_fuse/
│ ├── __init__.py # Public API
│ ├── core.py # Core LoopFuse class
│ ├── decorators.py # @loop_fuse decorator
│ ├── fingerprint.py # MD5 fingerprint generation
│ ├── exceptions.py # LoopDetectedError exception
│ ├── logger.py # JSON log saving
│ └── ui.py # Rich visual output
├── examples/
│ ├── basic_usage.py # Basic usage example
│ ├── with_callback.py # Custom callback example
│ └── cost_estimation.py # Cost estimation example
├── tests/
│ ├── test_core.py # Core logic tests
│ ├── test_decorators.py # Decorator tests
│ └── test_fingerprint.py # Fingerprint generation tests
├── README.md
├── LICENSE
├── CONTRIBUTING.md
└── pyproject.toml
- Uses a sliding window to record the last N operations | 使用滚动窗口记录最近 N 次操作
- Generates MD5 hash fingerprint for each operation | 为每次操作生成 MD5 哈希指纹
- Detects if repetition count within window exceeds threshold | 检测窗口内重复次数是否达到阈值
- Triggers circuit break: displays warning + saves log + raises exception | 触发熔断:显示警告 + 保存日志 + 抛出异常
- Python 3.8+ - Base runtime environment | 基础运行环境
- rich - Terminal visualization | 终端可视化输出
- hashlib - MD5 hash generation (built-in) | MD5 哈希生成(内置库)
- pytest - Unit testing framework | 单元测试框架
- pytest-cov - Test coverage | 测试覆盖率
pip install -e ".[dev]"pytest tests/ -v --cov=src/loop_fusepython examples/basic_usage.py
python examples/with_callback.py
python examples/cost_estimation.pySee CONTRIBUTING.md for contribution guidelines.
查看 CONTRIBUTING.md 了解贡献指南。
Apache License 2.0
Copyright 2026 Chance Dean ([email protected])
See LICENSE file for details.
查看 LICENSE 文件了解详情。
Chance Dean (@PerryLink)
- Email: [email protected]
- GitHub: https://github.com/PerryLink
Built with ❤️ to help AI developers avoid infinite loops and save API costs.
用 ❤️ 构建,帮助 AI 开发者避免死循环并节省 API 成本。