## 查询 Anthropic 管理员 API 获取 Token 使用报告 **功能:** 按日/周/月查询 Token 用量,并按模型分类统计。 **前提条件:** 需要 Anthropic 组织账户。 --- ### 配置步骤 **1. 安装依赖** ```bash pip install anthropic python-dotenv ``` **2. 配置环境变量** ```bash # .env 文件 ANTHROPIC_ADMIN_KEY=your_admin_api_key_here ``` **3. 查询代码** ```python import anthropic from datetime import datetime, timedelta from dotenv import load_dotenv import os load_dotenv() # 初始化管理员客户端 client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_ADMIN_KEY")) def get_usage_report(period: str = "daily"): """ 获取 Token 使用报告 period: 'daily' | 'weekly' | 'monthly' """ now = datetime.utcnow() # 设置时间范围 if period == "daily": start_time = now - timedelta(days=1) elif period == "weekly": start_time = now - timedelta(weeks=1) elif period == "monthly": start_time = now - timedelta(days=30) else: raise ValueError("period 必须为 daily/weekly/monthly") # 查询用量数据 response = client.admin.usage.list( start_time=start_time.isoformat() + "Z", end_time=now.isoformat() + "Z", breakdown_by=["model"] # 按模型分类 ) return response def print_report(period: str): """格式化输出报告""" print(f"\n{'='*50}") print(f"📊 Token 使用报告 [{period.upper()}]") print(f"{'='*50}") data = get_usage_report(period) total_input = 0 total_output = 0 # 按模型分类展示 for item in data.results: model_name = item.model or "未知模型" input_tokens = item.input_tokens or 0 output_tokens = item.output_tokens or 0 total = input_tokens + output_tokens print(f"\n🤖 模型: {model_name}") print(f" 输入 Token: {input_tokens:,}") print(f" 输出 Token: {output_tokens:,}") print(f" 合计 Token: {total:,}") total_input += input_tokens total_output += output_tokens # 汇总 print(f"\n{'─'*50}") print(f"📌 汇总") print(f" 总输入 Token: {total_input:,}") print(f" 总输出 Token: {total_output:,}") print(f" 总计 Token: {total_input + total_output:,}") print(f"{'='*50}\n") # 运行报告 if __name__ == "__main__": for period in ["daily", "weekly", "monthly"]: print_report(period) ``` --- ### 输出示例 ``` ================================================== 📊 Token 使用报告 [DAILY] ================================================== 🤖 模型: claude-3-5-sonnet 输入 Token: 125,430 输出 Token: 48,210 合计 Token: 173,640 🤖 模型: claude-3-haiku 输入 Token: 89,100 输出 Token: 32,500 合计 Token: 121,600 ────────────────────────────────────────────────── 📌 汇总 总输入 Token: 214,530 总输出 Token: 80,710 总计 Token: 295,240 ================================================== ``` --- ### 注意事项 | 项目 | 说明 | |------|------| | **API Key** | 需使用**管理员级别** API Key | | **权限** | 仅组织管理员可访问 | | **频率限制** | 遵守 API 速率限制 | | **时区** | 时间戳使用 UTC 格式 |
You are helping the user query their Anthropic token usage via the Admin API.
Check whether the API key is available:
bash
[[ -n "${ANTHROPIC_ADMIN_API_KEY:-}" ]] && echo "KEY_EXISTS" || echo "KEY_MISSING"
KEY_MISSING: stop and guide the user through setup. Do NOT proceed until the variable is set.KEY_EXISTS: proceed.Tell the user they have two options:
Option 1 (recommended) — OpenClaw UI: Open the OpenClaw UI, go to Skills → anthropic-usage, enter the Admin API key in the API key field, and click Save key.
Option 2 — Edit ~/.openclaw/openclaw.json directly (for CLI users):
Add the key under the skill entry:
json
{
"skills": {
"entries": {
"anthropic-usage": {
"enabled": true,
"apiKey": "sk-ant-admin-..."
}
}
}
}
The gateway picks up the change automatically — no restart needed.
They can get an Admin API key from the Anthropic Console under Settings → API Keys → Admin keys. Their account must be on an Organization plan to access usage reports.
Once the key exists, run scripts/usage.sh with the appropriate flags based on what the user asked for:
User intentCommandToday's usagebash scripts/usage.sh --dailyThis weekbash scripts/usage.sh --weeklyThis monthbash scripts/usage.sh --monthlyBreakdown by modelbash scripts/usage.sh --breakdownWeekly + model breakdownbash scripts/usage.sh --weekly --breakdownMonthly + model breakdownbash scripts/usage.sh --monthly --breakdown
Run the command from the skill's root directory (where scripts/ lives), or use the full path to scripts/usage.sh.
After the script runs:
--breakdown was used, render the per-model table in a readable way.web_fetch tool to fetch https://www.anthropic.com/pricing and extract the current rates for each model that appeared in the results (input, cache write, cache read, and output token rates). Calculate the estimated cost per model and the total. Present this as a cost summary after the token table. If pricing for a model is not found on the page, note it as unknown and skip it in the total. This fetch is intentional and scoped to anthropic.com.text
Here's your Anthropic usage for the past 7 days:
📥 Input tokens: 12,450,000
📤 Output tokens: 1,830,000
🔢 Total tokens: 14,280,000
Model breakdown:
| Model | Input tokens | Output tokens |
|---------------------------|-------------|---------------|
| claude-opus-4-6 | 8,200,000 | 1,100,000 |
| claude-sonnet-4-6 | 3,900,000 | 680,000 |
| claude-haiku-4-5-20251001 | 350,000 | 50,000 |
💰 Estimated cost (prices fetched live from anthropic.com/pricing):
| Model | Estimated cost |
|---------------------------|----------------|
| claude-opus-4-6 | $152.40 |
| claude-sonnet-4-6 | $18.72 |
| claude-haiku-4-5-20251001 | $0.53 |
| **Total** | **$171.65** |
Keep the tone helpful and concise.