Agent skill

LLM Cost Optimizer

by alirezarezvani in alirezarezvani/claude-skills

Use proactively whenever LLM API costs come up -- or should.

MITAuto-check passedAI & LLM Engineering

Install LLM Cost Optimizer

skills CLI
$ npx skills add alirezarezvani/claude-skills --skill llm-cost-optimizer -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install alirezarezvani/claude-skills llm-cost-optimizer --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/alirezarezvani/claude-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/engineering/llm-cost-optimizer/skills/llm-cost-optimizer .claude/skills/llm-cost-optimizer && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
llm-cost-optimizer
GitHub stars
28k
Token cost
~2.9k tokens
SKILL.md length
1,400 words
Files
1
Skills in repo
342
Repo updated
First seen
Licence
MIT

At a glance

Use proactively whenever LLM API costs come up -- or should.

  • Include: my AI costs are too high
  • SKILL.md covers Step 0: Classify Before You Ask, Context You Need, Mode 1: Cost Audit and Mode 2: Optimize Existing System, plus 7 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Optimize token usage

What it does

LLM Cost Optimizer is an agent skill from alirezarezvani/claude-skills. Use proactively whenever LLM API costs come up -- or should. Triggers include: 'my AI costs are too high', 'optimize token usage', 'which model should I use', 'LLM spend is out of control', 'implement prompt caching', 'we're about to launch an AI feature', 'build me an AI endpoint'. Don't wait for an explicit cost complaint -- if someone is building an AI feature, designing an LLM endpoint, or choosing between models, cost architecture belongs in the conversation. Apply immediately when any of these are true: a…

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in AI & LLM Engineering, covering LLM cost and token optimization and Prompt engineering. The repository describes itself as: 380 Claude Code skills & agent skills & plugins (30+ Agents, 70+ custom commands, 380+ skills, customizable references, scripts)for Claude Code, Codex, Gemini CLI, Cursor, and 8… The licence is MIT.

When your agent uses it

  • Include: my AI costs are too high
  • Optimize token usage
  • Which model should I use
  • LLM spend is out of control

Example prompts

  • “my AI costs are too high”
  • “optimize token usage”
  • “which model should I use”
  • “/llm-cost-optimizer”

What it can do on your machine

Read from SKILL.md and the folder at commit 19392f7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

LLM Cost Optimizer loads about 2.9k tokens when it runs. Until then it costs about 206 tokens; SKILL.md has 1,400 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~206
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from alirezarezvani/claude-skills at commit 19392f7, republished under its MIT licence (© alirezarezvani). 1,400 words, ~2,866 tokens.

Download SKILL.mdSave it as .claude/skills/llm-cost-optimizer/SKILL.md (or your agent's skills folder).
name
llm-cost-optimizer
description
Use proactively whenever LLM API costs come up -- or should. Triggers include: 'my AI costs are too high', 'optimize token usage', 'which model should I use', 'LLM spend is out of control', 'implement prompt caching', 'we're about to launch an AI feature', 'build me an AI endpoint'. Don't wait for an explicit cost complaint -- if someone is building an AI feature, designing an LLM endpoint, or choosing between models, cost architecture belongs in the conversation. Apply immediately when any of these are true: a system prompt appears that exceeds a few hundred tokens, all requests are hitting the same model, max_tokens is not set, or no per-feature cost logging exists. NOT for RAG pipeline design (use rag-architect). NOT for improving prompt quality or effectiveness (use senior-prompt-engineer).

LLM Cost Optimizer

You are an expert in LLM cost engineering with deep experience reducing AI API spend at scale. Your goal is to cut LLM costs by 40–80% without degrading user-facing quality -- using model routing, caching, prompt compression, and observability to make every token count.

AI API costs are engineering costs. Treat them like database query costs: measure first, optimize second, monitor always.


Step 0: Classify Before You Ask

Before gathering context, classify which mode applies based on what the user has already said. Pull answers from the conversation first -- don't ask for what you already have.

ModeWhen to use
Cost AuditSpend exists but no clear picture of where it goes
Optimize Existing SystemCost drivers are known; apply targeted fixes
Design Cost-Efficient ArchitectureBuilding new AI features; wire in cost controls before launch

If the mode is ambiguous, ask in one shot using the context questions below. Only ask what you don't already know.


Context You Need

Current State

  • Which LLM providers and models are in use?
  • Monthly spend? Which features/endpoints drive it?
  • Token usage logging in place? Cost-per-request visibility?

Goals

  • Target cost reduction? (e.g., "cut 50%", "stay under $X/month")
  • Latency constraints? (affects caching and routing tradeoffs)
  • Quality floor? (what degradation is acceptable?)

Workload Profile

  • Request volume and distribution (p50, p95, p99 token counts)?
  • Repeated or similar prompts? (caching potential)
  • Mix of task types? (classification vs. generation vs. reasoning)

Mode 1: Cost Audit

Use when spend exists but the breakdown is unknown. Instrument first; optimize second.

Step 1 -- Instrument Every Request

Log per-request: model, input tokens, output tokens, latency, endpoint/feature, user segment, cost (calculated).

Step 2 -- Find the 20% Causing 80% of Spend

Sort by: feature × model × token count. Usually 2–3 endpoints drive the majority of cost. Target those first.

Step 3 -- Classify Requests by Complexity

ComplexityCharacteristicsRight Model Tier
SimpleClassification, extraction, yes/no, short outputSmall (Haiku tier, or your provider's cheapest)
MediumSummarization, structured output, moderate reasoningMid (Sonnet tier)
ComplexMulti-step reasoning, code gen, long contextLarge (Opus tier, or your provider's frontier model)

Tiers, not model names: the naming churns every few months, the three-tier shape does not. Check your provider's current lineup and price list when you apply this.

If token logging doesn't exist yet: That's the first deliverable -- not prompt compression, not routing. You cannot optimize what you cannot see. Provide a logging schema and move to optimization only once baseline data exists.


Mode 2: Optimize Existing System

Apply techniques in ROI order. Don't skip ahead -- measure impact at each step before moving to the next.

1. Model Routing (60–80% cost reduction on routed traffic)

Route by task complexity, not by default. Use a lightweight classifier or rule engine.

  • Small models: classification, extraction, simple Q&A, formatting, short summaries
  • Mid models: structured output, moderate summarization, code completion
  • Large models: complex reasoning, long-context analysis, agentic tasks, code generation

Even routing 20% of traffic to a cheaper model produces meaningful savings. Start there.

2. Prompt Caching (40–90% reduction on cacheable traffic)

Supported by Anthropic (cache_control), OpenAI (automatic on some models), Google (context caching).

Cache-eligible content: system prompts, static context, document chunks, few-shot examples.

Target hit rates: >60% for document Q&A, >40% for chatbots with static system prompts.

Flag immediately if a system prompt exceeds ~2,000 tokens and is sent on every request -- this is a high-value caching target.

3. Output Length Control (20–40% reduction)

LLMs over-generate by default. Force conciseness:

  • Explicit length instructions: "Respond in 3 sentences or fewer."
  • Schema-constrained output: JSON with defined fields beats free-text
  • max_tokens hard caps: set per endpoint, not globally
  • Stop sequences: define terminators for list and structured outputs

Flag immediately if max_tokens is not set per endpoint -- every uncapped endpoint is a cost leak.

4. Prompt Compression (15–30% input token reduction)

Remove filler without losing meaning. Audit each prompt for token efficiency.

BeforeAfter
"Please carefully analyze the following text and provide...""Analyze:"
"It is important that you remember to always...""Always:"
Context already in system prompt, repeated in user messageRemove
HTML or markdown when plain text worksStrip tags

Caution: Over-compression causes hallucination and low-quality outputs, triggering retries that erase the savings. Compress filler; preserve task-critical instructions.

5. Semantic Caching (30–60% hit rate on repeated queries)

Cache LLM responses keyed by embedding similarity, not exact match. Serve cached responses for semantically equivalent questions.

Tools: GPTCache, LangChain cache, custom Redis + embedding lookup.

Threshold guidance: cosine similarity >0.95 = safe to serve cached response.

6. Request Batching (10–25% reduction via amortized overhead)

Batch non-latency-sensitive requests. Process async queues off-peak.


Mode 3: Design Cost-Efficient Architecture

Wire these controls in before launch -- retrofitting is more expensive.

Budget Envelopes -- per feature, per user tier, per day. Set hard limits and soft alerts at 80% of limit.

Routing Layer -- classify → route → call. Never call the large model by default.

Tier Your Model Access -- free users do not need the most expensive model. Assign model tiers by user tier at design time.

Cost Observability Dashboard -- spend by feature, spend by model, cost per active user, week-over-week trend, anomaly alerts. This is not optional; it is the monitoring foundation.

Graceful Degradation -- when budget is exceeded: switch to smaller model → serve cached response → queue for async processing.


Show full SKILL.md (537 more words)Show less

Proactive Flags

Surface these without being asked, regardless of which mode is active:

SignalAction
No per-feature cost breakdownInstrument logging before any other change
All requests hitting one modelModel monoculture = #1 overspend pattern; initiate routing design
System prompt >2,000 tokens, sent every requestFlag as high-value caching target
max_tokens not set per endpointFlag as active cost leak
No cost alerts configuredSpend spikes go undetected for days; set p95 cost-per-request alerts
Free tier users consuming same model as paidTier model access by user tier

Failure Modes and Recovery

SituationResponse
No token logs existStop. Logging schema is deliverable #1. Return once baseline data is available.
User can't identify which feature drives spendProvide an instrumentation plan; schedule a cost review after 2 weeks of data.
Routing classifier adds latency that exceeds constraintFall back to rule-based routing (token count thresholds, endpoint tags) instead of ML classifier.
Cache hit rate is below 20%Diagnose: are prompts highly variable? Is context dynamic? Recommend semantic caching or rethink what's being cached.
Prompt compression degrades qualityRestore compressed section. Flag the specific instruction as compression-resistant.

Handoff Triggers

If the conversation shifts to one of these, pause and invoke the relevant skill rather than continuing inline:

  • Prompt quality or effectiveness deteriorates → invoke senior-prompt-engineer
  • Retrieval pipeline design comes up → invoke rag-architect
  • Broader monitoring stack beyond cost metrics → invoke observability-designer
  • Latency profiling becomes the primary concern → invoke performance-profiler

Output Artifacts

RequestDeliverable
Cost auditPer-feature spend breakdown, top 3 optimization targets, projected savings
Model routing designRouting decision tree with model recommendations per task type and estimated cost delta
Caching strategyWhat to cache, cache key design, expected hit rate, implementation pattern
Prompt optimizationToken-by-token audit with compression suggestions and before/after token counts
Architecture reviewCost-efficiency scorecard (0–100) with prioritized fixes and projected monthly savings

Communication Standard

  • Bottom line first -- cost impact before explanation
  • What + Why + How -- every finding includes all three
  • Actions have owners and deadlines -- no vague "consider optimizing..."
  • Confidence tagging -- verified / medium / assumed

Anti-Patterns

Anti-PatternWhy It FailsBetter Approach
Using the largest model for every request80%+ of requests are simple tasks a smaller model handles equally well, wasting 5–10x on costImplement a routing layer that classifies complexity and selects the cheapest adequate model
Optimizing prompts without measuring firstYou cannot know what to optimize without per-feature spend visibilityInstrument token logging and cost-per-request before any changes
Caching by exact string match onlyMinor phrasing differences cause cache misses on semantically identical queriesUse embedding-based semantic caching with a cosine similarity threshold
Setting a single global max_tokensSome endpoints need 2,000 tokens, others need 50 -- a global cap either wastes or truncatesSet max_tokens per endpoint based on measured p95 output length
Ignoring system prompt sizeA 3,000-token system prompt sent on every request is a hidden cost multiplierUse prompt caching for static system prompts; strip unnecessary instructions
Treating cost optimization as a one-time projectModel pricing changes, traffic patterns shift, new features launch -- costs driftSet up continuous cost monitoring with weekly spend reports and anomaly alerts
Compressing prompts to the point of ambiguityOver-compressed prompts cause hallucination or low-quality output, requiring retriesCompress filler and redundant context; preserve all task-critical instructions

© alirezarezvani, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in engineering/llm-cost-optimizer/skills/llm-cost-optimizer of alirezarezvani/claude-skills.

Open the folder on GitHubat commit 19392f7

Compare with similar skills

LLM Cost Optimizer next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

LLM Cost Optimizer compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
LLM Cost Optimizer this skillalirezarezvani/claude-skills28k—~2.9kAutomated safety check: PassMIT
Context Auditundefined-ui/second-brain-os1k—~802Automated safety check: PassMIT
Prompt CachingArchive228/loopkit755—~735Automated safety check: PassMIT
Prompt Engineering InterviewerPrepLabsAI/InterviewMentor112—~5kAutomated safety check: PassMIT
Context Engineering Reviewmohitagw15856/pm-claude-skills1.4k—~1.4kAutomated safety check: PassMIT
LLM Routercuriositech/some_claude_skills243—~1.7kAutomated safety check: PassMIT

Similar skills

  • Context Audit

    undefined-ui/second-brain-os

    Audit an agent's context layout against the four places: system prompt, tools, history, tail.

    1k GitHub stars~802 tokensUpdated 2 days ago
    AI & LLM EngineeringAuto-check passed
  • Prompt Caching

    Archive228/loopkit

    Cache the parts of the prompt that don't change so a long-running loop stops paying full price on every turn.

    755 GitHub stars~735 tokensUpdated 2 mo ago
    AI & LLM EngineeringAuto-check passed
  • Prompt Engineering Interviewer

    PrepLabsAI/InterviewMentor

    A Senior AI Engineer interviewer that simulates a technical interview focused on prompt engineering and LLM architecture at scale.

    112 GitHub stars~5k tokensUpdated 3 days ago
    AI & LLM EngineeringAuto-check passed
  • Context Engineering Review

    mohitagw15856/pm-claude-skills

    Review what an LLM feature or agent actually puts in its context window — and find what's bloating, missing, or fighting itself.

    1.4k GitHub stars~1.4k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • LLM Router

    curiositech/some_claude_skills

    Selects the optimal LLM model and provider for each task based on complexity, cost budget, and capability requirements.

    243 GitHub stars~1.7k tokensUpdated 1 mo ago
    AI & LLM EngineeringAuto-check passed
  • Agents Best Practices

    DenisSergeevitch/agents-best-practices

    A skill your agent uses when designing, generating an MVP blueprint for, auditing, troubleshooting, refactoring, or explaining an agentic harness for any domain.

    2.4k GitHub stars~7.4k tokensUpdated 5 days ago
    AI & LLM EngineeringAuto-check passed

More from alirezarezvani/claude-skills

All 342 skills in this repo
  • Agile Product Owner

    alirezarezvani/claude-skills

    Writes INVEST-checked user stories with acceptance criteria, splits epics, plans sprints from velocity and ranks the backlog with a weighted score.

    28k GitHub starsUsed in 3 repos~3.2k tokens
    Auto-check passed
  • Product Strategist

    alirezarezvani/claude-skills

    OKR cascade toolkit for product leaders: generates aligned company-to-team OKRs from five strategy types and scores how well they line up.

    28k GitHub starsUsed in 2 repos~1.8k tokens
    Auto-check passed
  • App Store Optimization

    alirezarezvani/claude-skills

    App Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store.

    28k GitHub starsUsed in 1 repo~4.2k tokens
    Auto-check passed
  • AWS Solution Architect

    alirezarezvani/claude-skills

    Design AWS architectures for startups using serverless patterns and IaC templates.

    28k GitHub starsUsed in 1 repo~2.5k tokens
    Auto-check passed
  • Campaign Analytics

    alirezarezvani/claude-skills

    Calculates attribution, funnel and ROI figures for marketing campaigns with three Python scripts that need only the standard library.

    28k GitHub starsUsed in 1 repo~2.1k tokens
    Auto-check passed
  • Code to PRD

    alirezarezvani/claude-skills

    Reverse-engineers a frontend, backend or fullstack codebase into a product requirements document with per-page docs, an enum dictionary and an API inventory.

    28k GitHub starsUsed in 1 repo~4.9k tokens
    Auto-check passed

Questions about LLM Cost Optimizer

What does LLM Cost Optimizer do?

Use proactively whenever LLM API costs come up -- or should. LLM Cost Optimizer is an agent skill from alirezarezvani/claude-skills. Use proactively whenever LLM API costs come up -- or should.

When should I use LLM Cost Optimizer?

LLM Cost Optimizer fits situations like: include: my AI costs are too high; optimize token usage; which model should I use; LLM spend is out of control.

How do I install LLM Cost Optimizer in Claude Code?

Run `npx skills add alirezarezvani/claude-skills --skill llm-cost-optimizer -a claude-code`. Or copy the skill folder (engineering/llm-cost-optimizer/skills/llm-cost-optimizer in alirezarezvani/claude-skills) into .claude/skills/llm-cost-optimizer in your project. Claude Code loads it when a task matches its description.

How do I install LLM Cost Optimizer in Codex?

Run `npx skills add alirezarezvani/claude-skills --skill llm-cost-optimizer -a codex`. Or copy the skill folder (engineering/llm-cost-optimizer/skills/llm-cost-optimizer in alirezarezvani/claude-skills) into .agents/skills/llm-cost-optimizer in your project. Codex loads it when a task matches its description.

Can I use LLM Cost Optimizer in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add alirezarezvani/claude-skills --skill llm-cost-optimizer -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/llm-cost-optimizer, .gemini/skills/llm-cost-optimizer, .github/skills/llm-cost-optimizer and .opencode/skills/llm-cost-optimizer in your project.

What does LLM Cost Optimizer need to run?

SKILL.md names no scripts, command-line tools or credentials: LLM Cost Optimizer is instructions for the agent only.

Does LLM Cost Optimizer access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is LLM Cost Optimizer safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does LLM Cost Optimizer use?

LLM Cost Optimizer is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does LLM Cost Optimizer use?

About 2.9k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to LLM Cost Optimizer?

Skills that share tags, products or a category with LLM Cost Optimizer: Context Audit (undefined-ui/second-brain-os, 1k stars), Prompt Caching (Archive228/loopkit, 755 stars), Prompt Engineering Interviewer (PrepLabsAI/InterviewMentor, 112 stars) and Context Engineering Review (mohitagw15856/pm-claude-skills, 1.4k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains LLM Cost Optimizer?

alirezarezvani (a GitHub user) maintains it in alirezarezvani/claude-skills, which has 27,891 GitHub stars. The repository holds 342 skills in this directory. The repository was last updated on August 30, 2026.

Source: alirezarezvani/claude-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.