← 返回
未分类 Key 中文

Anthropic Usage

Query Anthropic Admin API for token usage reports (daily, weekly, monthly) with model breakdown. Requires an Anthropic Organization account. Configure your A...
## 查询 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 格式 |
leaofelipe leaofelipe 来源
未分类 clawhub v1.0.7 1 版本 100000 Key: 需要
★ 1
Stars
📥 464
下载
💾 6
安装
1
版本
#latest

概述

anthropic-usage

You are helping the user query their Anthropic token usage via the Admin API.

Before running anything

Check whether the API key is available:

[[ -n "${ANTHROPIC_ADMIN_API_KEY:-}" ]] && echo "KEY_EXISTS" || echo "KEY_MISSING"
  • If the output is KEY_MISSING: stop and guide the user through setup. Do NOT proceed until the variable is set.
  • If the output is KEY_EXISTS: proceed.

Setup guidance (show this when KEY_MISSING)

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:

{
  "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.

Running the usage script

Once the key exists, run scripts/usage.sh with the appropriate flags based on what the user asked for:

User intentCommand
------
Today's usagebash scripts/usage.sh --daily
This weekbash scripts/usage.sh --weekly
This monthbash scripts/usage.sh --monthly
Breakdown by modelbash scripts/usage.sh --breakdown
Weekly + model breakdownbash scripts/usage.sh --weekly --breakdown
Monthly + 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.

Formatting the output

After the script runs:

  1. Present the data as a friendly chat message, not a raw dump.
  2. Summarize the key numbers at the top (total input tokens, total output tokens).
  3. If --breakdown was used, render the per-model table in a readable way.
  4. Estimate the cost (agent-side step): The script returns token counts only — pricing is not included. After presenting the token data, use your 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.
  5. If the script exits with an error (non-zero exit code), show the error message and suggest fixes:
    • Exit 1 / "key file not found" → re-show setup guidance
    • "401 Unauthorized" → key is invalid or expired
    • "403 Forbidden" → key lacks Admin permissions or account is not on an Organization plan
    • Network error → ask the user to check their internet connection

Example friendly output

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.

版本历史

共 1 个版本

  • v1.0.7 当前
    2026-03-30 19:39 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

ai-agent

Todoist CLI Skill

leaofelipe
使用官方 Todoist CLI 工具(https://github.com/Doist/todoist-cli)管理 Todoist 中的任务和项目。当用户询问任务、待办、提醒等内容时使用。
★ 1 📥 705
data-analysis

Tavily 搜索

jacky1n7
通过 Tavily API 进行网页搜索(Brave 替代方案)。当用户要求搜索网页、查找来源或链接,且 Brave 网页搜索不可用时使用。
★ 273 📥 100,356
data-analysis

Data Analysis

ivangdavila
{"answer":"数据分析与可视化。查询数据库、生成报告、自动化电子表格,将原始数据转化为清晰可行的见解。适用于:(1) 您……"}
★ 208 📥 68,642