Claude Cost Optimizer

September 6, 2026 · View on GitHub

GitHub stars GitHub forks License Last Commit

Save 30-90% on Claude Code costs with an installable skill, CLI tools, and 12 deep-dive guides.

30-60% is the typical result for a mixed real workload. Up to 90% is the ceiling when you stack every lever -- prompt caching, Batch API, model routing, and context discipline -- against an unoptimized all-Opus baseline. Every number is sourced: see How far can you actually go?.

Install

Claude Code (official plugin system):

/plugin marketplace add Sagargupta16/claude-cost-optimizer
/plugin install cost-mode@claude-cost-optimizer

Multi-agent (Cursor, Cline, Codex, 40+ agents):

npx skills add Sagargupta16/claude-cost-optimizer

Then activate in any session:

/cost-mode              # Standard (40-60% output token reduction)
/cost-mode lite         # Professional brevity (20-40% output reduction)
/cost-mode strict       # Telegraphic, max savings (60-70% output reduction)
/cost-mode off          # Resume normal behavior

What cost-mode Does

FeatureHow It Saves Tokens
Strips fillerDrops pleasantries, hedging, restating your question, trailing summaries
Suggests cheaper models"Haiku handles this -- /model haiku" for simple tasks
Suggests CLI tools"Use prettier/eslint --fix directly" instead of burning LLM tokens
Session awarenessReminds to /compact after 20+ turns, fresh sessions for new tasks
Minimal code genDiffs over rewrites, no obvious comments, no speculative error handling
Auto-deactivatesFull clarity for security warnings, destructive ops, and when you're confused

Technical accuracy is never sacrificed. Code in commits and PRs is written normally.

Full skill documentation


Rate your setup

claude-rate runs on your filesystem -- no signup, no GitHub upload, no network round-trip. Pick whichever runner fits your shell:

# curl one-shot (no Node, no install)
curl -sSL https://raw.githubusercontent.com/Sagargupta16/claude-cost-optimizer/main/tools/claude-rate/install.sh | sh -s -- .

# curl, persistent install
curl -sSL https://raw.githubusercontent.com/Sagargupta16/claude-cost-optimizer/main/tools/claude-rate/install.sh | sh -s -- --install

Add --fix to print copy-pasteable fix commands, --strict to fail CI when the grade drops below B, or --json for machine-readable output. See tools/claude-rate/README.md for the full breakdown.

The local rater works on private and uncommitted repos and inspects things the web analyzer can't reach: settings.local.json, .claudeignore coverage gaps vs files actually on disk, and secrets in your working tree. The web analyzer applies the same 7-category rubric (CLAUDE.md, .claudeignore, settings, MCP, hooks, security, skills/agents/commands) to any public repo.

Public repos -- web tools

ToolWhat It Does
Repo AnalyzerPaste a GitHub URL to get a cost audit, grade (A+ to F), and recommendations
Cost CalculatorEstimate monthly spend with interactive charts: per-turn cost curve, savings breakdown, model comparison
Badge CheckerScore your setup and get a shields.io badge for your repo

Before vs After

Worked example, 30-turn session, Opus 5 (identical math on Opus 4.8 -- same $5/$25). The dollar figures are arithmetic from the posted rates, not a metered bill:

BEFORE (no optimization):                 AFTER (5 minutes of setup):
  CLAUDE.md:        6,200 chars (truncated)  CLAUDE.md:        2,800 chars (under limit)
  .claudeignore:    missing                   .claudeignore:    12 patterns
  MCP servers:      6 active                  MCP servers:      2 active
  System prompt:    ~15,000 tokens/turn       System prompt:    ~5,500 tokens/turn
  Session cost:     \$2.85                     Session cost:     \$1.12
  Monthly (3x/day): \$188.10                   Monthly (3x/day): \$73.92

  Savings: \$114.18/month (61%)

How Far Can You Actually Go?

Short answer: 30-60% is what a typical mixed workload saves. Up to ~90% is the ceiling when every lever stacks against a naive all-Opus, no-cache, verbose baseline. The headline numbers below are each real and sourced -- but each one applies only to the favorable slice of your spend, so the compound rarely holds across an entire real workload. Treat 90% as a ceiling, not a promise.

LeverPublished savingsApplies toSource
Prompt cachingup to 90% cost (97.5% on Fable 5.1), 85% latencycached input only (0.1x input price; 0.025x on Fable 5.1 / Mythos 5.1)Anthropic: Prompt caching, pricing docs
Batch APIflat 50% off input and output, stacks with cachingany async (24h) workAnthropic: Message Batches API, batch docs
Model routing~80% (Opus->Haiku is a flat 5x ratio); RouteLLM up to 85% at 95% qualitytasks a cheaper model handles wellRouteLLM (arXiv 2406.18665), LMSYS
Context management84% fewer tokens in a 100-turn evallong agentic sessionsAnthropic: Context management
Subscription vs API~90%+ for heavy users (Pro $20 / Max $100-200 flat)power users vs pay-as-you-goksred cost tracker (n=1)

The honest read

  • "up to 90%" is a ceiling, not a typical result. Anthropic itself publishes 90% for caching alone, and the levers genuinely multiply against an unoptimized baseline. But each 90% is a best case on its favorable slice (cached input for caching; conversational traffic for routing), so a whole mixed workload lands well below the sum.
  • The stacked total has no source. Each lever above is individually sourced; the combined figure is not, and this repo holds no controlled multi-lever measurement. For a number that applies to your workload, run claude-rate on your own repo and price only the levers you can apply.
  • The cost-mode skill on its own delivers 30-60% -- it does output-token reduction and model-routing hints, not batch/caching/subscription. The 90% ceiling needs the full playbook in the guides, not just the skill.
  • Caching and batch are the firmest floors (first-party Anthropic pricing; batch is a documented flat 50% that provably stacks with caching). Routing and subscription savings are the most workload-sensitive.

Prices verified against the pricing reference below (2026-09-05). Cache hit = 0.1x base input on every model except Fable 5.1 and Mythos 5.1, which read at 0.025x; Batch = 50% off both input and output.


Quick Start (5 Minutes, No Skill Needed)

Even without installing the skill, these 5 changes cut costs immediately:

#StrategySavingsGuide
1Keep CLAUDE.md under 4,000 characters -- content beyond 4K is silently truncated10-20%Context Optimization
2Use Haiku for simple tasks (--model haiku) -- 5x cheaper than Opus20-40%Model Selection
3Use Plan Mode before coding -- prevents wasted iterative cycles15-25%Workflow Patterns
4Add .claudeignore -- stop Claude from reading node_modules, dist, lock files5-15%Context Optimization
5Delegate to subagents -- isolate expensive searches from main context20-40%Workflow Patterns

Full walkthrough: Getting Started in 5 Minutes


Skills Roadmap

cost-mode is the first skill. More are planned:

SkillStatusWhat It DoesCost Impact
cost-modeLiveConcise responses, model routing suggestions, session awareness30-60% (skill alone)
claudeignore-genPlannedAuto-generates .claudeignore based on your project's tech stack5-15% input reduction
context-compressPlannedRewrites your CLAUDE.md to be shorter while keeping all essential info10-20% input reduction
cache-optimizerPlannedDetects cache-busting patterns and suggests fixes to maximize prompt cache hits10-25% input reduction
budget-guardPlannedPer-session and per-day spending limits with warnings before you blow past themPrevents overspend

Want to build one? Skills are just SKILL.md files -- see CONTRIBUTING.md and the skills/cost-mode/ directory for the pattern.


Guides

12 deep-dive guides covering every optimization area:

GuideWhat You'll Learn
00 - Getting StartedZero to optimized in 5 minutes -- the essential setup
01 - Understanding CostsHow billing works, what costs the most, where money goes
02 - Context OptimizationReduce input tokens: CLAUDE.md, .claudeignore, file reads
03 - Model SelectionWhen to use Opus vs Sonnet vs Haiku (with decision tree)
04 - Workflow PatternsPlan mode, subagents, commands, batch operations
05 - Team BudgetingPer-developer budgets, cost tracking, ROI calculation
06 - Access Methods & PricingCompare API vs Bedrock vs Vertex AI vs Claude Code pricing
07 - MCP & Agent Cost ImpactMCP server overhead, subagent costs, Agent SDK patterns
08 - Prompt Caching Deep DiveCache mechanics, TTL economics, maximizing hit rates, ROI math
09 - Subscription Plan ValueChoose the right plan, maximize allowance, upgrade/downgrade signals
10 - Three-Tier Task RoutingSkip the LLM for Tier 0 tasks, route cheap tasks to Haiku, save Opus for complex work
11 - Speed vs CostMake Claude faster without burning money -- free latency levers first, Fast Mode economics last

Also: Visual Diagrams (Mermaid flowcharts) | One-Page Cheatsheet


Templates

Copy-paste configs that are already optimized:

CLAUDE.md: Minimal | Standard | Comprehensive | Monorepo

By Stack: React+Vite | Next.js | FastAPI | MERN | Terraform | Go | Rust | Django | Rails | Spring Boot

Settings: Cost-Conscious | Balanced | Performance-First

Commands: /cost-check | /budget-mode | /quick-fix | /optimize


CLI Tools

The 8 tools in tools/, plus the budget hooks in hooks/. Full tools documentation

ToolWhat It Does
claude-rateGrade your local setup on the 7-category rubric (recommended entry point)
Token EstimatorEstimate token count and cost for any file
Usage AnalyzerFind cost hotspots across your sessions
Badge GeneratorGrade your project config (A+ to F) from the CLI
MCP Cost ServerIn-session cost estimation via MCP
VS Code ExtensionToken count and cost in the status bar
GitHub ActionAutomated cost audit on PRs
/optimize CommandClaude Code custom command that audits the current project
Budget HooksTrack tool calls, log costs, warn at thresholds

Pricing Reference

Verified 2026-09-05 against Anthropic's pricing, models overview, and model deprecations pages.

ModelInput / 1MOutput / 1MCache Hit / 1M5m Cache Write / 1M1h Cache Write / 1MContextMax OutputMin cacheable prompt
Fable 5.1 (highest capability)$10.00$50.00$0.25$12.50$20.001M128K512
Mythos 5.1 (limited, Glasswing)$10.00$50.00$0.25$12.50$20.001M128K512
Fable 5 (legacy)$10.00$50.00$1.00$12.50$20.001M128K512
Mythos 5 (limited, Glasswing)$10.00$50.00$1.00$12.50$20.001M128K512
Opus 5 (Opus flagship)$5.00$25.00$0.50$6.25$10.001M128K512
Opus 4.8 (legacy)$5.00$25.00$0.50$6.25$10.001M128K1,024
Opus 4.7$5.00$25.00$0.50$6.25$10.001M128K2,048
Opus 4.6$5.00$25.00$0.50$6.25$10.001M128K4,096
Opus 4.5$5.00$25.00$0.50$6.25$10.00200K64K4,096
Opus 4.1 (retired 2026-08-05, still on Bedrock + Google Cloud)$15.00$75.00$1.50$18.75$30.00200K32K1,024
Sonnet 5 (Sonnet flagship)$2.00$10.00$0.20$2.50$4.001M128K1,024
Sonnet 4.6$3.00$15.00$0.30$3.75$6.001M64K1,024
Sonnet 4.5$3.00$15.00$0.30$3.75$6.00200K64K1,024
Haiku 4.5$1.00$5.00$0.10$1.25$2.00200K64K4,096
Mythos Preview (deprecated, no retirement date)$25.00$125.00$2.50$31.25$50.001M--2,048

Mythos 5.1's rates come from the pricing page; its context window, max output and cache floor are not listed there. The Fable 5.1 model page states Mythos 5.1 "shares Claude Fable 5.1's specifications and pricing", and the prompt-caching page lists it at the 512-token floor.

Opus 5 (claude-opus-5, GA 2026-07-24) is the current Opus flagship and Anthropic's recommended default for complex agentic coding. It costs the same $5/$25 as Opus 4.8, so the upgrade is free at the posted rate -- see what actually changes before you flip the model string. 1M context on Fable 5.1, Mythos 5.1, Fable 5, Mythos 5, Opus 5, Opus 4.8, Opus 4.7, Opus 4.6, Sonnet 5, and Sonnet 4.6 bills at standard rates across the full window (no long-context premium). Sonnet 5 (claude-sonnet-5, GA 2026-06-30) is $2/$10 per MTok permanently -- the launch rate was labelled introductory through 2026-08-31, but Anthropic made it standard and cancelled the increase to $3/$15, so Sonnet 5 sits 60% below Opus 5. Batch API: 50% off both input and output -- Opus 5 batch is $2.50/$12.50 (up to 300K output via the output-300k-2026-03-24 beta). Fast Mode (research preview, Opus 5 and Opus 4.8 only): 2x ($10/$50) on both, up to 2.5x output tokens/sec. Regional endpoints (Bedrock / Vertex AI / Claude API inference_geo: "us" for 4.6+ models): +10%. Subscriptions: Pro $20/mo (or $200/yr ≈ $16.67/mo, ~17% off), Max 5x $100/mo, Max 20x $200/mo. Web search: $10 per 1,000 searches plus token costs. Web fetch: free beyond token costs. Code execution: free with web search/fetch; otherwise 1,550 free hours/month then $0.05/hour per container. Bash tool: +325 input tokens on Opus 5 / 4.8 / 4.7 (+244 on Opus 4.6 and earlier). Text editor tool: +700 input tokens.

Minimum cacheable prompt is a real cost lever. A cache_control block below the model's threshold is silently ignored -- you pay full input price every turn and see no error. Opus 5 halves the Opus 4.8 threshold from 1,024 to 512 tokens, so system prompts and CLAUDE.md files that never cached on 4.8 start caching on 5. Haiku 4.5, Opus 4.6, and Opus 4.5 sit at 4,096, the worst of the current lineup.

Opus 5 / 4.8 / 4.7 tokenizer caveat: The tokenizer introduced with Opus 4.7 may use up to 35% more tokens for the same fixed text. Effective per-task cost is higher than posted pricing suggests -- factor this into budgets, especially when comparing against Opus 4.6 / Sonnet 4.6.

Fast Mode (research preview): Now Opus 5 and Opus 4.8 only, via the fast-mode-2026-02-01 beta header (speed: "fast"). Both are 2x ($10/$50 per MTok). Up to 2.5x more output tokens/second; the speed gain is on output tokens/sec, not time-to-first-token. Opus 4.7 now returns an error on speed: "fast" with no fallback, and Opus 4.6 silently runs at standard speed and standard rates (usage.speed comes back "standard") -- if you were paying 6x for Fast Mode on either, that option is gone. Claude API + Managed Agents only: not on Claude Platform on AWS, Bedrock, Vertex AI, Microsoft Foundry, Batch API, or Priority Tier. Switching speeds invalidates prompt cache. Join the waitlist.

Fable 5 / Mythos 5 (GA 2026-06-09): Anthropic's Mythos-class tier above Opus, at 2x Opus 5's price ($10/$50). Same specs for both: 1M context at standard rates, 128K max output, always-on adaptive thinking (control depth with effort; thinking: disabled not supported), 4.7-generation tokenizer. Fable 5 is GA everywhere (Claude API, Claude Platform on AWS, Bedrock, Vertex AI, Microsoft Foundry) and includes safety classifiers that can decline requests -- a refusal returns HTTP 200 with stop_reason: "refusal", pre-output refusals are not billed, and the beta fallbacks parameter plus fallback credit make retrying on another model cheap. Mythos 5 is the same model without the classifiers, limited to approved Project Glasswing customers. No Fast Mode on either; Batch API supported ($5/$25). Requires 30-day data retention (no zero-data-retention option).

Mythos Preview: superseded by Mythos 5 and deprecated -- still functional, no longer recommended, and no retirement date is published. The invite-only defensive-cybersecurity research preview under Project Glasswing.

Looking for older model IDs and pricing? See the Legacy & Retired Models section below for migration context.

Migrating to Opus 5

Opus 5 is the same price as Opus 4.8, but it is not a drop-in swap of the model string. Four things change your bill or break your request:

ChangeWhy it matters for cost
Thinking is ON by defaultOmit thinking and Opus 5 thinks adaptively. Reasoning tokens bill as output at $25/1M, and max_tokens is a hard cap on thinking plus text -- an unchanged max_tokens: 4096 now gets eaten by thinking before your answer is written. Raise it to 64K+ if you run xhigh/max effort.
thinking: {type: "disabled"} is effort-gatedLegal only at effort high or below. Pairing it with xhigh or max returns a 400, so a config that worked on 4.8 can hard-fail.
Min cacheable prompt drops to 512 tokensPrompts too short to cache on 4.8 (1,024) now cache on 5. Free savings if you re-check your cache_control placement.
Cybersecurity classifiers ship on Opus 5Security-adjacent work can hit stop_reason: "refusal". Set the server-side fallbacks param (beta server-side-fallback-2026-07-01) to auto-retry on Opus 4.8 inside the same call rather than paying for a failed round-trip.

Two prompt-level cleanups worth doing at the same time: Opus 5 writes longer output than 4.8 by default, so re-tune your verbosity instructions; and it self-verifies, so any "double-check your work before answering" instruction you carried over from an older model is now paying twice for the same behavior. New beta mid-conversation-tool-changes-2026-07-01 also lets you change tool definitions between turns without invalidating the prompt cache -- previously a cache-busting move.

Full details: Anthropic's Opus 5 migration guide.


Legacy & Retired Models

Reference only -- don't use these for new work. Kept for migration context if you're unwinding code that still pins old model IDs.

Recently retired (requests now fail):

ModelRetired onMigrate to
Claude Opus 3 (claude-3-opus-20240229)2026-01-05Opus 5
Claude Sonnet 3.7 (claude-3-7-sonnet-20250219)2026-02-19Sonnet 5
Claude Haiku 3.5 (claude-3-5-haiku-20241022)2026-02-19 (still on Bedrock + Vertex AI)Haiku 4.5
Claude Haiku 3 (claude-3-haiku-20240307)2026-04-20Haiku 4.5
Claude Sonnet 4 (claude-sonnet-4-20250514)2026-06-15Sonnet 5
Claude Opus 4 (claude-opus-4-20250514)2026-06-15Opus 5
Claude Opus 4.1 (claude-opus-4-1-20250805)2026-08-05 (still on Bedrock + Google Cloud)Opus 5
Claude Sonnet 3.5 v1 / v2, Sonnet 3, Claude 2.x, Claude 1.x, Instant 1.x2024-2025See deprecations page

Deprecated: Claude Mythos Preview (claude-mythos-preview) is the one model in Deprecated state -- still functional, no longer recommended, and Anthropic publishes no retirement date for it. Migrate to Mythos 5 (Glasswing). Every other model that has not retired reads Active, so no dated forced migration is outstanding. The nearest tentative retirement is Sonnet 4.5 on 2026-09-29.

Older snapshots still callable (not retired, but not the headline tier):

SnapshotPricingContextEarliest retirementWhy use
Opus 4.8$5/$251M2027-05-28Previous flagship -- pin if prompts are tuned to it, or if you need thinking off at xhigh/max (Opus 5 rejects that combination). Also the fallback target for Opus 5 cyber refusals
Opus 4.7$5/$251M2027-04-16Pinned workloads. No Fast Mode -- speed: "fast" now errors
Opus 4.6$5/$251M2027-02-05Pinned workloads / older tokenizer. speed: "fast" silently runs standard
Opus 4.5$5/$25200K2026-11-24Pinned workloads only
Sonnet 4.6$3/$151M2027-02-17Pinned workloads -- migrate to Sonnet 5
Sonnet 4.5$3/$15200K2026-09-29Pinned workloads only

Authoritative source: platform.claude.com/docs/en/about-claude/model-deprecations.

The cheatsheet has a more detailed legacy table including last-known pricing for every retired tier.


Benchmarks & Case Studies


Community

Complementary Projects

ProjectWhat It DoesSavings
cavemanBrevity skill -- strips filler from responses50-75% output
claude-memCompresses session context for handoffInput reduction
claudetophtop-style monitoring with cost trackingVisibility

FAQ

How much does Claude Code actually cost?

With Pro ($20/mo or $200/yr ≈ $16.67/mo with annual billing -- 17% off), Max 5x ($100/mo), or Max 20x ($200/mo), you get included usage. Heavy users report $3-15/day without optimization, $1-5/day with it. Opus 5, 4.8, 4.7, and 4.6 at $5/$25 are 3x cheaper per token than Opus 4.1 ($15/$75) -- but the tokenizer introduced with Opus 4.7 can use up to 35% more tokens, so the effective gap is closer to ~2x.

Does this apply to the Claude API too?

Context optimization, model selection, and prompt engineering apply to both. The skill and commands are Claude Code-specific.

Will optimization reduce output quality?

No. These strategies eliminate waste (duplicate context, unnecessary file reads, expensive models for simple tasks). Quality stays the same or improves -- less noise means better reasoning.

What's the biggest single change I can make?

Install cost-mode (npx skills add Sagargupta16/claude-cost-optimizer) and switch to Haiku for routine tasks. Combined: 50-70% savings.


Star History

If this repo helped you save money, consider giving it a star!

Star History Chart

More AI Developer Tools

If you found this useful, check out my other AI/Claude tools:

ProjectDescription
claude-code-recipes47 copy-paste recipes for Claude Code - commands, subagents, hooks, skills
claude-skillsCustom Claude Code plugin marketplace with dev-workflow, FARM stack, and more
agent-recipesAI agent workflows for real-world dev tasks - code review, testing, security
ai-git-hooksAI-powered git hooks - auto-review diffs, generate commit messages, security scanning
mcp-toolkitProduction-ready middleware for MCP servers - auth, caching, rate limiting

License

MIT - use these strategies, templates, and tools however you want.