cost-aware-llm-pipeline
Skill8 starsChanged 3 months agoMITView on GitHub
Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching. Use when LLM spend needs to come down, or when routing tasks across model tiers and budgets.
We split this skill into the rules it gives an agent
1 rule. 1 is common, 0 are distinctive, and 0 are very specific to this project.
1
Common
Most of the 17 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Common: line 166
Set explicit budget limits: before processing batches — fail early rather than overspend
“Common” is measured: kept by at least 6 in 10 of the 17 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Cost-Aware LLM Pipeline
Patterns for controlling LLM API costs while maintaining quality. Combines model routing, budget tracking, retry logic, and prompt caching into a composable pipeline.
When to Activate
- Building applications that call LLM APIs (Claude, GPT, etc.)
- Processing batches of items with varying complexity
- Need to stay within a budget for API spend
- Optimizing cost without sacrificing quality on complex tasks
Core Concepts
1. Model Routing by Task Complexity
Automatically select cheaper models for simple tasks, reserving expensive models for complex ones.
MODEL_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)2. Immutable Cost Tracking
Track cumulative spend with frozen dataclasses. Each API call returns a new tracker — never mutates state.
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_limit3. Narrow Retry Logic
Retry only on transient errors. Fail fast on authentication or bad request errors.
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 immediately4. Prompt Caching
Cache long system prompts to avoid resending them on every request.
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"}, # Cache this
},
{
"type": "text",
"text": user_input, # Variable part
},
],
}
]Composition
Combine all four techniques in a single pipeline function:
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), trackerPricing Reference (2025-2026)
| Model | Input ($/1M tokens) | Output ($/1M tokens) | Relative Cost |
| Haiku 4.5 | $0.80 | $4.00 | 1x |
| Sonnet 4.6 | $3.00 | $15.00 | ~4x |
| Opus 4.5 | $15.00 | $75.00 | ~19x |
Best Practices
- Start with the cheapest model and only route to expensive models when complexity thresholds are met
- Set explicit budget limits before processing batches — fail early rather than overspend
- Log model selection decisions so you can tune thresholds based on real data
- Use prompt caching for system prompts over 1024 tokens — saves both cost and latency
- Never retry on authentication or validation errors — only transient failures (network, rate limit, server error)
Anti-Patterns to Avoid
- Using the most expensive model for all requests regardless of complexity
- Retrying on all errors (wastes budget on permanent failures)
- Mutating cost tracking state (makes debugging and auditing difficult)
- Hardcoding model names throughout the codebase (use constants or config)
- Ignoring prompt caching for repetitive system prompts
When to Use
- Any application calling Claude, OpenAI, or similar LLM APIs
- Batch processing pipelines where cost adds up quickly
- Multi-model architectures that need intelligent routing
- Production systems that need budget guardrails
Other versions19 projects use a version of this.
Word for word · 0
None found.
Edited · 16
- loulanyue/awesome-claude-notes★ 27299% same
- Fmarzochi/EGC★ 6196% same
- Puen2001/aether-os★ 298% same
- get-proofpilot/claude-skills-catalog★ 199% same
- junimnjw/everything-claude-code★ 154% same
- NISTALTALSON/essential-claude-skills★ 191% same
- royaluniondesign-sys/claude-os★ 199% same
- SamuelNDCE/claude-super-skill-library★ 199% same
- TironFox/everything-claude-code★ 199% same
- davidanthonyn/claude-skills★ 099% same
6 more not listed
Wrote their own version · 3
- kuker24/OpenCodeBestFriend★ 0same name
- SirCharan/claude-code-harness★ 0same name
- thanvish21/hcc-bundle★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository273 other files it gives its agents.
- accessibilitySkill
- agent-architecture-auditSkill
- agent-evalSkill
- agent-harness-constructionSkill
- agentic-engineeringSkill
- agentic-osSkill
- agent-introspection-debuggingSkill
- agent-payment-x402Skill
- agent-self-evaluationSkill
- agent-sortSkill
- ai-first-engineeringSkill
- ai-regression-testingSkill
- android-clean-architectureSkill
- angular-developerSkill
- api-connector-builderSkill
- api-designSkill
- architecture-decision-recordsSkill
- article-writingSkill
- automation-audit-opsSkill
- autonomous-agent-harnessSkill
- autonomous-loopsSkill
- backend-patternsSkill
- benchmark-methodologySkill
- benchmark-optimization-loopSkill
- benchmarkSkill
- blender-motion-state-inspectionSkill
- blueprintSkill
- brand-discoverySkill
- brand-voiceSkill
- browser-qaSkill
- bun-runtimeSkill
- canary-watchSkill
- carrier-relationship-managementSkill
- cisco-ios-patternsSkill
- ckSkill
- claude-devfleetSkill
- clickhouse-ioSkill
- click-path-auditSkill
- codebase-onboardingSkill
- codehealth-mcpSkill
- code-tourSkill
- coding-standardsSkill
- competitive-platform-analysisSkill
- competitive-report-structureSkill
- compose-multiplatform-patternsSkill
- config-gcSkill
- configure-eccSkill
- connections-optimizerSkill
- content-engineSkill
- content-hash-cache-patternSkill
- context-budgetSkill
- continuous-agent-loopSkill
- contract-firstSkill
- cost-trackingSkill
- council-multi-modelSkill
- councilSkill
- cpp-coding-standardsSkill
- cpp-testingSkill
- crosspostSkill
- csharp-testingSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

