Communitygithub.com

コスト意識型LLMパイプライン

LLM API利用におけるコスト最適化パターン — タスクの複雑さに応じたモデルルーティング、予算追跡、リトライロジック、プロンプトキャッシング。LLM費用を削減したい場合や、タスクを複数のモデル階層と予算に分散させたい場合に使用します。

コスト意識型LLMパイプライン とは?

このスキルは、LLM APIのコストを品質を維持しながら制御するための包括的なパターンを提供します。主な機能として、タスクの複雑さに基づいて安価なモデル(例:Haiku)と高価なモデル(例:Sonnet)を自動的にルーティングするモデル選択、不変データクラスを使用した累積API支出の追跡、一時的なエラーのみをリトライして認証エラーなどは即座に失敗させる狭いリトライロジック、そして長いシステムプロンプトの再送信を回避するプロンプトキャッシングを組み合わせます。これらの手法は単一のパイプライン関数に合成でき、開発者はLLM呼び出しのコスト、レイテンシ、信頼性を簡単に最適化できます。このパターンはClaude、GPTなどのLLM APIを呼び出すあらゆるアプリケーションに適用可能で、特にバッチ処理やマルチモデルアーキテクチャ、予算制限のある本番システムで効果を発揮します。

対応✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/cost-aware-llm-pipeline

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

コスト意識型LLMパイプライン は何をしますか?

LLM APIのコストを品質を維持しながら制御するためのパターン。モデルルーティング、予算追跡、リトライロジック、プロンプトキャッシングを合成可能なパイプラインに組み合わせます。

アクティベーションのタイミング

  • LLM API(Claude、GPTなど)を呼び出すアプリケーションを構築している場合
  • 複雑さが異なるアイテムのバッチを処理している場合
  • API支出の予算内に収める必要がある場合
  • 複雑なタスクの品質を犠牲にせずにコストを最適化したい場合

コアコンセプト

1. タスクの複雑さによるモデルルーティング

単純なタスクには自動的に安価なモデルを選択し、複雑なタスクには高価なモデルを予約します。

MODEL_SONNET = "claude-sonnet-5"
MODEL_HAIKU = "claude-haiku-4-5-20251001"

_SONNET_TEXT_THRESHOLD = 10_000  # chars
_SONNET_ITEM_THRESHOLD = 30     # items

def select_model(
    text_length: int,
    item_count: int,
    force_model: str | None = None,
) -> str:
    """タスクの複雑さに基づいてモデルを選択します。"""
    if force_model is not None:
        return force_model
    if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD:
        return MODEL_SONNET  # 複雑なタスク
    return MODEL_HAIKU  # 単純なタスク(3-4倍安い)

2. 不変なコスト追跡

凍結されたデータクラスで累積支出を追跡します。各API呼び出しは新しいトラッカーを返し、状態を変更することはありません。

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class CostRecord:
    model: str
    input_tokens: int
    output_tokens: int
    cost_usd: float

@dataclass(frozen=True, slots=True)
class CostTracker:
    budget_limit: float = 1.00
    records: tuple[CostRecord, ...] = ()

    def add(self, record: CostRecord) -> "CostTracker":
        """レコードを追加した新しいトラッカーを返します(自身を変更しません)。"""
        return CostTracker(
            budget_limit=self.budget_limit,
            records=(*self.records, record),
        )

    @property
    def total_cost(self) -> float:
        return sum(r.cost_usd for r in self.records)

    @property
    def over_budget(self) -> bool:
        return self.total_cost > self.budget_limit

3. 狭いリトライロジック

一時的なエラーの場合のみリトライします。認証エラーや無効なリクエストエラーでは即座に失敗します。

from anthropic import (
    APIConnectionError,
    InternalServerError,
    RateLimitError,
)

_RETRYABLE_ERRORS = (APIConnectionError, RateLimitError, InternalServerError)
_MAX_RETRIES = 3

def call_with_retry(func, *, max_retries: int = _MAX_RETRIES):
    """一時的なエラーの場合のみリトライし、その他のエラーでは即座に失敗します。"""
    for attempt in range(max_retries):
        try:
            return func()
        except _RETRYABLE_ERRORS:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # 指数バックオフ
    # AuthenticationError, BadRequestError など → 即座にraise

4. プロンプトキャッシング

長いシステムプロンプトをキャッシュして、リクエストごとに再送信するのを回避します。

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": system_prompt,
                "cache_control": {"type": "ephemeral"},  # これをキャッシュ
            },
            {
                "type": "text",
                "text": user_input,  # 可変部分
            },
        ],
    }
]

合成

4つのテクニックすべてを単一のパイプライン関数に組み合わせます:

def process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]:
    # 1. モデルをルーティング
    model = select_model(len(text), estimated_items, config.force_model)

    # 2. 予算をチェック
    if tracker.over_budget:
        raise BudgetExceededError(tracker.total_cost, tracker.budget_limit)

    # 3. リトライ + キャッシングで呼び出し
    response = call_with_retry(lambda: client.messages.create(
        model=model,
        messages=build_cached_messages(system_prompt, text),
    ))

    # 4. コストを追跡(不変)
    record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...)
    tracker = tracker.add(record)

    return parse_result(response), tracker

価格リファレンス(2026年)

モデル入力($ / 100万トークン)出力($ / 100万トークン)相対コスト
Haiku 3.5 (レガシー)$0.80$4.000.8x
Haiku 4.5$1.00$5.001x
Sonnet 5$2.00$10.002x
Sonnet 4.6$3.00$15.003x
Opus 4.8$5.00$25.005x
Fable 5 / Mythos 5$10.00$50.0010x
Opus 4.0 / 4.1 (レガシー)$15.00$75.0015x

ベストプラクティス

  • 最も安いモデルから始めて、複雑さのしきい値を満たした場合のみ高価なモデルにルーティングする
  • バッチ処理の前に明示的な予算制限を設定する — 過剰支出する前に早期に失敗する
  • モデル選択の決定をログに記録する ことで、実際のデータに基づいてしきい値を調整できる
  • 1024トークンを超えるシステムプロンプトにはプロンプトキャッシングを使用する — コストとレイテンシの両方を節約
  • 認証エラーやバリデーションエラーでは決してリトライしない — 一時的な障害(ネットワーク、レート制限、サーバーエラー)のみリトライする

避けるべきアンチパターン

  • 複雑さに関係なくすべてのリクエストに最も高価なモデルを使用する
  • すべてのエラーでリトライする(永続的な障害に予算を浪費する)
  • コスト追跡状態を変更可能にする(デバッグと監査が困難になる)
  • コードベース全体にモデル名をハードコーディングする(定数または設定を使用する)
  • 反復的なシステムプロンプトに対するプロンプトキャッシングを無視する

使用すべきタイミング

  • Claude、OpenAI、または類似のLLM APIを呼び出すあらゆるアプリケーション
  • コストが急速に累積するバッチ処理パイプライン
  • インテリジェントなルーティングを必要とするマルチモデルアーキテクチャ
  • 予算ガードレールを必要とする本番システム

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル