cost-aware-pipeline

Cost-aware LLM pipeline patterns for optimal model routing, narrow retry strategies, and prompt caching. Reduces API costs 40-70% through intelligent model selection, targeted retries, and cache-friendly prompt structures. Use when: (1) Building multi-model pipelines, (2) Optimizing API costs, (3) Designing retry strategies for LLM calls, (4) Implementing prompt caching, (5) Choosing between haiku/sonnet/opus for sub-tasks.

Best use case

cost-aware-pipeline is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Cost-aware LLM pipeline patterns for optimal model routing, narrow retry strategies, and prompt caching. Reduces API costs 40-70% through intelligent model selection, targeted retries, and cache-friendly prompt structures. Use when: (1) Building multi-model pipelines, (2) Optimizing API costs, (3) Designing retry strategies for LLM calls, (4) Implementing prompt caching, (5) Choosing between haiku/sonnet/opus for sub-tasks.

Teams using cost-aware-pipeline should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/cost-aware-pipeline/SKILL.md --create-dirs "https://raw.githubusercontent.com/stevengonsalvez/agents-in-a-box/main/toolkit/packages/skills/cost-aware-pipeline/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/cost-aware-pipeline/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How cost-aware-pipeline Compares

Feature / Agentcost-aware-pipelineStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Cost-aware LLM pipeline patterns for optimal model routing, narrow retry strategies, and prompt caching. Reduces API costs 40-70% through intelligent model selection, targeted retries, and cache-friendly prompt structures. Use when: (1) Building multi-model pipelines, (2) Optimizing API costs, (3) Designing retry strategies for LLM calls, (4) Implementing prompt caching, (5) Choosing between haiku/sonnet/opus for sub-tasks.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Cost-Aware LLM Pipeline

## Model Routing Strategy

Route tasks to the cheapest model that can handle them reliably.

### Pricing Reference (per 1M tokens, USD)

| Model | Input | Output | Relative Cost |
|-------|-------|--------|---------------|
| Haiku | $0.80 | $4.00 | 1x (baseline) |
| Sonnet | $3.00 | $15.00 | ~4x |
| Opus | $15.00 | $75.00 | ~19x |

### Routing Rules

| Task Complexity | Route To | Examples |
|-----------------|----------|----------|
| **Simple** (< 100 lines, clear pattern) | Haiku | File renaming, simple search, format conversion, status checks |
| **Moderate** (100-500 lines, some judgment) | Sonnet | Code review, test writing, refactoring, documentation |
| **Complex** (500+ lines, deep reasoning) | Opus | Architecture design, debugging subtle issues, multi-file refactoring |
| **Creative** (open-ended, high quality bar) | Opus | System design, novel algorithms, critical security review |

### Implementation with Claude Code Agent Tool

```python
# In agent orchestration, specify model based on task complexity
def route_to_model(task_description: str, estimated_complexity: str) -> str:
    """Return model parameter for Agent tool."""
    routing = {
        "simple": "haiku",
        "moderate": "sonnet",
        "complex": "opus",
        "creative": "opus",
    }
    return routing.get(estimated_complexity, "sonnet")
```

When spawning sub-agents:
- Use `model: "haiku"` for Explore agents doing simple file searches
- Use `model: "sonnet"` (default) for most implementation work
- Use `model: "opus"` only for architecture reviews, complex debugging, distinguished-engineer tasks

### Cost Savings Examples

| Scenario | Before (all Opus) | After (routed) | Savings |
|----------|-------------------|----------------|---------|
| 10 file searches | $0.15 | $0.008 (haiku) | 95% |
| 5 code reviews | $0.75 | $0.20 (sonnet) | 73% |
| 1 architecture review | $0.15 | $0.15 (opus) | 0% |
| **Typical session** | **$1.05** | **$0.36** | **66%** |

## Narrow Retry Strategy

When an LLM call fails, retry intelligently — not blindly.

### Principles

1. **Retry the minimum scope** — Don't re-run the entire pipeline, retry only the failed step
2. **Escalate model on retry** — If haiku fails, retry with sonnet, not haiku again
3. **Add context on retry** — Include the error in the retry prompt
4. **Max 2 retries** — If it fails 3 times, escalate to human

### Retry Escalation Ladder

```
Attempt 1: haiku (cheapest)
    | fail
    v
Attempt 2: sonnet + error context
    | fail
    v
Attempt 3: opus + error context + examples
    | fail
    v
Escalate to human
```

### Implementation

```python
RETRY_LADDER = [
    {"model": "haiku", "extra_context": None},
    {"model": "sonnet", "extra_context": "Previous attempt failed: {error}"},
    {"model": "opus", "extra_context": "Two attempts failed. Errors: {errors}. Please reason carefully."},
]

async def call_with_retry(prompt: str, task: str) -> str:
    errors = []

    for attempt in RETRY_LADDER:
        try:
            result = await call_llm(
                model=attempt["model"],
                prompt=prompt,
                extra_context=attempt["extra_context"].format(
                    error=errors[-1] if errors else "",
                    errors="; ".join(errors)
                ) if attempt["extra_context"] and errors else prompt,
            )
            return result
        except Exception as e:
            errors.append(str(e))

    raise EscalationNeeded(f"Failed after {len(RETRY_LADDER)} attempts: {errors}")
```

## Prompt Caching Strategies

Structure prompts to maximize cache hits and reduce costs.

### Cache-Friendly Prompt Structure

```
+-------------------------------------+
| STATIC SYSTEM PROMPT (cached)       |  <- Rarely changes, high cache hit rate
| - Agent instructions                |
| - Tool definitions                  |
| - Project context (CLAUDE.md)       |
+-------------------------------------+
| SEMI-STATIC CONTEXT (cached)        |  <- Changes per-task, not per-turn
| - File contents being worked on     |
| - Relevant documentation            |
| - Test results                      |
+-------------------------------------+
| DYNAMIC CONTENT (not cached)        |  <- Changes every turn
| - User message                      |
| - Latest tool results               |
| - Conversation tail                 |
+-------------------------------------+
```

### Key Principles

1. **Front-load static content** — Put rarely-changing content at the start of the prompt
2. **Batch file reads** — Read all needed files at once, not one at a time
3. **Minimize prompt churn** — Avoid reformatting the same content differently each turn
4. **Use system prompts for stable context** — CLAUDE.md, agent definitions, skill bodies

### Cost Impact of Caching

With Anthropic's prompt caching:
- Cached tokens cost 90% less on input
- Cache write costs 25% more (one-time)
- Cache TTL: 5 minutes (refreshed on use)

**Strategy**: Keep system prompt + project context stable across turns. Only the user message and tool results should change.

## Budget Planning

### Estimating Session Costs

| Session Type | Typical Tokens | Estimated Cost |
|-------------|----------------|----------------|
| Quick fix (5 min) | 50K in / 10K out | $0.15 - $0.90 |
| Feature implementation (30 min) | 500K in / 100K out | $1.50 - $9.00 |
| Deep debugging (1 hr) | 1M in / 200K out | $3.00 - $18.00 |
| Multi-agent swarm (2 hr) | 5M in / 1M out | $15.00 - $90.00 |

### Setting Budgets

```bash
# Per-session cost cap (used by agent-ops skill)
export AGENT_COST_CAP=5.00

# Per-agent cost cap for sub-agents
export SUBAGENT_COST_CAP=1.00

# Warning threshold (fraction of cap)
export AGENT_COST_CAP_WARN=0.80
```

### Monitoring

```bash
# View today's costs
grep "$(date +%Y-%m-%d)" "$HOME/{{TOOL_DIR}}/metrics/costs.jsonl" | \
  python3 -c "import sys,json; rows=[json.loads(l) for l in sys.stdin]; \
  print(f'Sessions: {len(set(r[\"session_id\"] for r in rows))}'); \
  print(f'Total: \${sum(r[\"estimated_cost_usd\"] for r in rows):.4f}')"
```

Related Skills

reflect:cost

8
from stevengonsalvez/agents-in-a-box

Report reflect drain spend over a time window — tokens split by cached (cache_read), uncached writes (cache_creation), and io (input+output), with a $ estimate, grouped by day / outcome / model / transcript. Reads the drainer's cost log and surfaces outlier runs and cache-reuse health (the 41.5M-token failure mode = low cache reuse + high cache writes). Use to answer "what is reflection costing me" for the last day / week.

workflow

8
from stevengonsalvez/agents-in-a-box

Guide through structured delivery workflow with plan, implement, validate phases

webapp-testing

8
from stevengonsalvez/agents-in-a-box

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

validate

8
from stevengonsalvez/agents-in-a-box

Verify implementation against specifications

ui-ux-pro-max

8
from stevengonsalvez/agents-in-a-box

UI/UX design intelligence. 67 styles, 96 palettes, 57 font pairings, 25 charts, 13 stacks (React, Next.js, Vue, Svelte, Astro, Nuxt, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui, Jetpack Compose). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient.

tui-style-guide

8
from stevengonsalvez/agents-in-a-box

TUI style guide for consistent terminal interface design

token-usage

8
from stevengonsalvez/agents-in-a-box

Show Claude Code token usage across sessions — daily, weekly, per-project, and per-session breakdowns. Parses {{HOME_TOOL_DIR}}/projects/**/*.jsonl for consumption data. Use when the user asks about token usage, costs, how many tokens were used, session statistics, or wants a usage report.

tmux-status

8
from stevengonsalvez/agents-in-a-box

Show status of all tmux sessions including dev environments, spawned agents, and running processes

tmux-monitor

8
from stevengonsalvez/agents-in-a-box

Monitor and report status of all tmux sessions including dev environments, spawned agents, and running processes. Uses tmuxwatch for enhanced visibility.

tmux-message

8
from stevengonsalvez/agents-in-a-box

Reliable peer-to-peer message delivery to other Claude Code instances via tmux send-keys. Use as a fallback when claude-peers MCP send_message fails to surface in the receiver's inbox (delivered server-side but receiver never picks it up — observed behaviour). Also use when sending a directive to a known Claude Code TUI session by tmux session name or fuzzy hint, or when injecting a multi-line directive into a peer's prompt and submitting it. Trigger phrases — "claude-peers fallback", "tmux send-keys", "send to peer via tmux", "inject directive", "deliver to nanoclaw/hermes peer", "peer message". Tmux-only — won't reach peers running outside tmux.

test-driven-development

8
from stevengonsalvez/agents-in-a-box

Use when implementing any feature or bugfix, before writing implementation code. Enforces RED-GREEN-REFACTOR cycle with test-first approach.

test-ainb

8
from stevengonsalvez/agents-in-a-box

Run tests for the ainb (agents-in-a-box) Rust workspace via a 5-layer strategy — unit, insta snapshot, mock-plugin compositing, real-plugin spawn, vhs recording. Wraps cargo + insta + vhs into one CLI. Use when Stevie says "/test-ainb", "test ainb", "run ainb tests", "snapshot <component>", "regenerate vhs tapes", or any phrasing about validating ainb test layers. The skill autodetects which ainb-tui worktree the cwd sits in and dispatches to scripts/run.sh.