Communitygithub.com

成本感知的LLM管道

用于控制LLM API使用成本的优化模式——按任务复杂度进行模型路由、预算跟踪、重试逻辑和提示缓存。当需要降低LLM开销或跨模型层级和预算路由任务时使用。

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

这是一个用于控制LLM API调用成本同时保持输出质量的组合式管道模式。它集成了四项关键技术:1) 按任务复杂度自动选择模型(简单任务使用低成本模型如Haiku,复杂任务使用高性能模型如Sonnet);2) 不可变成本跟踪,使用冻结数据类记录每次调用的花费并检查是否超预算;3) 窄重试逻辑,仅对临时性错误(如网络连接、速率限制、服务器错误)进行重试,对认证或参数错误立即失败;4) 提示缓存,对长系统提示进行缓存以减少重复发送。支持Claude、GPT等主流LLM 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 中提问

打开一个已预加载此 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/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.

相关技能