Skip to main content
skill Claude Code CX Codex Cursor GitHub Copilot

cost-aware-llm-pipeline — Claude skill: model routing and budgets

A skill for apps that call LLM APIs: picks a model by task complexity, tracks spend, caches prompts. Useful when your API bill keeps climbing.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add affaan-m/ECC --skill cost-aware-llm-pipeline -a claude-code
Open on GitHub

What cost-aware-llm-pipeline does

The skill lays out four techniques that compose into one pipeline. First, routing by complexity: select_model looks at text length and item count, hands simple work to a cheap model and only reaches for an expensive one past a threshold. The thresholds are plain constants, so you can tune them.

Second and third, cost tracking and retries. The tracker is a frozen dataclass: every call returns a new object with the record appended, so nothing mutates and the spend history stays easy to log and audit. Retries fire on transient failures only, network drops, rate limits, server errors, with exponential backoff. Auth and bad-request errors raise right away, since retrying those burns budget for nothing.

Fourth, prompt caching through cache_control, which keeps a long system prompt from being resent on every request. There is also a pricing table across model tiers and a list of anti-patterns: hardcoded model names, retrying every error, mutating tracker state. Worth installing if you run batch jobs or a service with a hard budget cap. For a one-off script call, the whole wrapper is overhead.

What it helps with

  • route simple requests to a cheap model and complex ones to a stronger model
  • keep API spend under a fixed budget limit
  • retry only transient failures instead of auth errors
  • cache a long system prompt across requests
  • log per-model spend for auditing

Example prompts for the agent

  • Set up model routing by task complexity in my pipeline
  • Add a budget limit and a cost tracker for API calls
  • Turn on prompt caching for the system prompt

How to install cost-aware-llm-pipeline

1Skills CLI (Vercel)

npx skills add affaan-m/ECC --skill cost-aware-llm-pipeline -a claude-code

2Manually: put the files in place

~/.claude/skills/cost-aware-llm-pipeline/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/cost-aware-llm-pipeline/

From the same set146

The whole set →
video-editing affaan-m AI-assisted workflow for editing, trimming, and enriching real footage. Connects raw recordings with FFmpeg cuts, Remotion overlays, and ElevenLabs voiceovers. Claude Code CX Codex Cursor +1 6,500installs docker-patterns affaan-m A skill with Dockerfile and Docker Compose patterns: local dev stacks, networking, volumes, container hardening. Claude Code CX Codex Cursor +1 6,300installs frontend-patterns affaan-m A skill for React and Next.js work: component patterns, state, data fetching, and render performance. Use it when building or reviewing UI. Claude Code CX Codex Cursor +1 5,900installs backend-patterns affaan-m A skill with backend patterns for Node.js, Express and Next.js API routes: layering, caching, transactions, error handling. Claude Code CX Codex Cursor +1 5,900installs coding-standards affaan-m Baseline cross-project coding conventions for naming, immutability, and clean code principles. Useful for code reviews and refactoring. Claude Code CX Codex Cursor +1 5,600installs api-design affaan-m Provides REST API design standards covering resource naming, status codes, pagination, and error payloads. Use it when creating or auditing API contracts. Claude Code CX Codex Cursor +1 5,500installs rust-testing affaan-m A skill for writing Rust tests: unit, integration, async, property-based, mocks and coverage. Useful when the project runs on TDD. Claude Code CX Codex Cursor +1 5,500installs laravel-security affaan-m This skill reviews Laravel authentication, Eloquent safety, CSRF, XSS, APIs, and production settings. Use it for security reviews or deployment checks. Claude Code CX Codex Cursor +1 5,400installs

Similar

migrate-ai-sdk-v6-to-v7 vercel Migrates applications from Vercel AI SDK 6.x to 7.0. It updates dependencies, fixes breaking API changes, and rewrites step-handling patterns. Claude Code CX Codex Cursor +1 5,500installs microsoft-docs official github Finds official Microsoft documentation, tutorials, and code samples for Azure, .NET, VS Code, and GitHub work. Use it when an agent needs a source tied to a specific technology or version. GitHub Copilot 14,881installs skill-creator official anthropics Creates and refines skills, then tests them with prompts, evaluations, and performance checks. Claude Code Claude.ai 414,180installs writing-for-agents Matt Pocock Guidance for writing skills and agent-facing documents. Use it when editing AGENTS.md, CLAUDE.md, or reference files reached from them. Claude Code 466,719installs media-use heygen-com Finds or generates media for HyperFrames videos, including voiceovers, music, cutouts, and color grades. Stores files locally in assets. Claude Code CX Codex Cursor +1 1,100,000installs mcp-builder official anthropics This skill walks through building an MCP server in TypeScript or Python, from reading the protocol spec to writing tests and evaluation questions. Claude Code Claude.ai 130,949installs subagent-driven-development Jesse Vincent This skill runs an implementation plan through fresh subagents for independent tasks and reviews each result. Use it for multi-step work in one session. Claude Code CX Codex 237,746installs orchestration stablyai Coordinates supervised Orca workers with task DAGs, decision gates, and threaded messages. Fits workflows that split work across multiple agents. Claude Code CX Codex Cursor +1 349,200installs

Questions about cost-aware-llm-pipeline

How do I install cost-aware-llm-pipeline in Claude?

Run npx skills add affaan-m/ECC --skill cost-aware-llm-pipeline -a claude-code. The skill lands at ~/.claude/skills/cost-aware-llm-pipeline/SKILL.md.

What does cost-aware-llm-pipeline do?

It combines model routing by complexity, immutable cost tracking, retries limited to transient errors, and prompt caching into one pipeline.

Which platforms support the skill?

Claude, Codex, Cursor, GitHub Copilot, Gemini CLI and OpenCode. On Copilot the install goes through gh skill install affaan-m/ECC cost-aware-llm-pipeline.

Source text

SKILL.md · MIT
---
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.

```python
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.

```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. Narrow Retry Logic

Retry only on transient errors. Fail fast on authentication or bad request errors.

```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. Prompt Caching

Cache long system prompts to avoid resending them on every request.

```python
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:

```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
```

## Pricing Reference (2026)

| Model | Input ($/1M tokens) | Output ($/1M tokens) | Relative Cost |
|-------|---------------------|----------------------|---------------|
| Haiku 3.5 (legacy) | $0.80 | $4.00 | 0.8x |
| Haiku 4.5 | $1.00 | $5.00 | 1x |
| Sonnet 5 | $2.00 | $10.00 | 2x |
| Sonnet 4.6 | $3.00 | $15.00 | 3x |
| Opus 4.8 | $5.00 | $25.00 | 5x |
| Fable 5 / Mythos 5 | $10.00 | $50.00 | 10x |
| Opus 4.0 / 4.1 (legacy) | $15.00 | $75.00 | 15x |

## 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

© affaan-m · MIT · affaan-m/ECC

See also

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor