Install any skill in seconds. Free to start, no credit card required.
Get Started Free →LLM APIの使用量のコスト最適化パターン — タスクの複雑さによるモデルルーティング、予算追跡、リトライロジック、プロンプトキャッシング。
.claude/skills/affaan-m-cost-aware-llm-pipeline/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 14% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 35% | 0% |
| case-05 | ✗→✓ | ▲ Improved | 56% | 0% |
| case-06 | ✗→✓ | ▲ Improved | 30% | 0% |
| case-08 | ✗→✓ | ▲ Improved | 118% | 0% |
在保持质量的同时控制 LLM API 成本的模式。将模型路由、预算跟踪、重试逻辑和提示词缓存组合成一个可组合的流水线。
自动为简单任务选择更便宜的模型,为复杂任务保留昂贵的模型。
pythonMODEL_SONNET = "claude-sonnet-5" MODEL_HAIKU = "claude-haiku-4-5-20251001" _SONNET_TEXT_THRESHOLD = 10_000 # chars _SONNET_ITEM_THRESHOLD = 30 # items def select_model( text_length: int, item_count: int, force_model: str | None = None, ) -> str: """Select model based on task complexity.""" if force_model is not None: return force_model if text_length >= _SONNET_TEXT_THRESHOLD or item_count >= _SONNET_ITEM_THRESHOLD: return MODEL_SONNET # Complex task return MODEL_HAIKU # Simple task (3-4x cheaper)
使用冻结的数据类跟踪累计支出。每个 API 调用都会返回一个新的跟踪器 —— 永不改变状态。
pythonfrom 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 new tracker with added record (never mutates 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
仅在暂时性错误时重试。对于认证或错误请求错误,快速失败。
pythonfrom anthropic import ( APIConnectionError, InternalServerError, RateLimitError, ) _RETRYABLE_ERRORS = (APIConnectionError, RateLimitError, InternalServerError) _MAX_RETRIES = 3 def call_with_retry(func, *, max_retries: int = _MAX_RETRIES): """Retry only on transient errors, fail fast on others.""" for attempt in range(max_retries): try: return func() except _RETRYABLE_ERRORS: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoff # AuthenticationError, BadRequestError etc. → raise immediately
缓存长的系统提示词,以避免在每个请求上重新发送它们。
pythonmessages = [ { "role": "user", "content": [ { "type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}, # Cache this }, { "type": "text", "text": user_input, # Variable part }, ], } ]
将所有四种技术组合到一个流水线函数中:
pythondef process(text: str, config: Config, tracker: CostTracker) -> tuple[Result, CostTracker]: # 1. Route model model = select_model(len(text), estimated_items, config.force_model) # 2. Check budget if tracker.over_budget: raise BudgetExceededError(tracker.total_cost, tracker.budget_limit) # 3. Call with retry + caching response = call_with_retry(lambda: client.messages.create( model=model, messages=build_cached_messages(system_prompt, text), )) # 4. Track cost (immutable) record = CostRecord(model=model, input_tokens=..., output_tokens=..., cost_usd=...) tracker = tracker.add(record) return parse_result(response), tracker
| 模型 | 输入(美元/百万令牌) | 输出(美元/百万令牌) | 相对成本 | |-------|---------------------|----------------------|---------------| | Haiku 4.5 | $0.80 | $4.00 | 1x | | Sonnet 4.6 | $3.00 | $15.00 | ~4x | | Opus 4.5 | $15.00 | $75.00 | ~19x |
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-15 | pass→pass | 17,004 | 13,294 | -22% | 1 | 1 | 0% | 2,637 | 3,591 | +36% | 0 | 0 | — |
case-01 | fail→pass | 25,706 | 22,795 | -11% | 1 | 1 | 0% | 5,420 | 6,173 | +14% | 0 | 0 | — |
case-02 | fail→pass | 14,290 | 10,243 | -28% | 1 | 1 | 0% | 2,574 | 3,482 | +35% | 0 | 0 | — |
case-03 | pass→pass | 12,136 | 9,026 | -26% | 1 | 1 | 0% | 2,171 | 3,085 | +42% | 0 | 0 | — |
case-04 | pass→pass | 15,030 | 9,864 | -34% | 1 | 1 | 0% | 2,619 | 3,313 | +26% | 0 | 0 | — |
case-05 | fail→pass | 9,850 | 6,298 | -36% | 1 | 1 | 0% | 1,787 | 2,788 | +56% | 0 | 0 | — |
case-06 | fail→pass | 15,939 | 13,278 | -17% | 1 | 1 | 0% | 3,181 | 4,120 | +30% | 0 | 0 | — |
case-07 | pass→pass | 14,914 | 8,497 | -43% | 1 | 1 | 0% | 2,799 | 3,012 | +8% | 0 | 0 | — |
case-08 | fail→pass | 6,923 | 6,936 | +0% | 1 | 1 | 0% | 1,298 | 2,828 | +118% | 0 | 0 | — |
case-09 | fail→pass | 10,864 | 7,098 | -35% | 1 | 1 | 0% | 1,872 | 2,739 | +46% | 0 | 0 | — |
case-10 | fail→pass | 16,217 | 9,058 | -44% | 1 | 1 | 0% | 2,417 | 2,999 | +24% | 0 | 0 | — |
case-11 | fail→pass | 4,973 | 1,911 | -62% | 1 | 1 | 0% | 841 | 1,824 | +117% | 0 | 0 | — |
case-12 | pass→pass | 5,190 | 2,021 | -61% | 1 | 1 | 0% | 880 | 1,914 | +118% | 0 | 0 | — |
case-13 | pass→pass | 21,106 | 7,448 | -65% | 1 | 1 | 0% | 2,778 | 2,733 | -2% | 0 | 0 | — |
case-14 | pass→pass | 16,802 | 17,281 | +3% | 1 | 1 | 0% | 2,856 | 4,794 | +68% | 0 | 0 | — |
case-16 | pass→pass | 5,980 | 3,405 | -43% | 1 | 1 | 0% | 938 | 2,068 | +120% | 0 | 0 | — |
case-17 | pass→pass | 13,326 | 3,829 | -71% | 1 | 1 | 0% | 2,214 | 2,212 | -0% | 0 | 0 | — |
case-18 | pass→pass | 3,219 | 2,482 | -23% | 1 | 1 | 0% | 452 | 1,865 | +313% | 0 | 0 | — |
case-19 | pass→pass | 17,183 | 19,758 | +15% | 1 | 1 | 0% | 2,289 | 4,792 | +109% | 0 | 0 | — |
case-20 | pass→pass | 10,271 | 3,418 | -67% | 1 | 1 | 0% | 1,492 | 2,000 | +34% | 0 | 0 | — |
case-21 | pass→pass | 21,051 | 33,085 | +57% | 1 | 1 | 0% | 3,677 | 5,663 | +54% | 0 | 0 | — |
case-22 | pass→pass | 17,319 | 15,030 | -13% | 1 | 1 | 0% | 2,652 | 3,825 | +44% | 0 | 0 | — |
case-23 | pass→fail | 19,432 | 14,957 | -23% | 1 | 1 | 0% | 2,880 | 3,910 | +36% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +30 percentage points is the difference between those two pass rates over the 23 comparable cases. 1 case got worse with the skill loaded, and it is included in that figure.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
| Model | Method | Date | Lift |
|---|---|---|---|
| gemini-3.6-flash | verified | 8/12/2026 | +23% |
Other measured skills in the registry, with their headline benchmark lift.