Communitygithub.com

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

LLM APIのコスト最適化パターン — タスクの複雑さに応じたモデルルーティング、予算管理、リトライロジック、プロンプトキャッシュ。LLMの支出を削減したい場合や、タスクをモデル階層や予算に応じてルーティングする必要がある場合に使用します。

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

このスキルは、品質を維持しながらLLM APIのコストを制御するためのパターンを提供します。具体的には、タスクの複雑さに基づいて安価なモデルと高価なモデルを自動的に選択するモデルルーティング、不変(イミュータブル)なデータクラスを使用した累積支出の追跡、一時的なエラーのみをリトライする狭いリトライロジック、および長いシステムプロンプトをキャッシュして再送信を避けるプロンプトキャッシュの4つの主要な概念を組み合わせます。これらのパターンはAnthropic(Claude)やOpenAI(GPT)などのLLM APIを呼び出すアプリケーションや、バッチ処理パイプライン、マルチモデルアーキテクチャ、および本番システムに適しています。このパイプラインは、各API呼び出しで新しいトラッカーを返す不変のコストトラッカーを使用することで、デバッグと監査を容易にし、予算超過時には早期にエラーを発生させることで予算超過を防止します。

対応✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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  # 文字数
_SONNET_ITEM_THRESHOLD = 30     # アイテム数

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 など → 即座に例外を送出

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

関連スキル