About this skill
This skill provides a comprehensive cost-aware pipeline for interacting with Large Language Model (LLM) APIs, specifically tailored for Claude. It intelligently optimizes API usage costs without compromising output quality by implementing several key components. The pipeline dynamically routes tasks to the most appropriate LLM model based on their complexity – leveraging cheaper models like Haiku for simpler requests and reserving more powerful, albeit pricier, models like Sonnet for complex operations. It includes real-time budget tracking to ensure API expenditure remains within defined limits, robust retry mechanisms to handle transient errors and improve reliability, and intelligent prompt caching to reduce redundant API calls. Designed for scalable, production-grade AI applications, this skill ensures efficient resource utilization and predictable expenditure when building LLM-powered solutions.
Best use case
Developing cost-efficient LLM-powered applications, processing batches of items with varying complexities, maintaining API expenditure within defined budgets, and optimizing cost for complex tasks without sacrificing quality.
LLM API 使用成本优化模式 —— 基于任务复杂度的模型路由、预算跟踪、重试逻辑和提示缓存。
Significantly reduced LLM API costs, improved resource efficiency and budget adherence, optimized performance for varying task complexities, and a more robust, reliable, and scalable integration with LLM services.
Practical example
Example input
An AI agent is tasked with processing a queue of diverse jobs, some requiring a quick summarization of short text, and others needing a deep analysis of large datasets.
**Scenario 1: Simple Summarization**
```python
# Agent receives a simple task
task = {
"type": "summarize",
"content": "The quick brown fox jumps over the lazy dog. This is a common pangram used to display typefaces and test fonts.",
"max_output_tokens": 50
}
# Agent calls the cost-aware pipeline
pipeline.process(task)
```
**Scenario 2: Complex Data Analysis**
```python
# Agent receives a complex task
task = {
"type": "analyze_sentiment_and_themes",
"content": "Extremely long document with customer feedback data...", # Assume content > 10,000 chars
"item_count": 150,
"analysis_depth": "detailed"
}
# Agent calls the cost-aware pipeline
pipeline.process(task)
```Example output
**Scenario 1: Simple Summarization**
```json
{
"model_selected": "claude-haiku-4-5-20251001",
"cost_incurred": 0.00005,
"response": "Summary: A short pangram about a fox, often used for font testing.",
"cache_hit": false,
"retries_taken": 0,
"budget_remaining": 9.99995
}
```
**Scenario 2: Complex Data Analysis**
```json
{
"model_selected": "claude-sonnet-4-6",
"cost_incurred": 0.015,
"analysis_results": {
"overall_sentiment": "mixed",
"dominant_themes": ["performance issues", "feature requests", "customer support"]
},
"cache_hit": false,
"retries_taken": 1,
"budget_remaining": 9.98495
}
```When to use this skill
- When building applications that frequently call LLM APIs (e.g., Claude), when processing diverse tasks that range in complexity, when strict budget control for API spending is required, or when aiming to achieve cost optimization for challenging tasks while preserving high quality and reliability.
When not to use this skill
- For very simple, low-volume LLM interactions where cost is not a primary concern and the overhead of managing a cost-aware pipeline is not justified. Also, if your application explicitly requires the most powerful model for *every* interaction regardless of complexity or cost, as the routing logic might introduce unnecessary steps.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/cost-aware-llm-pipeline/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How cost-aware-llm-pipeline Compares
| Feature / Agent | cost-aware-llm-pipeline | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
LLM API 使用成本优化模式 —— 基于任务复杂度的模型路由、预算跟踪、重试逻辑和提示缓存。
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# 成本感知型 LLM 流水线
在保持质量的同时控制 LLM API 成本的模式。将模型路由、预算跟踪、重试逻辑和提示词缓存组合成一个可组合的流水线。
## 何时激活
* 构建调用 LLM API(Claude、GPT 等)的应用程序时
* 处理具有不同复杂度的批量项目时
* 需要将 API 支出控制在预算范围内时
* 需要在复杂任务上优化成本而不牺牲质量时
## 核心概念
### 1. 根据任务复杂度进行模型路由
自动为简单任务选择更便宜的模型,为复杂任务保留昂贵的模型。
```python
MODEL_SONNET = "claude-sonnet-4-6"
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)
```
### 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":
"""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
```
### 3. 窄范围重试逻辑
仅在暂时性错误时重试。对于认证或错误请求错误,快速失败。
```python
from 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
```
### 4. 提示词缓存
缓存长的系统提示词,以避免在每个请求上重新发送它们。
```python
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"}, # Cache this
},
{
"type": "text",
"text": user_input, # Variable part
},
],
}
]
```
## 组合
将所有四种技术组合到一个流水线函数中:
```python
def 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
```
## 价格参考(2025-2026)
| 模型 | 输入(美元/百万令牌) | 输出(美元/百万令牌) | 相对成本 |
|-------|---------------------|----------------------|---------------|
| Haiku 4.5 | $0.80 | $4.00 | 1x |
| Sonnet 4.6 | $3.00 | $15.00 | ~4x |
| Opus 4.5 | $15.00 | $75.00 | ~19x |
## 最佳实践
* **从最便宜的模型开始**,仅在达到复杂度阈值时才路由到昂贵的模型
* **在处理批次之前设置明确的预算限制** —— 尽早失败而不是超支
* **记录模型选择决策**,以便您可以根据实际数据调整阈值
* **对于超过 1024 个令牌的系统提示词,使用提示词缓存** —— 既能节省成本,又能降低延迟
* **切勿在认证或验证错误时重试** —— 仅针对暂时性故障(网络、速率限制、服务器错误)重试
## 应避免的反模式
* 无论复杂度如何,对所有请求都使用最昂贵的模型
* 对所有错误都进行重试(在永久性故障上浪费预算)
* 改变成本跟踪状态(使调试和审计变得困难)
* 在整个代码库中硬编码模型名称(使用常量或配置)
* 对重复的系统提示词忽略提示词缓存
## 适用场景
* 任何调用 Claude、OpenAI 或类似 LLM API 的应用程序
* 成本快速累积的批处理流水线
* 需要智能路由的多模型架构
* 需要预算护栏的生产系统Related Skills
ralphinho-rfc-pipeline
基于RFC驱动的多智能体DAG执行模式,包含质量门、合并队列和工作单元编排。
workspace-surface-audit
Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.
safety-guard
Use this skill to prevent destructive operations when working on production systems or running agents autonomously.
repo-scan
Cross-stack source code asset audit — classifies every file, detects embedded third-party libraries, and delivers actionable four-level verdicts per module with interactive HTML reports.
project-flow-ops
Operate execution flow across GitHub and Linear by triaging issues and pull requests, linking active work, and keeping GitHub public-facing while Linear remains the internal execution layer. Use when the user wants backlog control, PR triage, or GitHub-to-Linear coordination.
manim-video
Build reusable Manim explainers for technical concepts, graphs, system diagrams, and product walkthroughs, then hand off to the wider ECC video stack if needed. Use when the user wants a clean animated explainer rather than a generic talking-head script.
laravel-plugin-discovery
Discover and evaluate Laravel packages via LaraPlugins.io MCP. Use when the user wants to find plugins, check package health, or assess Laravel/PHP compatibility.
design-system
Use this skill to generate or audit design systems, check visual consistency, and review PRs that touch styling.
click-path-audit
Trace every user-facing button/touchpoint through its full state change sequence to find bugs where functions individually work but cancel each other out, produce wrong final state, or leave the UI in an inconsistent state. Use when: systematic debugging found no bugs but users report broken buttons, or after any major refactor touching shared state stores.
ck
Persistent per-project memory for Claude Code. Auto-loads project context on session start, tracks sessions with git activity, and writes to native memory. Commands run deterministic Node.js scripts — behavior is consistent across model versions.
canary-watch
Use this skill to monitor a deployed URL for regressions after deploys, merges, or dependency upgrades.
benchmark
Use this skill to measure performance baselines, detect regressions before/after PRs, and compare stack alternatives.