Install
openclaw skills install cost-controlPrevent runaway API costs with 3-tier protection: caution, emergency, and hard cap. Works for ANY expensive API GPT-4, Claude Opus, Gemini, cloud services.
openclaw skills install cost-controlPrevent runaway API costs with 3-tier protection: caution, emergency, and hard cap. Works for ANY expensive API GPT-4, Claude Opus, Gemini, cloud services.
Cost Control System is a production-grade cost monitoring framework with tiered responses, external watchdog, and kill switch.
Originally built to prevent catastrophic AI API spend after a real runaway cost incident, now generalized for any expensive API that charges per request/token/compute.
You're running a system that makes API calls to an expensive service (OpenAI GPT-4, Anthropic Claude Opus, Google Gemini, cloud compute, etc.).
One bug, one infinite loop, one configuration error → hundreds of dollars burned in minutes.
Manual monitoring doesn't work. You need automated cost controls with failsafes.
Cost Control System implements 3-tier protection:
When cost velocity exceeds threshold (e.g., $3/15min):
When cost velocity is dangerous (e.g., $5/15min):
Independent process monitors cost separately:
pip install cost-control-system
# OR copy cost_control.py to your project
from cost_control import CostTracker
tracker = CostTracker(
cost_caution_15min=3.00, # Warning at $3/15min
cost_emergency_15min=5.00, # Emergency at $5/15min
cost_daily_cap=25.00, # Hard cap at $25/day
)
# Before each API call, check if allowed
allowed, reason = tracker.is_call_allowed()
if not allowed:
print(f"API call blocked: {reason}")
# Handle emergency mode (alert, exit, etc.)
return
# Make your API call
response = your_expensive_api_call()
# Record actual cost
input_tokens = response.usage.input_tokens
output_tokens = response.usage.output_tokens
tracker.record_call(input_tokens, output_tokens, request_id="req-123")
# Run external watchdog every 2 minutes (via cron)
*/2 * * * * cd /your/project && python3 cost_watchdog.py >> logs/watchdog.log 2>&1
Time to integrate: 15-20 minutes.
Prevent runaway token usage from:
Monitor spend on:
Track costs for:
Control costs for:
Any API with measurable per-request or per-unit costs benefits from this.
Normal → Caution (Tier 1) → Emergency (Tier 2) → Kill (Tier 3)
↓ ↓ ↓ ↓
OK Slow down Stop calls Kill process
Trigger: 15-minute cost > $3 (configurable)
Response:
Exit: 15-minute cost < $2 for 5 minutes
Trigger: 15-minute cost > $5 OR daily cost > $25 (configurable)
Response:
is_call_allowed() returns False)Exit: Manual intervention required (rm state/cost_emergency.flag)
Trigger: Hourly cost > $12 OR daily cost > $30 (configurable, higher than Tier 2)
Response:
Purpose: Catch cases where Tier 2 fails (e.g., bug in cost tracker itself)
from cost_control import CostTracker
tracker = CostTracker(
# Tier 1 (Caution)
cost_caution_15min=3.00,
# Tier 2 (Emergency)
cost_emergency_15min=5.00,
cost_daily_cap=25.00,
# State persistence
state_dir="./state",
)
tracker = CostTracker(
# Thresholds
cost_caution_15min=3.00,
cost_emergency_15min=5.00,
cost_daily_cap=25.00,
max_cost_per_call=0.50, # Single-call sanity check
# Recovery
caution_recovery_threshold=2.00, # Exit caution when <$2/15min
caution_recovery_duration=300, # Must stay below for 5 min
# State
state_dir="./state",
cost_log_file="cost_log.jsonl",
# Alerting
alert_callback=my_alert_function,
)
# Define your API's pricing
tracker.set_pricing(
input_price_per_unit=15.00, # e.g., $15 per million input tokens
output_price_per_unit=75.00, # e.g., $75 per million output tokens
unit_size=1_000_000, # e.g., per million tokens
)
# For non-token APIs (e.g., per-request pricing):
tracker.set_pricing(
fixed_cost_per_call=0.01, # $0.01 per API call
)
See config_example.py for complete examples.
record_call(input_units, output_units, request_id=None)Record an API call with actual usage.
Args:
input_units (int): Input units consumed (e.g., tokens, requests)output_units (int): Output units consumedrequest_id (str, optional): Identifier for loggingReturns: True if within limits, False if emergency triggered
is_call_allowed()Check if API calls are currently allowed.
Returns: (allowed: bool, reason: str)
allowed=True, reason="ok" → Safe to call APIallowed=False, reason="cost_emergency_mode" → BlockedUsage:
allowed, reason = tracker.is_call_allowed()
if not allowed:
handle_emergency(reason)
return
get_stats()Get current cost statistics.
Returns: Dict with keys:
{
"cost_5min": 0.45,
"cost_15min": 1.23,
"cost_1hour": 3.45,
"cost_daily": 12.34,
"calls_1hour": 23,
"calls_session": 156,
"caution_mode": False,
"emergency_mode": False,
}
clear_emergency()Clear emergency mode (manual intervention).
Usage:
tracker.clear_emergency()
# Or: rm state/cost_emergency.flag
caution_mode (bool) — Whether in Tier 1 cautionemergency_mode (bool) — Whether in Tier 2 emergencycost_15min (float) — Rolling 15-minute costcost_daily (float) — Total cost today (UTC)cp cost_watchdog.py /your/project/
Edit cost_watchdog.py:
KILL_THRESHOLD_HOURLY = 12.00 # $12/hour (higher than Tier 2)
KILL_THRESHOLD_DAILY = 30.00 # $30/day (higher than Tier 2)
crontab -e
# Add this line (run every 2 minutes)
*/2 * * * * cd /your/project && python3 cost_watchdog.py >> logs/watchdog.log 2>&1
tail -f logs/watchdog.log
# Should see entries every 2 minutes
python3 kill_switch.py enable
# Stops all API calls immediately
python3 kill_switch.py status
python3 kill_switch.py disable
rm state/cost_emergency.flag # Clear emergency flag
# Restart your application
pytest tests/test_cost_control.py
from cost_control import CostTracker
tracker = CostTracker(
cost_emergency_15min=1.00, # Low threshold for testing
)
# Simulate 50 expensive calls
for i in range(50):
allowed, reason = tracker.is_call_allowed()
if not allowed:
print(f"Blocked after {i} calls: {reason}")
break
# Simulate $0.10 per call
tracker.record_call(10000, 50000, request_id=f"test-{i}")
# Should trigger emergency after ~10 calls
# Verify emergency mode
assert tracker.emergency_mode
print("✅ Emergency mode triggered successfully")
See LIMITATIONS.md for details, including:
Cause: Clock skew — system time doesn't match API billing time
Fix: Sync system clock with NTP (ntpdate or chrony)
Cause: Cron not running or watchdog script errors
Fix: Check cron logs (/var/log/syslog), verify script permissions
Cause: Threshold too low for your use case
Fix: Raise cost_caution_15min to match normal usage peaks
What happened:
How Cost Control would have stopped it:
Result: Max damage $5-8 instead of $150+
cost_caution_15min = 2x baseline peakcost_emergency_15min = 3x baseline peakcost_daily_cap = acceptable daily budgetCost Control System is open source and community-maintained.
Contribution guidelines: Open an issue or PR on GitHub. We review everything.
Cost Control solves a universal infrastructure problem — preventing runaway API spend. This affects everyone building on paid APIs.
This is a goodwill project to:
Cost Control is free, but if it saved you money:
☕ Ko-fi: https://ko-fi.com/theshadowrose
Donations support ongoing testing, docs, and new features.
MIT License — use freely, credit appreciated.
Copyright © 2026 Shadow Rose
See LICENSE for details.
Want to work on these? Open an issue or reach out on Discord.
Created by: Shadow Rose
Extracted from: Production trading bot (battle-tested in live operation)
Philosophy: Vibe coding — infrastructure that protects itself
License: MIT
Built from a real runaway cost incident — learned the hard way so you don't have to.
Every system that calls expensive APIs will eventually have a runaway cost incident.
The question is: does your system detect and stop it in 5 minutes, or do you find out when the $1000 bill arrives?
Cost Control ensures you find out in 5 minutes.
Ship it. Break it. Tell us what you find.
— Shadow Rose
February 2026
☕ Support: https://ko-fi.com/theshadowrose
🐦 Follow: https://x.com/TheShadowyRose
💬 Community: https://discord.com/invite/clawd
This software is provided "AS IS", without warranty of any kind, express or implied.
USE AT YOUR OWN RISK.
By downloading, installing, or using this software, you acknowledge that you have read this disclaimer and agree to use the software entirely at your own risk.
| 🐛 Bug Reports | TheShadowyRose@proton.me |
| ☕ Ko-fi | ko-fi.com/theshadowrose |
| 🛒 Gumroad | shadowyrose.gumroad.com |
| @TheShadowyRose | |
| 🐙 GitHub | github.com/TheShadowRose |
| 🧠 PromptBase | promptbase.com/profile/shadowrose |
Built with OpenClaw — thank you for making this possible.
🛠️ Need something custom? Custom OpenClaw agents & skills starting at $500. If you can describe it, I can build it. → Hire me on Fiverr