cost-tracker

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cost Tracker — LLM API Cost Monitoring

成本追踪器 — LLM API成本监控

Track and monitor API costs across multiple LLM providers with real-time budget alerts.
跨多个LLM服务商跟踪和监控API成本,支持实时预算警报。

Overview

概述

This skill provides:
  • Multi-Provider Tracking: Anthropic, OpenAI, Google, and custom providers
  • Real-Time Monitoring: Track costs as they happen
  • Budget Alerts: Get notified when approaching spending limits
  • Cost Attribution: Track costs per job, task, or project
  • Historical Reports: Generate spending reports and trends
  • Provider Comparison: Compare costs across different providers
本技能提供以下功能:
  • 多服务商追踪:支持Anthropic、OpenAI、Google及自定义服务商
  • 实时监控:实时跟踪成本消耗情况
  • 预算警报:当接近支出限额时收到通知
  • 成本归属:按作业、任务或项目追踪成本
  • 历史报告:生成支出报告及趋势分析
  • 服务商对比:对比不同服务商的成本差异

Pricing Configuration

定价配置

Configure provider pricing in
config/pricing.json
:
json
{
  "providers": {
    "anthropic": {
      "claude-sonnet-4-5-20250929": {
        "input": 0.000003,
        "output": 0.000015,
        "currency": "USD"
      },
      "claude-opus-4-0-20250514": {
        "input": 0.000015,
        "output": 0.000075,
        "currency": "USD"
      }
    },
    "openai": {
      "gpt-4o": {
        "input": 0.0000025,
        "output": 0.00001,
        "currency": "USD"
      },
      "gpt-4o-mini": {
        "input": 0.00000015,
        "output": 0.0000006,
        "currency": "USD"
      }
    },
    "google": {
      "gemini-2.0-flash": {
        "input": 0.0000001,
        "output": 0.0000004,
        "currency": "USD"
      },
      "gemini-2.0-pro": {
        "input": 0.00000125,
        "output": 0.000005,
        "currency": "USD"
      }
    }
  },
  "budgets": {
    "daily": 10.00,
    "weekly": 50.00,
    "monthly": 200.00
  },
  "alerts": {
    "thresholds": [0.5, 0.75, 0.9],
    "channels": ["telegram", "discord"]
  }
}
config/pricing.json
中配置服务商定价:
json
{
  "providers": {
    "anthropic": {
      "claude-sonnet-4-5-20250929": {
        "input": 0.000003,
        "output": 0.000015,
        "currency": "USD"
      },
      "claude-opus-4-0-20250514": {
        "input": 0.000015,
        "output": 0.000075,
        "currency": "USD"
      }
    },
    "openai": {
      "gpt-4o": {
        "input": 0.0000025,
        "output": 0.00001,
        "currency": "USD"
      },
      "gpt-4o-mini": {
        "input": 0.00000015,
        "output": 0.0000006,
        "currency": "USD"
      }
    },
    "google": {
      "gemini-2.0-flash": {
        "input": 0.0000001,
        "output": 0.0000004,
        "currency": "USD"
      },
      "gemini-2.0-pro": {
        "input": 0.00000125,
        "output": 0.000005,
        "currency": "USD"
      }
    }
  },
  "budgets": {
    "daily": 10.00,
    "weekly": 50.00,
    "monthly": 200.00
  },
  "alerts": {
    "thresholds": [0.5, 0.75, 0.9],
    "channels": ["telegram", "discord"]
  }
}

API

API

Track a Token Usage

跟踪令牌使用量

javascript
const { trackUsage } = require('./cost-tracker');

await trackUsage({
  provider: 'anthropic',
  model: 'claude-sonnet-4-5-20250929',
  input_tokens: 1500,
  output_tokens: 800,
  job_id: 'job-12345'
});

// Returns: { cost: 0.0165, currency: 'USD' }
javascript
const { trackUsage } = require('./cost-tracker');

await trackUsage({
  provider: 'anthropic',
  model: 'claude-sonnet-4-5-20250929',
  input_tokens: 1500,
  output_tokens: 800,
  job_id: 'job-12345'
});

// 返回: { cost: 0.0165, currency: 'USD' }

Get Current Spending

获取当前支出

javascript
const { getSpending } = require('./cost-tracker');

const spending = await getSpending('daily');
console.log(`Spent $${spending.amount} of $${spending.budget}`);
console.log(`Remaining: $${spending.remaining}`);
javascript
const { getSpending } = require('./cost-tracker');

const spending = await getSpending('daily');
console.log(`已支出 $${spending.amount} / 预算 $${spending.budget}`);
console.log(`剩余额度: $${spending.remaining}`);

Get Cost by Job

按作业查询成本

javascript
const { getJobCost } = require('./cost-tracker');

const jobCost = getJobCost('job-12345');
console.log(`Job cost: $${jobCost.total}`);
console.log(`Breakdown:`, jobCost.breakdown);
javascript
const { getJobCost } = require('./cost-tracker');

const jobCost = getJobCost('job-12345');
console.log(`作业成本: $${jobCost.total}`);
console.log(`明细:`, jobCost.breakdown);

Generate Report

生成报告

javascript
const { generateReport } = require('./cost-tracker');

const report = await generateReport({
  period: 'weekly',
  group_by: 'provider'
});
javascript
const { generateReport } = require('./cost-tracker');

const report = await generateReport({
  period: 'weekly',
  group_by: 'provider'
});

Budget Alerts

预算警报

Configure alerts at spending thresholds:
javascript
const { setAlert } = require('./cost-tracker');

setAlert({
  type: 'threshold',
  threshold: 0.8,  // Alert at 80% of budget
  channels: ['telegram', 'email'],
  message: 'Warning: 80% of monthly budget used!'
});
按支出阈值配置警报:
javascript
const { setAlert } = require('./cost-tracker');

setAlert({
  type: 'threshold',
  threshold: 0.8,  // 达到预算的80%时触发警报
  channels: ['telegram', 'email'],
  message: '警告:已使用月度预算的80%!'
});

Real-Time Dashboard

实时仪表盘

javascript
const { getDashboard } = require('./cost-tracker');

const dashboard = getDashboard();
console.log(dashboard);
// {
//   today: { spent: 2.45, budget: 10.00, remaining: 7.55 },
//   this_week: { spent: 18.30, budget: 50.00, remaining: 31.70 },
//   this_month: { spent: 89.50, budget: 200.00, remaining: 110.50 },
//   top_models: [...],
//   top_jobs: [...]
// }
javascript
const { getDashboard } = require('./cost-tracker');

const dashboard = getDashboard();
console.log(dashboard);
// {
//   today: { spent: 2.45, budget: 10.00, remaining: 7.55 },
//   this_week: { spent: 18.30, budget: 50.00, remaining: 31.70 },
//   this_month: { spent: 89.50, budget: 200.00, remaining: 110.50 },
//   top_models: [...],
//   top_jobs: [...]
// }

Cost Attribution

成本归属

Track costs by job, user, or project:
javascript
// Track with context
await trackUsage({
  provider: 'openai',
  model: 'gpt-4o',
  input_tokens: 2000,
  output_tokens: 500,
  job_id: 'job-12345',
  user_id: 'user-789',
  project: 'research-agent'
});

// Get costs by project
const projectCost = getCostByProject('research-agent');
按作业、用户或项目追踪成本:
javascript
// 携带上下文追踪
await trackUsage({
  provider: 'openai',
  model: 'gpt-4o',
  input_tokens: 2000,
  output_tokens: 500,
  job_id: 'job-12345',
  user_id: 'user-789',
  project: 'research-agent'
});

// 按项目查询成本
const projectCost = getCostByProject('research-agent');

CLI Usage

CLI 使用方法

bash
undefined
bash
undefined

Show current spending

查看当前支出状态

cost-tracker status
cost-tracker status

Show detailed dashboard

查看详细仪表盘

cost-tracker dashboard
cost-tracker dashboard

Show costs for a specific job

查看特定作业的成本

cost-tracker job --id job-12345
cost-tracker job --id job-12345

Generate monthly report

生成月度报告

cost-tracker report --period monthly
cost-tracker report --period monthly

Reset counters

重置统计计数器

cost-tracker reset --period daily
undefined
cost-tracker reset --period daily
undefined

Output Format

输出格式

Daily Status

每日状态

💰 Cost Tracker Status

Today (2026-02-25)
  Spent:     $2.45 / $10.00 (24.5%)
  Remaining: $7.55

This Week
  Spent:     $18.30 / $50.00 (36.6%)
  Remaining: $31.70

This Month
  Spent:     $89.50 / $200.00 (44.8%)
  Remaining: $110.50

Top Models (today):
  1. claude-sonnet-4-5: $1.20
  2. gpt-4o-mini: $0.85
  3. gemini-2.0-flash: $0.40
💰 成本追踪器状态

今日(2026-02-25)
  已支出:     $2.45 / $10.00 (24.5%)
  剩余额度: $7.55

本周
  已支出:     $18.30 / $50.00 (36.6%)
  剩余额度: $31.70

本月
  已支出:     $89.50 / $200.00 (44.8%)
  剩余额度: $110.50

今日热门模型:
  1. claude-sonnet-4-5: $1.20
  2. gpt-4o-mini: $0.85
  3. gemini-2.0-flash: $0.40

Best Practices

最佳实践

  1. Set Conservative Budgets: Start low and adjust based on usage patterns
  2. Monitor Daily: Check spending daily to catch unexpected spikes
  3. Attribute Costs: Always track job_id for cost attribution
  4. Alert Early: Set alerts at 50%, 75%, and 90% thresholds
  5. Review Weekly: Analyze weekly reports to optimize model usage
  1. 设置保守预算:初始预算设低一些,根据使用模式逐步调整
  2. 每日监控:每日查看支出情况,及时发现异常飙升
  3. 标注成本归属:始终跟踪job_id以实现成本归属
  4. 提前设置警报:在预算的50%、75%和90%阈值处设置警报
  5. 每周复盘:分析每周报告以优化模型使用

Integration with Agent

与Agent集成

javascript
// In agent code
const { trackUsage, shouldThrottle } = require('./cost-tracker');

async function callLLM(prompt, options) {
  // Check if we should throttle
  if (shouldThrottle()) {
    throw new Error('Cost limit reached. Throttling requests.');
  }
  
  // Make API call
  const response = await provider.complete(prompt, options);
  
  // Track usage
  await trackUsage({
    provider: options.provider,
    model: options.model,
    input_tokens: response.usage.prompt_tokens,
    output_tokens: response.usage.completion_tokens,
    job_id: options.job_id
  });
  
  return response;
}
javascript
// 在Agent代码中
const { trackUsage, shouldThrottle } = require('./cost-tracker');

async function callLLM(prompt, options) {
  // 检查是否需要限流
  if (shouldThrottle()) {
    throw new Error('已达到成本限额,正在限制请求。');
  }
  
  // 调用API
  const response = await provider.complete(prompt, options);
  
  // 跟踪使用量
  await trackUsage({
    provider: options.provider,
    model: options.model,
    input_tokens: response.usage.prompt_tokens,
    output_tokens: response.usage.completion_tokens,
    job_id: options.job_id
  });
  
  return response;
}

Cost Estimation

成本估算

Estimate costs before making expensive calls:
javascript
const { estimateCost } = require('./cost-tracker');

const estimate = estimateCost({
  provider: 'anthropic',
  model: 'claude-opus-4-0-20250514',
  estimated_input: 10000,
  estimated_output: 2000
});

console.log(`Estimated cost: $${estimate.cost}`);
// Estimated cost: $0.30
在进行高成本调用前估算成本:
javascript
const { estimateCost } = require('./cost-tracker');

const estimate = estimateCost({
  provider: 'anthropic',
  model: 'claude-opus-4-0-20250514',
  estimated_input: 10000,
  estimated_output: 2000
});

console.log(`估算成本: $${estimate.cost}`);
// 估算成本: $0.30

Export Data

数据导出

Export spending data for analysis:
javascript
const { exportData } = require('./cost-tracker');

const csv = await exportData({
  format: 'csv',
  period: 'monthly',
  columns: ['timestamp', 'provider', 'model', 'input_tokens', 'output_tokens', 'cost', 'job_id']
});

fs.writeFileSync('spending-report.csv', csv);
导出支出数据用于分析:
javascript
const { exportData } = require('./cost-tracker');

const csv = await exportData({
  format: 'csv',
  period: 'monthly',
  columns: ['timestamp', 'provider', 'model', 'input_tokens', 'output_tokens', 'cost', 'job_id']
});

fs.writeFileSync('spending-report.csv', csv);