Communitygithub.com

成本感知的LLM管道

LLM API使用成本優化模式——按任務複雜度進行模型路由、預算追蹤、重試邏輯和提示快取。當LLM開銷需要降低,或需要在不同模型階層與預算間分配任務時使用。

成本感知的LLM管道 是什麼?

此技能提供一個可組合的管道,用於控制LLM API成本,同時維持輸出品質。它整合了四項關鍵技術:依據輸入長度或項目數量自動路由至較便宜或較昂貴模型的模型選擇邏輯;一個不可變的CostTracker類別,用於累積花費並在超出預算時提早失敗;僅針對暫時性錯誤(如連線或速率限制)進行指數退避重試、對認證錯誤則快速失敗的窄重試機制;以及對長系統提示使用ephemeral快取的內建提示快取支援。此技能設計用於Claude Code或Cursor等AI代理,當工作負載涉及批次處理不同複雜度的項目,或需要在生產系統中設定預算護欄時特別有用。它支援Claude(Sonnet、Haiku)與OpenAI模型,並有基於2026年定價的參考表格。實作強調不變性與清晰的組合——每個API呼叫都會產生新的CostRecord與CostTracker,讓審計與除錯更簡單。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

成本感知的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,  # 可變部分
            },
        ],
    }
]

組合

將四種技術整合到一個管道函數中:

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年)

模型輸入(每百萬Token美元)輸出(每百萬Token美元)相對成本
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個Token的系統提示使用提示快取——節省成本並降低延遲
  • 絕不在認證或驗證錯誤時重試——僅針對暫時性錯誤(網路、速率限制、伺服器錯誤)

應避免的反模式

  • 不考慮複雜度,對所有請求都使用最昂貴的模型
  • 對所有錯誤進行重試(浪費預算在永久性失敗上)
  • 變異成本追蹤狀態(使除錯和審計困難)
  • 在整個程式碼庫中硬編碼模型名稱(應使用常數或設定檔)
  • 忽略重複性系統提示的快取

使用時機

  • 任何呼叫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.

相關技能