# This Week in Claude, 30 October 2026: what each Claude API key cost you in the last 7 days.
# Needs: pip install --upgrade anthropic, and an Admin API key in ANTHROPIC_ADMIN_KEY.
# Uses the Usage and Cost Analytics API (beta, 29 October 2026).
import os
from datetime import datetime, timedelta, timezone

import anthropic

# Name your keys so the report reads like your business. The first run prints the IDs to copy here.
KEY_NAMES = {
    "apikey_REPLACE_ME": "n8n inbox triage",
    "apikey_REPLACE_ME_TOO": "Make invoice reader",
}

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_ADMIN_KEY"])
end = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
start = end - timedelta(days=7)

totals = {}
for row in client.beta.organization.analytics.cost.list(
    starting_at=start.strftime("%Y-%m-%dT%H:%M:%SZ"),
    ending_at=end.strftime("%Y-%m-%dT%H:%M:%SZ"),
    group_by=["api_key_id"],
):
    key = row.group.api_key_id or "(no key)"
    totals[key] = totals.get(key, 0.0) + float(row.cost.amount) / 100  # amount is in cents

print(f"Claude API spend, {start:%d %b} to {end:%d %b} (USD, before credits)")
for key, usd in sorted(totals.items(), key=lambda kv: -kv[1]):
    print(f"  {KEY_NAMES.get(key, key):<32} ${usd:,.2f}")
print(f"  {'Total':<32} ${sum(totals.values()):,.2f}")
