Skill — LLM Cost Optimization
When this skill activates
Any task involving LLM API cost reduction, prompt compression, semantic caching,
model cascading/routing, batch API usage, or token budget management.
Mandatory actions when this skill is active
Before writing any code
- Establish baseline costs (cost per query, daily/monthly spend, cost by feature).
- Identify the biggest cost drivers (which prompts, which models, which features).
- Set cost reduction targets with quality guardrails.
During implementation
- Implement semantic caching for repeated/similar queries.
- Use model cascading (start cheap, escalate only when needed).
- Add token estimation before API calls (pre-flight cost check).
After implementation
- Monitor cost per query, cache hit rate, and cascade escalation rate.
- Set up cost anomaly alerts (spike detection).
- Document cost optimization decisions in ARCHITECTURE.md.
Prompt Compression
System Prompt Optimization
- Remove redundant instructions (LLMs don't need repetition like humans).
- Use abbreviations and compact formatting in system prompts.
- Reference items by ID rather than including full content.
- Cache static system prompts (most providers support this).
Context Window Efficiency
- Include only relevant context (not entire documents).
- Summarize long documents before including in prompt.
- Use structured formats (JSON/YAML) over verbose prose for data.
- Remove examples from system prompt once model demonstrates understanding.
Token Reduction Techniques
| Technique |
Savings |
Quality Impact |
| Remove redundant instructions |
10-30% |
None |
| Abbreviate system prompt |
15-25% |
Minimal |
| Summarize context |
40-60% |
Low-moderate |
| Reference by ID |
50-70% |
None (if lookup available) |
| Fewer few-shot examples |
30-50% |
Low (if model is capable) |
Semantic Caching
Concept
- Hash similar queries → return cached response if semantically equivalent.
- Not exact-match caching — uses embedding similarity.
- Threshold: if query embedding distance < 0.05, serve cached response.
Implementation
1. Embed incoming query
2. Search cache for similar queries (cosine similarity > 0.95)
3. If hit: return cached response (cost = ~$0)
4. If miss: call LLM, store response in cache with query embedding
Cache Invalidation
- TTL-based: expire after N hours (for time-sensitive data).
- Event-based: invalidate when underlying data changes.
- Version-based: invalidate when prompt/model version changes.
Expected Performance
- Cache hit rate: 20-60% for typical applications.
- Cost reduction: proportional to hit rate.
- Latency improvement: 10-100x faster on cache hits.
Model Cascading
Pattern
Query → Haiku/Small Model → Quality Check → Pass? → Return
→ Fail? → Sonnet/Large Model → Return
Implementation Rules
- Start with cheapest model capable of the task.
- Define quality gate (confidence score, format validation, length check).
- Escalate to more expensive model only when quality gate fails.
- Track escalation rate (target: < 20% of queries escalate).
Model Tier Pricing (Approximate)
| Tier |
Model Examples |
Cost (per 1M tokens) |
Use For |
| Cheap |
Haiku, GPT-4o-mini |
$0.25-1.00 |
Simple tasks, classification, extraction |
| Medium |
Sonnet, GPT-4o |
$3.00-15.00 |
Most generation, reasoning |
| Expensive |
Opus, o1 |
$15.00-75.00 |
Complex reasoning, critical decisions |
Routing Heuristics
- Classification/extraction → always use cheap model.
- Code generation → medium model (escalate if syntax errors).
- Complex reasoning → start medium, escalate if confidence low.
- Safety-critical → always use expensive model (no cascading).
Batch API Usage
When to Use
- Non-real-time workloads (background processing, ETL, reports).
- Large volume of similar requests.
- Typical discount: 50% cheaper than synchronous API.
Batch-Eligible Workloads
- Document summarization pipelines.
- Nightly content generation.
- Bulk classification/tagging.
- Training data generation.
- Automated evaluations.
Implementation
- Queue requests during the day.
- Submit batch job during off-peak (overnight).
- Process results next morning.
- Set up retry for failed items in batch.
Token Estimation
Pre-Flight Cost Check
estimated_tokens = count_tokens(system_prompt + context + query)
estimated_cost = estimated_tokens * price_per_token
if estimated_cost > budget_threshold:
compress_context() # or reject query
Token Counting
- Use tiktoken (OpenAI) or provider-specific tokenizer.
- Count BEFORE sending to API (not after).
- Include expected output tokens in estimate.
- Set max_tokens to limit output cost.
Budget Controls
- Per-query budget: reject or compress if estimated cost too high.
- Per-user budget: track cumulative cost, throttle when approaching limit.
- Per-feature budget: allocate cost budgets to product features.
Output Token Reduction
Techniques
- Set
max_tokens to reasonable limit for the task.
- Instruct model to be concise: "Answer in 2-3 sentences."
- Use structured output (JSON) to prevent verbose prose.
- Ask for key information only, not explanations (when appropriate).
Output Cost Impact
| Approach |
Typical Output Reduction |
Quality Impact |
| max_tokens cap |
Varies |
May truncate if too aggressive |
| Conciseness instruction |
30-50% |
Usually none for factual tasks |
| JSON/structured output |
40-60% |
None (often improves) |
| Enumerate, don't explain |
50-70% |
Low for extraction tasks |
Cost Monitoring
Key Metrics
| Metric |
Alert Threshold |
Description |
| Daily cost |
> 2x rolling average |
Anomaly detection |
| Cost per query |
> budget ceiling |
Individual query cost |
| Cache hit rate |
< 30% (if caching enabled) |
Cache effectiveness |
| Escalation rate |
> 30% |
Cascade efficiency |
| Token waste ratio |
> 20% unused max_tokens |
Over-allocated budgets |
Dashboard Requirements
- Cost breakdown by: feature, model, endpoint, user tier.
- Trend lines: daily, weekly, monthly.
- Forecast: projected monthly cost at current rate.
- Anomaly alerts: immediate notification on cost spikes.
Optimization Feedback Loop
Monitor costs → Identify top cost drivers → Apply optimization →
Measure improvement → Adjust thresholds → Repeat monthly
Self-check before task completion
Before marking a task done when this skill was active:
1---2name: llm-cost-optimization3description: Skill — LLM Cost Optimization4---56# Skill — LLM Cost Optimization78## When this skill activates9Any task involving LLM API cost reduction, prompt compression, semantic caching,10model cascading/routing, batch API usage, or token budget management.1112## Mandatory actions when this skill is active1314### Before writing any code151. Establish baseline costs (cost per query, daily/monthly spend, cost by feature).162. Identify the biggest cost drivers (which prompts, which models, which features).173. Set cost reduction targets with quality guardrails.1819### During implementation20- Implement semantic caching for repeated/similar queries.21- Use model cascading (start cheap, escalate only when needed).22- Add token estimation before API calls (pre-flight cost check).2324### After implementation25- Monitor cost per query, cache hit rate, and cascade escalation rate.26- Set up cost anomaly alerts (spike detection).27- Document cost optimization decisions in ARCHITECTURE.md.2829## Prompt Compression3031### System Prompt Optimization32- Remove redundant instructions (LLMs don't need repetition like humans).33- Use abbreviations and compact formatting in system prompts.34- Reference items by ID rather than including full content.35- Cache static system prompts (most providers support this).3637### Context Window Efficiency38- Include only relevant context (not entire documents).39- Summarize long documents before including in prompt.40- Use structured formats (JSON/YAML) over verbose prose for data.41- Remove examples from system prompt once model demonstrates understanding.4243### Token Reduction Techniques44| Technique | Savings | Quality Impact |45|-----------|---------|---------------|46| Remove redundant instructions | 10-30% | None |47| Abbreviate system prompt | 15-25% | Minimal |48| Summarize context | 40-60% | Low-moderate |49| Reference by ID | 50-70% | None (if lookup available) |50| Fewer few-shot examples | 30-50% | Low (if model is capable) |5152## Semantic Caching5354### Concept55- Hash similar queries → return cached response if semantically equivalent.56- Not exact-match caching — uses embedding similarity.57- Threshold: if query embedding distance < 0.05, serve cached response.5859### Implementation60```611. Embed incoming query622. Search cache for similar queries (cosine similarity > 0.95)633. If hit: return cached response (cost = ~$0)644. If miss: call LLM, store response in cache with query embedding65```6667### Cache Invalidation68- TTL-based: expire after N hours (for time-sensitive data).69- Event-based: invalidate when underlying data changes.70- Version-based: invalidate when prompt/model version changes.7172### Expected Performance73- Cache hit rate: 20-60% for typical applications.74- Cost reduction: proportional to hit rate.75- Latency improvement: 10-100x faster on cache hits.7677## Model Cascading7879### Pattern80```81Query → Haiku/Small Model → Quality Check → Pass? → Return82 → Fail? → Sonnet/Large Model → Return83```8485### Implementation Rules86- Start with cheapest model capable of the task.87- Define quality gate (confidence score, format validation, length check).88- Escalate to more expensive model only when quality gate fails.89- Track escalation rate (target: < 20% of queries escalate).9091### Model Tier Pricing (Approximate)92| Tier | Model Examples | Cost (per 1M tokens) | Use For |93|------|---------------|----------------------|---------|94| Cheap | Haiku, GPT-4o-mini | $0.25-1.00 | Simple tasks, classification, extraction |95| Medium | Sonnet, GPT-4o | $3.00-15.00 | Most generation, reasoning |96| Expensive | Opus, o1 | $15.00-75.00 | Complex reasoning, critical decisions |9798### Routing Heuristics99- Classification/extraction → always use cheap model.100- Code generation → medium model (escalate if syntax errors).101- Complex reasoning → start medium, escalate if confidence low.102- Safety-critical → always use expensive model (no cascading).103104## Batch API Usage105106### When to Use107- Non-real-time workloads (background processing, ETL, reports).108- Large volume of similar requests.109- Typical discount: 50% cheaper than synchronous API.110111### Batch-Eligible Workloads112- Document summarization pipelines.113- Nightly content generation.114- Bulk classification/tagging.115- Training data generation.116- Automated evaluations.117118### Implementation119- Queue requests during the day.120- Submit batch job during off-peak (overnight).121- Process results next morning.122- Set up retry for failed items in batch.123124## Token Estimation125126### Pre-Flight Cost Check127```python128estimated_tokens = count_tokens(system_prompt + context + query)129estimated_cost = estimated_tokens * price_per_token130if estimated_cost > budget_threshold:131 compress_context() # or reject query132```133134### Token Counting135- Use tiktoken (OpenAI) or provider-specific tokenizer.136- Count BEFORE sending to API (not after).137- Include expected output tokens in estimate.138- Set max_tokens to limit output cost.139140### Budget Controls141- Per-query budget: reject or compress if estimated cost too high.142- Per-user budget: track cumulative cost, throttle when approaching limit.143- Per-feature budget: allocate cost budgets to product features.144145## Output Token Reduction146147### Techniques148- Set `max_tokens` to reasonable limit for the task.149- Instruct model to be concise: "Answer in 2-3 sentences."150- Use structured output (JSON) to prevent verbose prose.151- Ask for key information only, not explanations (when appropriate).152153### Output Cost Impact154| Approach | Typical Output Reduction | Quality Impact |155|----------|------------------------|---------------|156| max_tokens cap | Varies | May truncate if too aggressive |157| Conciseness instruction | 30-50% | Usually none for factual tasks |158| JSON/structured output | 40-60% | None (often improves) |159| Enumerate, don't explain | 50-70% | Low for extraction tasks |160161## Cost Monitoring162163### Key Metrics164| Metric | Alert Threshold | Description |165|--------|----------------|-------------|166| Daily cost | > 2x rolling average | Anomaly detection |167| Cost per query | > budget ceiling | Individual query cost |168| Cache hit rate | < 30% (if caching enabled) | Cache effectiveness |169| Escalation rate | > 30% | Cascade efficiency |170| Token waste ratio | > 20% unused max_tokens | Over-allocated budgets |171172### Dashboard Requirements173- Cost breakdown by: feature, model, endpoint, user tier.174- Trend lines: daily, weekly, monthly.175- Forecast: projected monthly cost at current rate.176- Anomaly alerts: immediate notification on cost spikes.177178### Optimization Feedback Loop179```180Monitor costs → Identify top cost drivers → Apply optimization →181Measure improvement → Adjust thresholds → Repeat monthly182```183184## Self-check before task completion185186Before marking a task done when this skill was active:187188- [ ] Did I read the full SKILL.md before starting? (Not just the triggers)189- [ ] Is semantic caching implemented for repeated queries?190- [ ] Is model cascading configured (cheap first, escalate on failure)?191- [ ] Are token budgets estimated before API calls?192- [ ] Is cost monitoring in place with anomaly alerts?193- [ ] Are batch APIs used for non-real-time workloads?194- [ ] Is prompt compression applied to system prompts?