PluginBench
Skill
Review
Audit score 70

cost-aware-llm-pipeline

affaan-m/everything-claude-code

Route models by complexity, track costs immutably, retry safely, and cache prompts to optimize LLM API spend.

What is cost-aware-llm-pipeline?

Cost-aware LLM pipeline provides patterns for controlling API costs while maintaining quality. It combines intelligent model routing (cheap models for simple tasks, expensive for complex ones), immutable budget tracking, narrow retry logic for transient errors only, and prompt caching to reduce token usage. Use this when building applications that call LLM APIs and need to stay within budget constraints.

  • Route between models (Haiku, Sonnet, Opus) based on task complexity thresholds
  • Track cumulative API costs immutably with frozen dataclasses, never mutating state
  • Implement narrow retry logic that fails fast on auth/validation errors but retries on transient failures
  • Cache long system prompts to avoid resending them and reduce token costs
  • Check budget limits before API calls and raise errors when exceeded
  • Log model selection decisions for threshold tuning and auditing

How to install cost-aware-llm-pipeline

npx skills add https://github.com/affaan-m/everything-claude-code --skill cost-aware-llm-pipeline
Prerequisites
  • Anthropic Python SDK (or equivalent for other LLM providers)
  • API keys for Claude or target LLM service
  • Understanding of token pricing for your models
Claude Code
Cursor
Windsurf
Cline

How to use cost-aware-llm-pipeline

  1. 1.Define complexity thresholds (text length, item count) for model selection
  2. 2.Create a CostTracker instance with your budget limit
  3. 3.Implement select_model() to route based on task complexity
  4. 4.Build cached messages with system prompt marked for caching
  5. 5.Call APIs using call_with_retry() to handle transient errors safely
  6. 6.Track each response by creating CostRecord and adding to tracker immutably
  7. 7.Check tracker.over_budget before processing batches to fail early

Use cases

Good for
  • Batch processing pipelines where cost accumulates across many API calls
  • Multi-model applications that need intelligent routing to balance cost and quality
  • Production systems requiring explicit budget guardrails and spend tracking
  • Applications with repetitive system prompts that benefit from caching
  • Services processing variable-complexity tasks (simple classification vs. complex analysis)
Who it's for
  • Backend engineers building LLM-powered applications
  • Data engineers processing batches with LLM APIs
  • DevOps/SREs managing cost constraints in production
  • Teams deploying multi-model architectures
  • Developers optimizing API spend without sacrificing quality

cost-aware-llm-pipeline FAQ

When should I use Haiku vs. Sonnet vs. Opus?

Start with Haiku (1x cost baseline) for simple tasks. Route to Sonnet (~4x cost) when text exceeds ~10k characters or item count exceeds ~30 items. Reserve Opus (~19x cost) for the most complex reasoning tasks. Tune thresholds based on your actual quality requirements and cost data.

Why use immutable cost tracking instead of just mutating a counter?

Immutable tracking makes debugging and auditing easier because each state is frozen and traceable. It prevents accidental mutations, enables easier parallelization, and makes it simpler to replay or reconstruct cost history.

What errors should I retry on?

Only retry on transient errors: APIConnectionError, RateLimitError, and InternalServerError. Fail immediately on AuthenticationError and BadRequestError—retrying won't help and wastes budget.

How much does prompt caching save?

Prompt caching saves both cost and latency. Cached tokens cost 90% less than regular tokens. Use it for system prompts over 1024 tokens that are reused across multiple requests.

Can I use this with OpenAI or other LLM providers?

Yes. The patterns (model routing, budget tracking, retry logic, caching) are provider-agnostic. Adapt the code to your provider's API and pricing structure.

Full instructions (SKILL.md)

Source of truth, from affaan-m/everything-claude-code.


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. 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-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. 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)

ModelInput ($/1M tokens)Output ($/1M tokens)Relative Cost
Haiku 4.5$0.80$4.001x
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