Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching.
.claude/skills/loulanyue-cost-aware-llm-pipeline/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 47% | 0% |
| case-03 | ✗→✓ | ▲ Improved | 49% | 0% |
| case-08 | ✗→✓ | ▲ Improved | -16% | 0% |
| case-09 | ✗→✓ | ▲ Improved | 49% | 0% |
| case-12 | ✗→✓ | ▲ Improved | 97% | 0% |
Patterns for controlling LLM API costs while maintaining quality. Combines model routing, budget tracking, retry logic, and prompt caching into a composable pipeline.
Automatically select cheaper models for simple tasks, reserving expensive models for complex ones.
pythonMODEL_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)
Track cumulative spend with frozen dataclasses. Each API call returns a new tracker — never mutates state.
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
Retry only on transient errors. Fail fast on authentication or bad request errors.
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
Cache long system prompts to avoid resending them on every request.
pythonmessages = [ { "role": "user", "content": [ { "type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}, # Cache this }, { "type": "text", "text": user_input, # Variable part }, ], } ]
Combine all four techniques in a single pipeline function:
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
| 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 |
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 9,918 | 6,652 | -33% | 1 | 1 | 0% | 2,035 | 2,985 | +47% | 0 | 0 | — |
case-02 | fail→fail | 9,170 | 8,414 | -8% | 1 | 1 | 0% | 1,898 | 3,272 | +72% | 0 | 0 | — |
case-03 | fail→pass | 10,354 | 8,631 | -17% | 1 | 1 | 0% | 2,104 | 3,145 | +49% | 0 | 0 | — |
case-04 | pass→pass | 14,502 | 10,418 | -28% | 1 | 1 | 0% | 2,840 | 3,620 | +27% | 0 | 0 | — |
case-05 | fail→fail | 14,506 | 7,162 | -51% | 1 | 1 | 0% | 2,848 | 2,960 | +4% | 0 | 0 | — |
case-06 | pass→pass | 14,011 | 9,041 | -35% | 1 | 1 | 0% | 2,981 | 3,295 | +11% | 0 | 0 | — |
case-07 | pass→pass | 6,705 | 7,001 | +4% | 1 | 1 | 0% | 1,258 | 2,771 | +120% | 0 | 0 | — |
case-08 | fail→pass | 23,026 | 11,800 | -49% | 1 | 1 | 0% | 4,874 | 4,100 | -16% | 0 | 0 | — |
case-09 | fail→pass | 7,956 | 4,514 | -43% | 1 | 1 | 0% | 1,639 | 2,438 | +49% | 0 | 0 | — |
case-10 | pass→pass | 11,283 | 4,171 | -63% | 1 | 1 | 0% | 2,411 | 2,406 | -0% | 0 | 0 | — |
case-11 | pass→pass | 9,807 | 5,209 | -47% | 1 | 1 | 0% | 1,828 | 2,594 | +42% | 0 | 0 | — |
case-12 | fail→pass | 6,479 | 3,615 | -44% | 1 | 1 | 0% | 1,106 | 2,178 | +97% | 0 | 0 | — |
case-13 | pass→pass | 12,337 | 6,353 | -49% | 1 | 1 | 0% | 2,161 | 2,540 | +18% | 0 | 0 | — |
case-14 | pass→pass | 13,029 | 8,840 | -32% | 1 | 1 | 0% | 2,680 | 3,162 | +18% | 0 | 0 | — |
case-15 | pass→pass | 15,564 | 9,860 | -37% | 1 | 1 | 0% | 2,375 | 3,150 | +33% | 0 | 0 | — |
case-16 | pass→pass | 16,518 | 13,428 | -19% | 1 | 1 | 0% | 2,859 | 3,849 | +35% | 0 | 0 | — |
case-17 | fail→pass | 14,541 | 12,638 | -13% | 1 | 1 | 0% | 2,221 | 3,503 | +58% | 0 | 0 | — |
case-18 | pass→pass | 14,383 | 9,663 | -33% | 1 | 1 | 0% | 2,372 | 3,241 | +37% | 0 | 0 | — |
case-19 | fail→pass | 10,901 | 4,212 | -61% | 1 | 1 | 0% | 1,973 | 2,383 | +21% | 0 | 0 | — |
case-20 | pass→pass | 16,712 | 15,044 | -10% | 1 | 1 | 0% | 3,002 | 4,140 | +38% | 0 | 0 | — |
case-21 | pass→pass | 18,112 | 13,286 | -27% | 1 | 1 | 0% | 3,095 | 3,853 | +24% | 0 | 0 | — |
case-22 | fail→fail | 16,950 | 16,924 | -0% | 1 | 1 | 0% | 2,902 | 4,452 | +53% | 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. 22 cases were attempted. The headline lift of +32 percentage points is the difference between those two pass rates over the 22 comparable cases.
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.
Other measured skills in the registry, with their headline benchmark lift.