Back to list
hgeldenhuys

cost-optimization

by hgeldenhuys

1🍴 0📅 Jan 24, 2026

SKILL.md


name: cost-optimization description: Manage Claude Code API costs - token strategies, model selection, monitoring. Use when concerned about API spend, optimizing token usage, choosing models for tasks, or setting up cost monitoring. Covers /cost command, batching strategies, and budget management. version: 1.0.0 author: Claude Code SDK tags: [cost, optimization, tokens, budget]

Cost Optimization

Reduce Claude Code API costs while maintaining quality through smart token management, model selection, and monitoring.

Quick Reference

StrategyImpactEffort
Use Haiku for simple tasksHighLow
Batch related operationsMediumLow
Use /compact strategicallyMediumLow
Reduce context sizeHighMedium
Efficient promptingMediumMedium

Understanding Costs

How API Costs Work

Claude Code costs are based on tokens:

  • Input tokens: Everything Claude reads (prompts, files, context)
  • Output tokens: Everything Claude generates (responses, code)
  • Cached tokens: Reduced rate for repeated context

Model Pricing (Relative)

ModelInput CostOutput CostBest For
Haiku$$Simple tasks, exploration
Sonnet$$$$General development (default)
Opus$$$$$$$$$$Complex reasoning, architecture

Rule of thumb: Opus is ~15x more expensive than Haiku for the same tokens.

What Consumes Tokens

ActivityToken ImpactOptimization
Reading filesHighRead selectively, use grep
Long conversationsCumulativeUse /compact regularly
Tool outputsVariableRequest summaries
Code generationMediumBe specific in requests
Error messagesLowN/A

The /cost Command

Basic Usage

> /cost

Shows:

  • Session token usage (input/output)
  • Estimated cost for current session
  • Context window usage percentage

When to Check

  • Before starting large tasks
  • After reading multiple files
  • When responses slow down
  • Every 15-20 exchanges
  • Before deciding to /compact vs /clear

Interpreting Results

MetricGoodConcernAction
Context usage<50%>70%Consider /compact
Session costVariesUnexpected spikeReview recent operations
Output ratioBalancedOutput >> InputResponses too verbose

The /stats Command

View usage statistics over time:

> /stats

Date Range Filtering (2.1.6+): Press r to cycle between:

  • Last 7 days
  • Last 30 days
  • All time

Shows:

  • Total tokens used (input/output)
  • Number of sessions
  • Cost breakdown by period
  • Model usage distribution

MCP Tool Search Auto Mode (2.1.7+)

When you have many MCP tools configured, their descriptions can consume significant context space. Version 2.1.7 introduces automatic MCP tool deferral:

How It Works

  • Trigger: When MCP tool descriptions exceed 10% of context window
  • Behavior: Tools are deferred and discovered via MCPSearch instead of loaded upfront
  • Default: Enabled for all users

Cost Impact

MCP ToolsWithout Auto ModeWith Auto ModeSavings
10-20 tools~2-5% context~1% context50-80%
50+ tools~10-20% context~1% context90%+

Disabling Auto Mode

If you need all MCP tools loaded upfront (e.g., for specific workflows):

// settings.json
{
  "disallowedTools": ["MCPSearch"]
}

Note: Only disable if you have few MCP tools or specifically need immediate tool availability.

Token Reduction Strategies

1. Selective File Reading

Expensive:

> Read the entire src/ directory to understand the codebase

Efficient:

> @src/api/users.ts @src/types/user.ts - I need to modify the user API

2. Use Grep Before Read

Expensive:

> Find all files that use the AuthService class
[Claude reads many files to find them]

Efficient:

> grep for "AuthService" in src/, then I'll look at the most relevant ones

3. Targeted @ Mentions

PatternToken CostUse Case
@src/Very HighAvoid unless necessary
@src/api/HighWhen exploring a module
@src/api/users.tsLowSpecific file work
@src/api/users.ts:50-100Very LowSpecific section

4. Limit Output Verbosity

> Analyze this file and give me a brief summary of the key functions

vs

> Explain every line of this file

Expensive (multiple turns):

> Read file A
> Now modify line 10
> Now read file B
> Modify line 20

Efficient (single turn):

> In file A, update the getUserById function to handle null.
> In file B, add the new UserNotFound error type.
> Run the tests after both changes.

/compact vs /clear

When to /compact

Use /compact when:

  • Context is 70%+ full
  • You want to continue the same task
  • Need to preserve decisions and progress
  • Responses are slowing down

Cost impact: Reduces ongoing costs by 50-80%

When to /clear

Use /clear when:

  • Switching to unrelated task
  • Previous context is irrelevant
  • Starting fresh approach
  • Maximum cost savings needed

Cost impact: Resets to zero (but loses all context)

Decision Matrix

SituationCommandReasoning
Same task, full context/compactPreserve progress
Different project/clearIrrelevant context
Stuck on approach/clearFresh perspective
After major milestone/compactKeep decisions
Testing something new/clearClean state

Model Selection

Quick Guide

Task TypeRecommended ModelWhy
File explorationHaikuFast, cheap, sufficient
Simple editsHaikuStraightforward
General codingSonnetBalanced (default)
Bug fixingSonnetNeeds reasoning
Architecture designOpusDeep analysis
Security reviewOpusCritical thinking
Complex refactoringOpusMulti-file reasoning

Switching Models

Set model in skill frontmatter:

---
model: haiku
---

Or request model in prompt:

> Using Haiku, list all TypeScript files in src/

Cost Comparison Example

Task: Review 10 files for security issues

ApproachEstimated Cost
Opus reviews all$$$$$
Haiku scans, Opus reviews flagged$$
Sonnet reviews all$$$

Best strategy: Use Haiku for initial scan, escalate to Opus for detailed review of potential issues.

Efficient Prompting

Reduce Token Count

VerboseConciseSavings
"Could you please"[Just ask]3-4 tokens
"I want you to"[State task]4-5 tokens
Long explanationsBullet points20-50%
Repeated context@ mentionsSignificant

Be Specific

Token-heavy:

> I have this function that gets users from the database and I want
> to add some caching because it's being called too often and making
> the app slow. Can you help me figure out a good caching strategy?

Efficient:

> Add Redis caching to getUserById in @src/api/users.ts.
> TTL: 5 minutes. Invalidate on user update.

Use Checklists

> Implement user search:
> - [ ] Add search endpoint
> - [ ] Add debounced input
> - [ ] Handle empty results
> Run tests when done.

Clearer than long paragraph descriptions.

Batching Strategies

Batch Similar Operations

Instead of multiple turns:

> Add logging to function A
[response]
> Add logging to function B
[response]
> Add logging to function C

Single turn:

> Add consistent logging to functions A, B, and C in @src/utils.ts
> Use format: logger.info("[FunctionName] action", { params })

Batch Read-Modify Cycles

> Review @src/api/*.ts for missing error handling.
> Add try-catch with proper logging to any functions that need it.
> Summarize changes made.

When NOT to Batch

  • Complex, interdependent changes
  • When you need to verify each step
  • Exploratory work
  • Learning a new codebase

Budget Management

Setting Expectations

Session TypeTypical Cost Range
Quick fix$
Feature implementation$$-$$$
Large refactor$$$-$$$$
Architecture session (Opus)$$$$$

Cost Controls

  1. Monitor actively: Check /cost regularly
  2. Set mental limits: "I'll compact at $X"
  3. Use appropriate models: Haiku for exploration
  4. Plan sessions: Know scope before starting

Daily/Weekly Tracking

> /cost
[Note the total]

Track across sessions to understand your patterns.

Subagent Cost Efficiency

Why Subagents Help

Subagents have isolated context:

  • Main context stays lean
  • Exploratory work doesn't pollute
  • Can use cheaper models

Cost-Efficient Agent Pattern

---
name: explorer
model: haiku
tools: Read, Glob, Grep
---
Explore and summarize. Return only key findings.

Delegation Examples

TaskAgent ModelReturn
Find all API routesHaikuRoute list
Analyze dependenciesHaikuSummary
Review for patternsSonnetFindings
Deep security reviewOpusDetailed report

Common Wasteful Patterns

PatternWhy WastefulBetter Approach
Reading entire directoriesMassive token costGrep first, read specific
Verbose explanationsUnnecessary outputRequest concise
Repeating contextAlready in historyUse @ mentions
Not using /compactGrowing costsCompact at 70%
Opus for everythingExpensive overkillMatch model to task
Long debugging sessionsCumulative costClear and restart

Reference Files

FileContents
TOKEN-STRATEGIES.mdDetailed token reduction techniques
MODEL-SELECTION.mdModel comparison and selection guide
MONITORING.mdCost tracking and budget management

Quick Decisions

SituationAction
Context at 70%/compact
Simple file explorationUse Haiku
Need deep analysisUse Opus (worth the cost)
Unexpected high costCheck recent operations
Switching tasks/clear to save costs
Debugging loopClear and try fresh approach

Score

Total Score

50/100

Based on repository quality metrics

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

0/10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

0/5

Reviews

💬

Reviews coming soon