Automated summary
This skill provides Python patterns for lowering LLM API costs by combining complexity-based model routing, immutable budget tracking, narrow retry logic, and prompt caching.
Strengths
- Automatic routing between a cheap and an expensive model using text-length and item-count thresholds
- Cost tracking through frozen dataclasses with no state mutation and an over-budget check
- Retries restricted to transient errors (connection, rate limit, server) with exponential backoff, failing fast on auth errors
- Ephemeral cache_control on long system prompts so they are not resent on every request
Limitations
- Routing thresholds (10,000 characters, 30 items) and pricing are hardcoded and must be tuned per project
- The skill describes no quality measurement to confirm the cheap model suffices for routed tasks
- The composition example is partial and assumes manual wiring into the Anthropic SDK
Use it when an application makes high-volume LLM API calls and the bill must come down without hurting complex tasks.
Avoid it when you only call a single fixed model at low volume, where routing and tracking overhead adds nothing.
Security analysis
SafeThis skill contains only documentation, illustrative Python snippets, and standard LLM API cost-management patterns. It declares no tools and has no instructions to run shell commands, exfiltrate secrets, disable safeguards, or perform destructive actions.
No concerns found
How this analysis is madeExamples
Our batch job calls Claude on thousands of short support tickets and the bill is too high. Add model routing so simple tickets use a cheaper model, and wire in cost tracking with a $5 budget limit.Refactor our LLM client to cache the long system prompt with cache_control ephemeral and only retry on rate limit and server errors with exponential backoff.Implement an immutable CostTracker that accumulates spend per call and raises a BudgetExceededError before we exceed our $2 budget.name: cost-aware-llm-pipeline description: 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. metadata: origin: ECC
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_limit
3. 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 immediately
4. 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), tracker
Pricing 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
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/cost-aware-llm-pipeline-mte1lkqk/download' --output '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md.part' && mv '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md.part' '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md' && test -s '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/cost-aware-llm-pipeline' && cp -R '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk' '.claude/skills/cost-aware-llm-pipeline'Cursor
test -f '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md' && test -s '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/cost-aware-llm-pipeline' && cp -R '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk' '.cursor/skills/cost-aware-llm-pipeline'Codex
test -f '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md' && test -s '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/cost-aware-llm-pipeline' && cp -R '.skill-downloads/cost-aware-llm-pipeline-mte1lkqk' '.agents/skills/cost-aware-llm-pipeline'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/cost-aware-llm-pipeline-mte1lkqk'openskills read 'cost-aware-llm-pipeline-mte1lkqk'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/cost-aware-llm-pipeline-mte1lkqk/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
Create Interactive Maps with kepler.gl
Data & AI
Create interactive map visualizations and export standalone HTML using the keplergl Python package. Use to plot geospatial data from DataFrames, GeoJSON, or CSV.
Agent-Driven Parameter Optimization
Data & AI
Guide for optimizing configurable systems with a measurable objective, using bounded trials and evidence-based recommendations.
ICP Visitor Outreach
Data & AI
Identify signed-up users matching the ideal customer profile but stalled, and draft personalized outreach to re-engage them.