Back to Skills

Llm Cost Optimizer

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 endpoi…

apiaillmrag
By alirezarezvani
19k2.7kUpdated 3 days agoPythonMIT

Skill Content

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

| Mode | When to use |
|---|---|
| **Cost Audit** | Spend exists but no clear picture of where it goes |
| **Optimize Existing System** | Cost drivers are known; apply targeted fixes |
| **Design Cost-Efficient Architecture** | Building 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**

| Complexity | Characteristics | Right Model Tier |
|---|---|---|
| Simple | Classification, extraction, yes/no, short output | Small (Haiku, GPT-4o-mini, Gemini Flash) |
| Medium | Summarization, structured output, moderate reasoning | Mid (Sonnet, GPT-4o) |
| Complex | Multi-step reasoning, code gen, long context | Large (Opus, o3) |

**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.

| Before | After |
|---|---|
| "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 message | Remove |
| HTML or markdown when plain text works | Strip 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.

---

## Proactive Flags

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

| Signal | Action |
|---|---|
| No per-feature cost breakdown | Instrument logging before any other change |
| All requests hitting one model | Model monoculture = #1 overspend pattern; initiate routing design |
| System prompt >2,000 tokens, sent every request | Flag as high-value caching target |
| `max_tokens` not set per endpoint | Flag as active cost leak |
| No cost alerts configured | Spend spikes go undetected for days; set p95 cost-per-request alerts |
| Free tier users consuming same model as paid | Tier model access by user tier |

---

## Failure Modes and Recovery

| Situation | Response |
|---|---|
| No token logs exist | Stop. Logging schema is deliverable #1. Return once baseline data is available. |
| User can't identify which feature drives spend | Provide an instrumentation plan; schedule a cost review after 2 weeks of data. |
| Routing classifier adds latency that exceeds constraint | Fall 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 quality | Restore 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

| Request | Deliverable |
|---|---|
| Cost audit | Per-feature spend breakdown, top 3 optimization targets, projected savings |
| Model routing design | Routing decision tree with model recommendations per task type and estimated cost delta |
| Caching strategy | What to cache, cache key design, expected hit rate, implementation pattern |
| Prompt optimization | Token-by-token audit with compression suggestions and before/after token counts |
| Architecture review | Cost-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-Pattern | Why It Fails | Better Approach |
|---|---|---|
| Using the largest model for every request | 80%+ of requests are simple tasks a smaller model handles equally well, wasting 5–10x on cost | Implement a routing layer that classifies complexity and selects the cheapest adequate model |
| Optimizing prompts without measuring first | You cannot know what to optimize without per-feature spend visibility | Instrument token logging and cost-per-request before any changes |
| Caching by exact string match only | Minor phrasing differences cause cache misses on semantically identical queries | Use embedding-based semantic caching with a cosine similarity threshold |
| Setting a single global max_tokens | Some endpoints need 2,000 tokens, others need 50 -- a global cap either wastes or truncates | Set max_tokens per endpoint based on measured p95 output length |
| Ignoring system prompt size | A 3,000-token system prompt sent on every request is a hidden cost multiplier | Use prompt caching for static system prompts; strip unnecessary instructions |
| Treating cost optimization as a one-time project | Model pricing changes, traffic patterns shift, new features launch -- costs drift | Set up continuous cost monitoring with weekly spend reports and anomaly alerts |
| Compressing prompts to the point of ambiguity | Over-compressed prompts cause hallucination or low-quality output, requiring retries | Compress filler and redundant context; preserve all task-critical instructions |

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-llm-cost-optimizer.md
  4. Use /claude-skills-llm-cost-optimizer in Claude Code to invoke this skill

Claude Code Skills & Plugins — Agent Skills for Every Coding Tool

345 production-ready Claude Code skills, plugins, and agent skills for 13 AI coding tools.

The most comprehensive open-source library of Claude Code skills and agent plugins — also works with OpenAI Codex, Gemini CLI, Cursor, and 9 more coding agents. Reusable expertise packages covering engineering, DevOps, marketing (incl. AEO — Answer Engine Optimization for LLM citation), security (PreToolUse hooks), compliance, C-level advisory (incl. founder-mode CFO/CMO/CRO/CPO/COO/CHRO/CISO/GC/CDO/CAIO/CCO/VPE personas + 21 /cs:* slash commands), productivity (capture/email/reflect), an academic research stack (litreview/grants/dossier/patent/syllabus/pulse/notebooklm + hybrid router), and enterprise Research Operations (clinical-research/research-finance/market-research/product-research, v2.9.0).

Works with: Claude Code · OpenAI Codex · Gemini CLI · OpenClaw · Hermes Agent1 · Mistral Vibe2 · Cursor · Aider · Windsurf · Kilo Code · OpenCode · Augment · Antigravity

License: MIT Skills Agents Personas Commands Stars SkillCheck Validated

5,200+ GitHub stars — the most comprehensive open-source Claude Code skills & agent plugins library.


What Are Claude Code Skills & Agent Plugins?

Claude Code skills (also called agent skills or coding agent plugins) are modular instruction packages that give AI coding agents domain expertise they don't have out of the box. Each skill includes:

  • SKILL.md — structured instructions, workflows, and decision frameworks
  • Python tools — 579 CLI scripts (all stdlib-only, zero pip installs)
  • Reference docs — 702 templates, checklists, and domain-specific knowledge files

One repo, thirteen platforms. Works natively as Claude Code plugins, Codex agent skills, Gemini CLI skills, Hermes Agent skills, Mistral Vibe skills, and converts to more tools via scripts/convert.sh. All 579 Python tools run anywhere Python runs.

Skills vs Agents vs Personas

SkillsAgentsPersonas
PurposeHow to execute a taskWhat task to doWho is thinking
ScopeSingle domainSingle domainCross-domain
VoiceNeutralProfessionalPersonality-driven
Example"Follow these steps for SEO""Run a security audit""Think like a startup CTO"

All three work together. See Orchestration for how to combine them.


Quick Install

Gemini CLI (New)

# Clone the repository
git clone https://github.com/alirezarezvani/claude-skills.git
cd claude-skills

# Run the setup script
./scripts/gemini-install.sh

# Start using skills
> activate_skill(name="senior-architect")

Claude Code (Recommended)

# Add the marketplace
/plugin marketplace add alirezarezvani/claude-skills

# Install by domain
/plugin install engineering-skills@claude-code-skills          # 24 core engineering
/plugin install engineering-advanced-skills@claude-code-skills  # 25 POWERFUL-tier
/plugin install product-skills@claude-code-skills               # 12 product skills
/plugin install marketing-skills@claude-code-skills             # 43 marketing skills
/plugin install ra-qm-skills@claude-code-skills                 # 12 regulatory/quality
/plugin install pm-skills@claude-code-skills                    # 6 project management
/plugin install c-level-skills@claude-code-skills               # 28 C-level advisory (full C-suite)
/plugin install business-growth-skills@claude-code-skills       # 4 business & growth
/plugin install finance-skills@claude-code-skills               # 2 finance (analyst + SaaS metrics)

# Or install individual skills
/plugin install skill-security-auditor@claude-code-skills       # Security scanner
/plugin install playwright-pro@claude-code-skills                  # Playwright testing toolkit
/plugin install self-improving-agent@claude-code-skills         # Auto-memory curation
/plugin install content-creator@claude-code-skills              # Single skill

OpenAI Codex

npx agent-skills-cli add alirezarezvani/claude-skills --agent codex
# Or: git clone + ./scripts/codex-install.sh

OpenClaw

bash <(curl -s https://raw.githubusercontent.com/alirezarezvani/claude-skills/main/scripts/openclaw-install.sh)

Manual Installation

git clone https://github.com/alirezarezvani/claude-skills.git
# Copy any skill folder to ~/.claude/skills/ (Claude Code) or ~/.codex/skills/ (Codex)

Multi-Tool Support (New)

Convert all 345 skills to 9 AI coding tools with a single script:

ToolFormatInstall
Cursor.mdc rules./scripts/install.sh --tool cursor --target .
AiderCONVENTIONS.md./scripts/install.sh --tool aider --target .
Kilo Code.kilocode/rules/./scripts/install.sh --tool kilocode --target .
Windsurf.windsurf/skills/./scripts/install.sh --tool windsurf --target .
OpenCode.opencode/skills/./scripts/install.sh --tool opencode --target .
Augment.augment/rules/./scripts/install.sh --tool augment --target .
Antigravity~/.gemini/antigravity/skills/./scripts/install.sh --tool antigravity
Hermes Agent~/.hermes/skills/python scripts/sync-hermes-skills.py --verbose
Mistral Vibe~/.vibe/skills/./scripts/vibe-install.sh

How it works:

# 1. Convert all skills to all tools (takes ~15 seconds)
./scripts/convert.sh --tool all

# 2. Install into your project (with confirmation)
./scripts/install.sh --tool cursor --target /path/to/project

# Or use --force to skip confirmation:
./scripts/install.sh --tool aider --target . --force

# 3. Verify
find .cursor/rules -name "*.mdc" | wc -l  # Should show 346

Each tool gets:

  • ✅ All 345 skills converted to native format
  • ✅ Per-tool README with install/verify/update steps
  • ✅ Support for scripts, references, templates where applicable
  • ✅ Zero manual conversion work

Run ./scripts/convert.sh --tool all to generate tool-specific outputs locally.


Skills Overview

345 skills across 17 domains:

DomainSkillsHighlightsDetails
🔧 Engineering — Core51Architecture, frontend, backend, fullstack, QA, DevOps, SecOps, AI/ML, data, Playwright Pro (test gen, flaky fix, migrations), self-improving agent (auto-memory curation), security suite, a11y auditengineering-team/
⚡ Engineering — POWERFUL78Agent designer, RAG architect, database designer, CI/CD builder, security auditor, MCP builder, AgentHub, Helm charts, Terraform, self-eval, llm-wiki, tc-tracker, autoresearch-agent, reliability portfolio (feature-flags-architect, kubernetes-operator, chaos-engineering, slo-architect), ship-gate, security-guidance PreToolUse hook, Matt Pocock skills (write-a-skill, caveman, grill-me, handoff, grill-with-docs)engineering/
🎯 Product17Product manager, agile PO, strategist, UX researcher, UI design, landing pages, SaaS scaffolder, analytics, experiment designer, discovery, roadmap communicator, code-to-prd, apple-hig-expertproduct-team/
📣 Marketing468 pods: Content, SEO + AEO (aeo — E-E-A-T audit, citation tracking across 5 LLMs), CRO, Channels, Growth, Intelligence, Sales + context foundation + orchestration routermarketing-skill/
🚀 Productivity6capture (brain-dump-to-action), email pair (inbox-setup + inbox-triage), reflect (journal), handoff (Matt Pocock-inspired), andreessen (market-first decision mode)productivity/
🎨 Marketing (top-level)1landing — single-file HTML landing-page generator (4 design styles, GSAP patterns, brand palette validator)marketing/
🔬 Research (academic)8research orchestrator (hybrid router + fallback) + 7 specialists: pulse, litreview, grants (NIH), dossier, patent, syllabus, notebooklmresearch/
🧪 Research Operations ✨v2.9.05Enterprise/cross-functional research: orchestrator + clinical-research (study design), research-finance (R&D program finance), market-research (sizing/survey/segmentation), product-research (user research) — each with onboarding + customization + opt-in autoresearch bridgeresearch-ops/
📋 Project Management9Senior PM, scrum master, Jira, Confluence, Atlassian admin, templates + bundled Atlassian Remote MCPproject-management/
🏥 Regulatory & QM18ISO 13485, MDR 2017/745, FDA, ISO 27001, GDPR, SOC 2, CAPA, risk managementra-qm-team/
🛡️ Compliance OS9Compliance operating system — controls, evidence, audit-readiness workflowscompliance-os/
💼 C-Level Advisory66Full C-suite (CEO/CTO/CFO/CMO/CRO/CPO/COO/CHRO/CISO/GC/CDO/CAIO/CCO/VPE) + founder-mode agents + orchestration + board meetings + culture & collaborationc-level-advisor/
📈 Business & Growth5Customer success, sales engineer, revenue ops, contracts & proposals, BizDev toolkitbusiness-growth/
🏭 Business Operations7Orchestrator + process-mapper, vendor-management, capacity-planner, internal-comms, knowledge-ops, procurement-optimizerbusiness-operations/
🤝 Commercial8Orchestrator + pricing-strategist, deal-desk, partnerships-architect, channel-economics, commercial-policy, rfp-responder, commercial-forecastercommercial/
💰 Finance4Financial analyst (DCF, budgeting, forecasting), SaaS metrics coach, business investment advisorfinance/

Personas

Pre-configured agent identities with curated skill loadouts, workflows, and distinct communication styles. Personas go beyond "use these skills" — they define how an agent thinks, prioritizes, and communicates.

PersonaDomainBest For
Startup CTOEngineering + StrategyArchitecture decisions, tech stack selection, team building, technical due diligence
Growth MarketerMarketing + GrowthContent-led growth, launch strategy, channel optimization, bootstrapped marketing
Solo FounderCross-domainOne-person sta

Footnotes

  1. Hermes Agent is BYO-sync tier: the repo ships a pre-generated .hermes/skills/claude-skills/ tree, but you run python scripts/sync-hermes-skills.py once locally to install into ~/.hermes/skills/. Uses the same agentskills.io SKILL.md standard — no format conversion.

  2. Mistral Vibe is also BYO-sync tier: the repo ships a pre-generated .vibe/skills/claude-skills/ tree, run ./scripts/vibe-install.sh once locally to install into ~/.vibe/skills/. Same agentskills.io SKILL.md standard — no format conversion. Docs: https://docs.mistral.ai/mistral-vibe/agents-skills.

View source on GitHub