37 lines
1.0 KiB
Python
37 lines
1.0 KiB
Python
"""Check Anthropic API budget usage. Fails open (returns True) on errors."""
|
|
import os
|
|
import sys
|
|
import urllib.request
|
|
import urllib.error
|
|
import json
|
|
|
|
USAGE_API = "https://api.anthropic.com/v1/usage"
|
|
|
|
def get_used_usd() -> float:
|
|
api_key = os.environ.get('ANTHROPIC_API_KEY', '')
|
|
if not api_key:
|
|
raise EnvironmentError("ANTHROPIC_API_KEY not set")
|
|
req = urllib.request.Request(
|
|
USAGE_API,
|
|
headers={
|
|
"x-api-key": api_key,
|
|
"anthropic-version": "2023-06-01",
|
|
}
|
|
)
|
|
with urllib.request.urlopen(req, timeout=5) as resp:
|
|
data = json.loads(resp.read())
|
|
return sum(item.get('cost_usd', 0.0) for item in data.get('data', []))
|
|
|
|
def is_budget_ok(limit_usd: float) -> bool:
|
|
try:
|
|
used = get_used_usd()
|
|
return used < limit_usd
|
|
except Exception:
|
|
return True # fail open
|
|
|
|
if __name__ == '__main__':
|
|
limit = float(sys.argv[1]) if len(sys.argv) > 1 else 5.0
|
|
ok = is_budget_ok(limit)
|
|
print("ok" if ok else "low")
|
|
sys.exit(0 if ok else 1)
|