Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

llm-cost-optimizer

БесплатноБез исполняемых скриптовНе проверен

Cuts LLM API spend by measuring cost per feature and user, routing easy requests to cheaper models, using provider prompt caching, adding a semantic response…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

LLM Cost Optimizer

Overview

LLM bills grow with traffic, prompt length and model tier. Work in this order: measure, cache the stable prefix, move easy work to a cheaper model, defer non-urgent work to batch, then add a response cache. Prices and model IDs change often; the figures below are from the vendors' pricing pages on 2026-10-24 and belong in a config file you update, not in code you forget.

Checked facts that matter for the code below:

  • Anthropic (platform.claude.com pricing): claude-sonnet-5-5 $2 input / $10 output per million tokens (MTok), cache reads $0.10, 5-minute cache writes $2.50; claude-haiku-5-5 $0.10 / $0.50 for prompts up to 100,000 tokens (higher above that), cache reads $0.01, writes $0.125. Cache writes cost 1.25x (5 min) or 2x (1 h) base input; reads cost 0.1x on most models and 0.05x on Sonnet 5.5 and Opus 5.5. The Batch API is 50% off input and output.
  • Anthropic usage fields: input_tokens counts only tokens after the last cache breakpoint. Total input is cache_read_input_tokens + cache_creation_input_tokens + input_tokens.
  • Anthropic minimum cacheable prompt: 512 tokens for the 5.x models above, 1,024 for Sonnet 5, 4,096 for Haiku 4.5. Shorter prompts are processed uncached with no error; both cache fields read 0.
  • OpenAI (developers.openai.com pricing): gpt-6-luna $0.10 / $0.50 per MTok (cached input $0.01), gpt-6.1-sol $2 / $10 (cached $0.10). gpt-4o, gpt-4o-mini, gpt-4.1 and gpt-4.1-mini snapshots are on the deprecation list with removal on 2027-01-14 (suggested replacement gpt-6-luna). OpenAI's Batch API is 50% cheaper with a 24-hour completion window. OpenAI caches automatically, but on GPT-5.6 and later (including both models above) a cache write costs 1.25x the input price for the default 30-minute lifetime (2.5x for 12h), so cached input is billed as write, read or plain input. The prices above are the short-context rates; input over the long-context threshold costs about double.
  • Retired Anthropic IDs that old code still uses: claude-sonnet-4-20250514, claude-opus-4-20250514 (both retired 2026-06-15), claude-3-5-haiku-20241022, claude-3-haiku-20240307. claude-sonnet-4-5-20250929 retires 2026-11-30.

Instructions

Strategy 1: Cost tracking

Wrap every call and record normalised usage. Providers report differently, so convert first:

  • Anthropic: input_tokens -> inputTokens, cache_read_input_tokens -> cacheReadTokens, cache_creation_input_tokens -> cacheWriteTokens.
  • OpenAI Responses API: input_tokens includes cached tokens, so inputTokens = input_tokens - cached_tokens - cache_write_tokens (fields under input_tokens_details).
// cost-tracker.ts
interface Price { input: number; output: number; cacheRead: number; cacheWrite: number } // USD per 1M tokens

// Source: vendor pricing pages, 2026-10-24. Update when prices change.
export const PRICING: Record<string, Price> = {
  "claude-sonnet-5-5": { input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.5 },
  "claude-haiku-5-5":  { input: 0.1, output: 0.5,  cacheRead: 0.01, cacheWrite: 0.125 }, // prompts <= 100k tokens
  "gpt-6.1-sol":       { input: 2.0, output: 10.0, cacheRead: 0.1, cacheWrite: 2.5 },  // short-context rates, 30m cache write
  "gpt-6-luna":        { input: 0.1, output: 0.5,  cacheRead: 0.01, cacheWrite: 0.125 },
};

export interface Usage {
  model: string; feature: string; userId?: string;
  inputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; outputTokens: number;
}

export class CostTracker {
  private entries: (Usage & { costUsd: number; at: Date })[] = [];
  private budgets = new Map<string, number>();            // feature -> monthly USD
  private alerted = new Set<string>();

  constructor(private onAlert: (msg: string) => void = console.warn) {}

  cost(u: Usage): number {
    const p = PRICING[u.model];
    if (!p) throw new Error(`No price for model ${u.model}`);  // fail loudly: a missing price hides spend
    return (u.inputTokens * p.input + u.cacheReadTokens * p.cacheRead +
            u.cacheWriteTokens * p.cacheWrite + u.outputTokens * p.output) / 1_000_000;
  }

  setBudget(feature: string, monthlyUsd: number) { this.budgets.set(feature, monthlyUsd); }

  track(u: Usage, now = new Date()): number {
    const costUsd = this.cost(u);
    this.entries.push({ ...u, costUsd, at: now });
    const budget = this.budgets.get(u.feature);
    if (budget) {
      const spent = this.monthlySpend(u.feature, now);
      for (const level of [0.8, 1.0]) {
        const key = `${u.feature}:${level}:${now.getUTCFullYear()}-${now.getUTCMonth()}`;
        if (spent >= budget * level && !this.alerted.has(key)) {
          this.alerted.add(key);
          this.onAlert(`${u.feature} reached ${level * 100}% of $${budget} (spent $${spent.toFixed(2)})`);
        }
      }
    }
    return costUsd;
  }

  monthlySpend(feature?: string, now = new Date()): number {
    return this.entries
      .filter((e) =>
Полный SKILL.md на GitHub

Установить llm-cost-optimizer в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл llm-cost-optimizer?

Cuts LLM API spend by measuring cost per feature and user, routing easy requests to cheaper models, using provider prompt caching, adding a semantic response cache, and using the batch APIs. Use when someone asks to "reduce AI costs", "track LLM spending", "my OpenAI or Anthropic bill is too high", "set up model routing", "cache LLM responses", "compare model costs", or "set budget alerts for AI".

Как установить скилл llm-cost-optimizer?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл llm-cost-optimizer запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить llm-cost-optimizer с