Cost Aware Llm Pipeline logo

Cost Aware Llm Pipeline

Community
mturac
cost-aware-llm-pipeline

LLM APIの使用量のコスト最適化パターン — タスクの複雑さによるモデルルーティング、予算追跡、リトライロジック、プロンプトキャッシング。

Overview

Publishermturac
Repositoryeverything-openai-codex
Skill namecost-aware-llm-pipeline
Stars
91
Forks
2
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by mturac on GitHub. Read the source before you install it.

Installation

Install the Cost Aware Llm Pipeline AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/mturac/everything-openai-codex.git /tmp/everything-openai-codex
mkdir -p .claude/skills
cp -r /tmp/everything-openai-codex/docs/ja-JP/skills/cost-aware-llm-pipeline .claude/skills/cost-aware-llm-pipeline
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Cost Aware Llm Pipeline in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Cost Aware Llm Pipeline on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Cost Aware Llm Pipeline is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

コスト認識LLMパイプライン

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

起動条件

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

コアコンセプト

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

シンプルなタスクには自動的に安価なモデルを選択し、複雑なタスクのために高価なモデルを予約します。

python
MODEL_STANDARD = "codex-standard-4-6"
MODEL_FAST = "codex-fast-4-5-20251001"

_STANDARD_TEXT_THRESHOLD = 10_000  # 文字数
_STANDARD_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 >= _STANDARD_TEXT_THRESHOLD or item_count >= _STANDARD_ITEM_THRESHOLD:
        return MODEL_STANDARD  # 複雑なタスク
    return MODEL_FAST  # シンプルなタスク(3〜4倍安価)

2. 不変のコスト追跡

凍結データクラスで累積支出を追跡します。各API呼び出しは新しいトラッカーを返します — 状態を変更しません。

python
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":
        """追加されたレコードで新しいトラッカーを返す(selfは変更しない)。"""
        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. 狭いリトライロジック

一時的なエラーのみリトライします。認証やリクエストエラーでは素早く失敗します。

python
from openai 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. プロンプトキャッシング

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

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

合成

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

python
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

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

モデル入力($/1Mトークン)出力($/1Mトークン)相対コスト
Fast 4.5$0.80$4.001x
Standard 4.6$3.00$15.00約4x
Deep 4.5$15.00$75.00約19x

ベストプラクティス

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

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

  • 複雑さに関わらずすべてのリクエストに最も高価なモデルを使用すること
  • すべてのエラーでリトライすること(永続的な失敗で予算を無駄にする)
  • コスト追跡の状態を変更すること(デバッグと監査が困難になる)
  • コードベース全体にモデル名をハードコードすること(定数または設定を使用する)
  • 繰り返しのシステムプロンプトでプロンプトキャッシングを無視すること

使用すべき場合

  • Codex、OpenAI、または同様のLLM APIを呼び出すすべてのアプリケーション
  • コストが積み上がるバッチ処理パイプライン
  • インテリジェントルーティングが必要なマルチモデルアーキテクチャ
  • 予算ガードレールが必要な本番システム

Frequently asked questions

What does the Cost Aware Llm Pipeline AI skill do?

LLM APIの使用量のコスト最適化パターン — タスクの複雑さによるモデルルーティング、予算追跡、リトライロジック、プロンプトキャッシング。

Why use Cost Aware Llm Pipeline on TypingMind?

Because you install it once and use it with any model. Cost Aware Llm Pipeline is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Cost Aware Llm Pipeline in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/mturac/everything-openai-codex/tree/main/docs/ja-JP/skills/cost-aware-llm-pipeline. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Cost Aware Llm Pipeline?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Cost Aware Llm Pipeline?

As many as you like. As long as a model supports skills, you can use Cost Aware Llm Pipeline with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Cost Aware Llm Pipeline AI skill free?

Yes. It is published on GitHub by mturac under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇