jpskill.com
💼 ビジネス コミュニティ

llm-cost-optimizer

LLM APIの利用コストを削減するために、モデルの使い分け、過去の回答の再利用、類似質問の活用、予算アラート設定などを行い、AI利用料金の最適化を支援するSkill。

📜 元の英語説明(参考)

Track, analyze, and reduce LLM API costs — model routing, prompt caching, semantic caching, and budget alerts. Use when someone asks to "reduce AI costs", "track LLM spending", "optimize API costs", "set up model routing", "cache LLM responses", "compare model costs", "set budget limits for AI", or "my OpenAI bill is too high". Covers cost tracking per feature/user, smart model routing (expensive model for hard tasks, cheap for easy), semantic caching, prompt compression, and budget alerting.

🇯🇵 日本人クリエイター向け解説

一言でいうと

LLM APIの利用コストを削減するために、モデルの使い分け、過去の回答の再利用、類似質問の活用、予算アラート設定などを行い、AI利用料金の最適化を支援するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o llm-cost-optimizer.zip https://jpskill.com/download/15080.zip && unzip -o llm-cost-optimizer.zip && rm llm-cost-optimizer.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/15080.zip -OutFile "$d\llm-cost-optimizer.zip"; Expand-Archive "$d\llm-cost-optimizer.zip" -DestinationPath $d -Force; ri "$d\llm-cost-optimizer.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して llm-cost-optimizer.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → llm-cost-optimizer フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

LLM Cost Optimizer

概要

LLM APIのコストは急速に増加します。例えば、1日に1万回の会話を行うチャットボットが1回あたり0.01ドルの場合、月額3,000ドルになります。このSkillは、コスト管理を構築します。機能ごと、ユーザーごとの支出を追跡し、単純なタスクを安価なモデルにルーティングし、繰り返されるクエリをキャッシュし、プロンプトを圧縮し、予算超過前にアラートを発します。

どのような時に使うか

  • 月々のLLMの請求額が増加しており、何がそれを引き起こしているのかを把握する必要がある場合
  • 一部の機能で、GPT-4o-miniで十分な場合にGPT-4oを使用している場合
  • ユーザーが同じ質問を繰り返し行うため、それらの応答をキャッシュしたい場合
  • チーム、機能、またはAPIキーごとに予算制限が必要な場合
  • プロバイダー間の総所有コストを比較する場合

手順

戦略1:コスト追跡ミドルウェア

すべてのLLM呼び出しをラップして、トークン、コスト、モデル、および機能をログに記録します。お金がどこに使われているかを正確に把握します。

// cost-tracker.ts — 機能、モデル、およびユーザーごとのLLMコストを追跡します
/**
 * LLM API呼び出しをラップし、トークン使用量と推定コストをログに記録し、
 * 予算制限を適用するミドルウェア。
 * 直接API呼び出しのドロップイン代替。
 */

interface CostEntry {
  timestamp: string;
  model: string;
  feature: string;         // この呼び出しを行った製品機能
  userId?: string;
  inputTokens: number;
  outputTokens: number;
  cachedTokens: number;
  costUsd: number;
  latencyMs: number;
}

// 100万トークンあたりの価格(入力/出力)— プロバイダーの変更に応じて更新
const PRICING: Record<string, { input: number; output: number; cached?: number }> = {
  "gpt-4o":                  { input: 2.50,  output: 10.00, cached: 1.25 },
  "gpt-4o-mini":             { input: 0.15,  output: 0.60,  cached: 0.075 },
  "claude-sonnet-4-20250514":   { input: 3.00,  output: 15.00, cached: 0.30 },
  "claude-haiku-3-20250722": { input: 0.25,  output: 1.25,  cached: 0.025 },
  "llama-3.1-8b":            { input: 0.05,  output: 0.05 },  // セルフホストの見積もり
};

export class CostTracker {
  private entries: CostEntry[] = [];
  private budgets: Map<string, number> = new Map();  // feature → 月間制限(USD)

  /**
   * 単一のLLM呼び出しのコストを計算します。
   */
  calculateCost(model: string, inputTokens: number, outputTokens: number, cachedTokens: number = 0): number {
    const pricing = PRICING[model];
    if (!pricing) return 0;

    const inputCost = ((inputTokens - cachedTokens) * pricing.input) / 1_000_000;
    const cachedCost = pricing.cached
      ? (cachedTokens * pricing.cached) / 1_000_000
      : 0;
    const outputCost = (outputTokens * pricing.output) / 1_000_000;

    return inputCost + cachedCost + outputCost;
  }

  /**
   * LLM呼び出しをログに記録し、予算を確認します。
   */
  track(entry: Omit<CostEntry, "costUsd" | "timestamp">): CostEntry {
    const costUsd = this.calculateCost(
      entry.model, entry.inputTokens, entry.outputTokens, entry.cachedTokens
    );

    const full: CostEntry = {
      ...entry,
      costUsd,
      timestamp: new Date().toISOString(),
    };

    this.entries.push(full);

    // 予算を確認
    const monthlySpend = this.getMonthlySpend(entry.feature);
    const budget = this.budgets.get(entry.feature);
    if (budget && monthlySpend > budget) {
      console.warn(`⚠️ "${entry.feature}"の予算を超過しました:$${monthlySpend.toFixed(2)} / $${budget}`);
    }

    return full;
  }

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

  getMonthlySpend(feature?: string): number {
    const now = new Date();
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);

    return this.entries
      .filter((e) => new Date(e.timestamp) >= monthStart)
      .filter((e) => !feature || e.feature === feature)
      .reduce((sum, e) => sum + e.costUsd, 0);
  }

  /**
   * 機能とモデルでグループ化されたコストレポートを生成します。
   */
  report(): Record<string, { calls: number; tokens: number; cost: number }> {
    const groups: Record<string, { calls: number; tokens: number; cost: number }> = {};

    for (const entry of this.entries) {
      const key = `${entry.feature} → ${entry.model}`;
      if (!groups[key]) groups[key] = { calls: 0, tokens: 0, cost: 0 };
      groups[key].calls++;
      groups[key].tokens += entry.inputTokens + entry.outputTokens;
      groups[key].cost += entry.costUsd;
    }

    return groups;
  }
}

戦略2:スマートモデルルーター

タスクを処理できる最も安価なモデルにルーティングします。難しいタスク → 高価なモデル。簡単なタスク → 安価なモデル。

// model-router.ts — LLM呼び出しを、処理可能な最も安価なモデルにルーティングします
/**
 * タスクの複雑さを分析し、適切なモデルにルーティングします。
 * 単純な分類/抽出 → ミニモデル(〜95%安価)。
 * 複雑な推論/コーディング → フルモデル。
 */

interface RouteDecision {
  model: string;
  reason: string;
  estimatedCostRatio: number;  // 1.0 = フルプライス、0.1 = フルプライスの10%
}

export function routeModel(task: string, context?: string): RouteDecision {
  const taskLower = task.toLowerCase();
  const contextLength = (context || "").length;

  // 単純な抽出/分類 → ミニモデル
  if (
    taskLower.includes("extract") ||
    taskLower.includes("classify") ||
    taskLower.includes("categorize") ||
    taskLower.includes("summarize") ||
    taskLower.includes("translate") ||
    taskLower.includes("format")
  ) {
    return {
      model: "gpt-4o-mini",
      reason: "単純な抽出/分類タスク",
      estimatedCostRatio: 0.06,  // GPT-4oコストの〜6%
    };
  }

  // 短いコンテキスト + 単純な質問 → ミニ
  if (contextLength < 2000 && !requiresReasoning(taskLower)) {
    return {
      model: "gpt-4o-mini",
      reason: "短いコンテキスト、単純なタスク",
      estimatedCostRatio: 0.06,
    };
  }

  // コード生成/デバッグ → フルモデル
  if (
    taskLower.includes("write code") ||
    taskLower.includes("debug") ||
    taskLower.includes("refactor") ||
    taskLower.includes("architect")
  ) {
    return {
      model: "claude-sonnet-4-20250514",
      reason: "コード生成には強力な推論が必要",
      estimate
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

LLM Cost Optimizer

Overview

LLM API costs grow fast — a chatbot doing 10K conversations/day at $0.01 each is $3K/month. This skill builds cost controls: track spending per feature and user, route simple tasks to cheap models, cache repeated queries, compress prompts, and alert before budgets blow up.

When to Use

  • Monthly LLM bill is growing and you need visibility into what's driving it
  • Some features use GPT-4o when GPT-4o-mini would work fine
  • Users ask the same questions repeatedly — cache those responses
  • Need budget limits per team, feature, or API key
  • Comparing total cost of ownership between providers

Instructions

Strategy 1: Cost Tracking Middleware

Wrap every LLM call to log tokens, cost, model, and feature. Know exactly where money goes.

// cost-tracker.ts — Track LLM costs per feature, model, and user
/**
 * Middleware that wraps LLM API calls, logs token usage
 * and estimated cost, and enforces budget limits.
 * Drop-in replacement for direct API calls.
 */

interface CostEntry {
  timestamp: string;
  model: string;
  feature: string;         // Which product feature made this call
  userId?: string;
  inputTokens: number;
  outputTokens: number;
  cachedTokens: number;
  costUsd: number;
  latencyMs: number;
}

// Pricing per 1M tokens (input / output) — update as providers change
const PRICING: Record<string, { input: number; output: number; cached?: number }> = {
  "gpt-4o":                  { input: 2.50,  output: 10.00, cached: 1.25 },
  "gpt-4o-mini":             { input: 0.15,  output: 0.60,  cached: 0.075 },
  "claude-sonnet-4-20250514":   { input: 3.00,  output: 15.00, cached: 0.30 },
  "claude-haiku-3-20250722": { input: 0.25,  output: 1.25,  cached: 0.025 },
  "llama-3.1-8b":            { input: 0.05,  output: 0.05 },  // Self-hosted estimate
};

export class CostTracker {
  private entries: CostEntry[] = [];
  private budgets: Map<string, number> = new Map();  // feature → monthly limit USD

  /**
   * Calculate cost for a single LLM call.
   */
  calculateCost(model: string, inputTokens: number, outputTokens: number, cachedTokens: number = 0): number {
    const pricing = PRICING[model];
    if (!pricing) return 0;

    const inputCost = ((inputTokens - cachedTokens) * pricing.input) / 1_000_000;
    const cachedCost = pricing.cached
      ? (cachedTokens * pricing.cached) / 1_000_000
      : 0;
    const outputCost = (outputTokens * pricing.output) / 1_000_000;

    return inputCost + cachedCost + outputCost;
  }

  /**
   * Log an LLM call and check budget.
   */
  track(entry: Omit<CostEntry, "costUsd" | "timestamp">): CostEntry {
    const costUsd = this.calculateCost(
      entry.model, entry.inputTokens, entry.outputTokens, entry.cachedTokens
    );

    const full: CostEntry = {
      ...entry,
      costUsd,
      timestamp: new Date().toISOString(),
    };

    this.entries.push(full);

    // Check budget
    const monthlySpend = this.getMonthlySpend(entry.feature);
    const budget = this.budgets.get(entry.feature);
    if (budget && monthlySpend > budget) {
      console.warn(`⚠️ Budget exceeded for "${entry.feature}": $${monthlySpend.toFixed(2)} / $${budget}`);
    }

    return full;
  }

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

  getMonthlySpend(feature?: string): number {
    const now = new Date();
    const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);

    return this.entries
      .filter((e) => new Date(e.timestamp) >= monthStart)
      .filter((e) => !feature || e.feature === feature)
      .reduce((sum, e) => sum + e.costUsd, 0);
  }

  /**
   * Generate a cost report grouped by feature and model.
   */
  report(): Record<string, { calls: number; tokens: number; cost: number }> {
    const groups: Record<string, { calls: number; tokens: number; cost: number }> = {};

    for (const entry of this.entries) {
      const key = `${entry.feature} → ${entry.model}`;
      if (!groups[key]) groups[key] = { calls: 0, tokens: 0, cost: 0 };
      groups[key].calls++;
      groups[key].tokens += entry.inputTokens + entry.outputTokens;
      groups[key].cost += entry.costUsd;
    }

    return groups;
  }
}

Strategy 2: Smart Model Router

Route tasks to the cheapest model that can handle them. Hard tasks → expensive model. Easy tasks → cheap model.

// model-router.ts — Route LLM calls to the cheapest capable model
/**
 * Analyzes task complexity and routes to the appropriate model.
 * Simple classification/extraction → mini model (~95% cheaper).
 * Complex reasoning/coding → full model.
 */

interface RouteDecision {
  model: string;
  reason: string;
  estimatedCostRatio: number;  // 1.0 = full price, 0.1 = 10% of full price
}

export function routeModel(task: string, context?: string): RouteDecision {
  const taskLower = task.toLowerCase();
  const contextLength = (context || "").length;

  // Simple extraction / classification → mini model
  if (
    taskLower.includes("extract") ||
    taskLower.includes("classify") ||
    taskLower.includes("categorize") ||
    taskLower.includes("summarize") ||
    taskLower.includes("translate") ||
    taskLower.includes("format")
  ) {
    return {
      model: "gpt-4o-mini",
      reason: "Simple extraction/classification task",
      estimatedCostRatio: 0.06,  // ~6% of GPT-4o cost
    };
  }

  // Short context + simple question → mini
  if (contextLength < 2000 && !requiresReasoning(taskLower)) {
    return {
      model: "gpt-4o-mini",
      reason: "Short context, simple task",
      estimatedCostRatio: 0.06,
    };
  }

  // Code generation / debugging → full model
  if (
    taskLower.includes("write code") ||
    taskLower.includes("debug") ||
    taskLower.includes("refactor") ||
    taskLower.includes("architect")
  ) {
    return {
      model: "claude-sonnet-4-20250514",
      reason: "Code generation requires strong reasoning",
      estimatedCostRatio: 1.0,
    };
  }

  // Complex reasoning → full model
  return {
    model: "gpt-4o",
    reason: "Complex task requiring strong reasoning",
    estimatedCostRatio: 0.8,
  };
}

function requiresReasoning(task: string): boolean {
  const reasoningKeywords = [
    "analyze", "compare", "evaluate", "design", "architect",
    "debug", "optimize", "explain why", "trade-off", "recommend",
  ];
  return reasoningKeywords.some((k) => task.includes(k));
}

Strategy 3: Semantic Cache

Cache LLM responses by meaning, not exact match. "What's the weather?" and "How's the weather today?" should hit the same cache.

# semantic_cache.py — Cache LLM responses by semantic similarity
"""
Caches LLM responses using embedding similarity.
If a new query is semantically similar to a cached one,
return the cached response instead of calling the API.
Saves 30-60% on repetitive workloads.
"""
import hashlib
import json
import time
from typing import Optional
import numpy as np
import openai

class SemanticCache:
    """LLM response cache using embedding similarity."""

    def __init__(self, similarity_threshold: float = 0.92, ttl_seconds: int = 3600):
        """
        Args:
            similarity_threshold: Min cosine similarity to consider a cache hit (0.92 = very similar)
            ttl_seconds: Cache entry expiration time
        """
        self.threshold = similarity_threshold
        self.ttl = ttl_seconds
        self.cache: list[dict] = []  # In production, use Redis or a vector DB
        self.client = openai.OpenAI()
        self.stats = {"hits": 0, "misses": 0, "saved_usd": 0.0}

    def get(self, query: str) -> Optional[str]:
        """Check cache for a semantically similar query.

        Args:
            query: The user's query

        Returns:
            Cached response if found, None otherwise
        """
        query_embedding = self._embed(query)
        now = time.time()

        best_match = None
        best_score = 0.0

        for entry in self.cache:
            # Skip expired entries
            if now - entry["timestamp"] > self.ttl:
                continue

            score = self._cosine_similarity(query_embedding, entry["embedding"])
            if score > best_score:
                best_score = score
                best_match = entry

        if best_match and best_score >= self.threshold:
            self.stats["hits"] += 1
            self.stats["saved_usd"] += best_match.get("cost_usd", 0.01)
            return best_match["response"]

        self.stats["misses"] += 1
        return None

    def set(self, query: str, response: str, cost_usd: float = 0.01) -> None:
        """Store a query-response pair in the cache."""
        self.cache.append({
            "query": query,
            "response": response,
            "embedding": self._embed(query),
            "cost_usd": cost_usd,
            "timestamp": time.time(),
        })

    def _embed(self, text: str) -> list[float]:
        response = self.client.embeddings.create(
            model="text-embedding-3-small",
            input=text
        )
        return response.data[0].embedding

    def _cosine_similarity(self, a: list[float], b: list[float]) -> float:
        a_arr, b_arr = np.array(a), np.array(b)
        return float(np.dot(a_arr, b_arr) / (np.linalg.norm(a_arr) * np.linalg.norm(b_arr)))

Examples

Example 1: Cut chatbot costs by 60%

User prompt: "Our support chatbot costs $3K/month on GPT-4o. Most questions are FAQs. Help me reduce costs without hurting quality."

The agent will:

  • Add cost tracking middleware to identify which question types cost the most
  • Set up semantic cache for FAQ-type questions (covers ~40% of volume)
  • Route simple questions to GPT-4o-mini (covers ~30% more)
  • Keep GPT-4o only for complex, novel questions
  • Result: ~60% cost reduction while maintaining quality on hard questions

Example 2: Set up budget alerts

User prompt: "I want to cap our AI spending at $500/month per team and get alerts at 80%."

The agent will use CostTracker with per-team budgets, add webhook alerts at 80% threshold, and generate weekly cost reports broken down by team and feature.

Guidelines

  • Track before optimizing — you can't reduce what you don't measure
  • Mini models handle 70% of tasks — GPT-4o-mini and Haiku are dramatically cheaper
  • Semantic cache threshold 0.92+ — lower risks returning wrong answers
  • Cache TTL depends on data freshness — static FAQs: hours. Dynamic data: minutes.
  • Prompt caching is free money — OpenAI and Anthropic cache system prompts automatically
  • Batch API = 50% off — OpenAI's Batch API halves cost for non-realtime workloads
  • Shorter prompts = lower costs — remove examples and instructions the model already knows
  • Monitor cost per user — detect abuse early, especially on free tiers
  • Self-hosted models for high volume — at 1M+ calls/month, Llama on your own GPU can be cheaper