Token Usage Tracker

v1.0.0

Token 使用追踪系统。记录每个对话的输入/输出 token 消耗,累计统计,预算控制。 当用户说"token统计"、"用量追踪"、"消耗了多少"、"花了我多少token"时触发。

0· 136·0 current·0 all-time

Install

OpenClaw Prompt Flow

Install with OpenClaw

Best for remote or guided setup. Copy the exact prompt, then paste it into OpenClaw for xhmqq616/token-usage-tracker.

Previewing Install & Setup.
Prompt PreviewInstall & Setup
Install the skill "Token Usage Tracker" (xhmqq616/token-usage-tracker) from ClawHub.
Skill page: https://clawhub.ai/xhmqq616/token-usage-tracker
Keep the work scoped to this skill only.
After install, inspect the skill metadata and help me finish setup.
Use only the metadata you can verify from ClawHub; do not invent missing requirements.
Ask before making any broader environment changes.

Command Line

CLI Commands

Use the direct CLI path if you want to install manually and keep every step visible.

OpenClaw CLI

Bare skill slug

openclaw skills install token-usage-tracker

ClawHub CLI

Package manager switcher

npx clawhub@latest install token-usage-tracker
Security Scan
VirusTotalVirusTotal
Benign
View report →
OpenClawOpenClaw
Benign
high confidence
Purpose & Capability
The name/description (token usage tracking, budgeting) matches the code and SKILL.md: functions to estimate tokens, record turns, compute stats, check budgets, and export history are implemented. No unrelated credentials or binaries are requested.
Instruction Scope
SKILL.md shows example usage and describes storing prompts in the TurnUsage interface, but the implementation only records numeric token counts (it does not persist raw prompt/response text). Also the README example uses require(...) (CommonJS) while the shipped file is an ES module (.mjs with export), so the import example is incorrect — callers must use import or adjust usage. Aside from these doc mismatches, the instructions do not ask the agent to read unrelated system files or exfiltrate data.
Install Mechanism
There is no install spec and no downloads; this is an instruction + code-only skill with no external install artifacts. That minimizes supply-chain risk.
Credentials
The skill does not request environment variables, credentials, or config paths. Its behavior (local counting and budgeting) does not require secrets, so the lack of required env vars is appropriate.
Persistence & Privilege
The tracker persists data to disk by default (storagePath defaults to './.usage-tracker.json'). This is reasonable for a usage tracker, but users should be aware it writes a JSON file in the current working directory (or whatever storagePath is provided). No evidence of attempts to modify other skills or system-wide settings; always:false and no elevated privileges are requested.
Assessment
This skill looks coherent and locally scoped, but check two small issues before installing: (1) the SKILL.md import example uses require(...) while the file is an ES module — import it with ESM syntax or adapt as needed; (2) the README implies prompts might be recorded but the code only stores numeric token counts (it does not persist raw prompt/response text). Also note the tracker writes a JSON file by default at ./ .usage-tracker.json — if that location is sensitive, set storagePath to a secure directory with appropriate permissions. If you need the skill to keep no disk traces, do not enable it or pass a temporary in-memory path. Otherwise it is internally consistent and does not request secrets or network access.

Like a lobster shell, security has layers — review code before you run it.

budgetvk973eqcs1v0z0n77pdd6ae9zth84arn2costvk973eqcs1v0z0n77pdd6ae9zth84arn2latestvk973eqcs1v0z0n77pdd6ae9zth84arn2tokenvk973eqcs1v0z0n77pdd6ae9zth84arn2trackingvk973eqcs1v0z0n77pdd6ae9zth84arn2usagevk973eqcs1v0z0n77pdd6ae9zth84arn2
136downloads
0stars
1versions
Updated 3w ago
v1.0.0
MIT-0

Usage Tracker - Token 使用追踪系统

核心概念

对话轮次 → 记录 usage → 累计统计 → 预算检查 → 超限警告

数据结构

interface TokenUsage {
  input_tokens: number;
  output_tokens: number;
  cache_creation_input_tokens?: number;  // 缓存创建
  cache_read_input_tokens?: number;     // 缓存读取
}

interface TurnUsage {
  turn: number;
  prompt: string;
  usage: TokenUsage;
  timestamp: string;
}

interface UsageBudget {
  maxInputTokens: number;
  maxOutputTokens: number;
  maxTotalTokens: number;
  warningThreshold: number;  // 80%
}

追踪指标

指标说明
input_tokens输入 token 数
output_tokens输出 token 数
total_tokens总 token 数
cache_creation缓存创建消耗
cache_read缓存读取节省
turn_count对话轮次
cost_estimate费用估算

API 使用

const { UsageTracker } = require('./scripts/usage-tracker.mjs');

const tracker = new UsageTracker({
  maxTotalTokens: 100000,
  warningThreshold: 0.8
});

// 记录一次使用
tracker.record({
  input_tokens: 500,
  output_tokens: 200,
});

// 获取统计
const stats = tracker.getStats();
console.log(stats);
// {
//   totalInput: 1500,
//   totalOutput: 600,
//   totalTokens: 2100,
//   turnCount: 3,
//   avgInputPerTurn: 500,
//   avgOutputPerTurn: 200,
//   budgetUsedPercent: 2.1,
//   estimatedCost: 0.042
// }

// 检查是否超预算
const budget = tracker.checkBudget();
if (budget.exceeded) {
  console.log(`⚠️ 超出预算 ${budget.percent}%`);
}

// 获取历史
const history = tracker.getHistory();

Token 估算(无需 API)

// 简单估算(中英文都适用)
function estimateTokens(text) {
  // 中文约 1 token / 字符
  // 英文约 1 token / 4 字符
  const chineseChars = (text.match(/[\u4e00-\u9fff]/g) || []).length;
  const otherChars = text.length - chineseChars;
  return chineseChars + Math.ceil(otherChars / 4);
}

费用估算

基于 Claude API 定价(仅供参考):

模型输入输出
Claude 3.5 Sonnet$3/1M$15/1M
Claude 3 Opus$15/1M$75/1M
Claude 3 Haiku$0.25/1M$1.25/1M

预算控制

const tracker = new UsageTracker({
  maxTotalTokens: 50000,
  maxTurns: 20,
  onBudgetExceeded: (stats) => {
    console.log('⚠️ 预算超出!');
    console.log(`已用: ${stats.totalTokens} / ${stats.maxTotal}`);
  }
});

文件结构

usage-tracker/
├── SKILL.md              # 本文件
└── scripts/
    └── usage-tracker.mjs # 核心实现

龙虾王子自我进化的成果 🦞

Comments

Loading comments...