Communitygithub.com

成本感知的LLM管線

用於LLM API使用的最佳化成本模式——依據任務複雜度進行模型路由、預算追蹤、重試邏輯和提示快取。當LLM花費需要降低,或需要在不同模型層級和預算間路由任務時使用。

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

這個技能提供了一套可組合的管線模式,用於控制LLM API成本同時維持品質。它結合了模型路由(依據任務複雜度選擇較便宜或較昂貴的模型)、不可變的成本追蹤(使用凍結資料類別來累積記錄,並在超出預算時提早失敗)、狹義重試邏輯(僅針對短暫性錯誤如連線問題、速率限制和伺服器錯誤進行重試,並採用指數退避),以及提示快取(透過快取系統提示來減少重複傳送的代幣)。支援的平台包括Claude、OpenAI等LLM API,特別適合批次處理管線、多模型架構和需要預算保護的生產系統。技能提供了Python實作範例,包括模型選擇函數、成本追蹤器類別、重試裝飾器和快取訊息建構,並附有2026年定價參考表和最佳實踐指南。

相容平台✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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)

模型輸入(每百萬代幣美元)輸出(每百萬代幣美元)相對成本
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.

相關技能