Token Cost Optimization
Master the economics of LLM applications. Understand pricing models, calculate costs accurately, and implement strategies to reduce spend by 50-80% without sacrificing quality.
๐ฐ Why Token Costs Matter
๐ฅ Input Tokens
System prompt + context + user message. Cheaper but adds up with long contexts.
๐ค Output Tokens
Generated response. 3-5x more expensive and harder to predict accurately.
๐ Model Pricing Comparison (2024)
| Model | Provider | Input $/M | Output $/M | Context | Best For |
|---|---|---|---|---|---|
| GPT-4o | OpenAI | $2.50 | $10.00 | 128K | Multimodal, vision |
| Claude 3.5 Sonnet | Anthropic | $3.00 | $15.00 | 200K | Coding, analysis |
| Gemini 1.5 Pro | $1.25 | $5.00 | 2M | Long context | |
| GPT-4o-mini | OpenAI | $0.15 | $0.60 | 128K | Cost-effective general |
| Claude 3.5 Haiku | Anthropic | $0.80 | $4.00 | 200K | Fast responses |
| Gemini 2.0 Flash | $0.075 | $0.30 | 1M | Best value | |
| Llama 3.1 70B | Self-host | ~$0.20* | ~$0.20* | 128K | Open, customizable |
| Mixtral 8x22B | Self-host | ~$0.15* | ~$0.15* | 64K | MoE efficiency |
* Self-hosted costs vary based on GPU and utilization. Estimates based on cloud GPU pricing.
๐งฎ Quick Cost Estimation
Formula
Example Calculation
๐ฏ Cost Optimization Strategies
Model Routing
Route requests to the cheapest capable model:
- โข Simple queries: GPT-4o-mini, Gemini Flash
- โข Complex reasoning: GPT-4o, Claude Sonnet
- โข Classification: Fine-tuned small model
Prompt Optimization
Reduce tokens without losing quality:
- โข Remove redundant instructions
- โข Use shorter variable names in few-shot
- โข Compress context with summaries
Caching
Reuse previous responses:
- โข Exact match: Cache identical queries
- โข Semantic: Embeddings similarity (>0.95)
- โข Prompt caching: Anthropic/OpenAI native
Output Control
Limit expensive output tokens:
- โข Set appropriate
max_tokens - โข Request concise responses in prompt
- โข Use structured output (JSON)
โก Prompt Caching (Native)
Both Anthropic and OpenAI offer native prompt caching for repeated system promptsโup to 90% cheaper!
Anthropic Prompt Caching
- โข Mark cacheable content with
cache_control - โข 90% discount on cached input tokens
- โข 5-minute TTL (refreshes on use)
- โข Min 1024 tokens to cache
OpenAI Prompt Caching
- โข Automatic for repeated prompts
- โข 50% discount on cached tokens
- โข Works on GPT-4o and mini
- โข Min 1024 tokens prefix match
๐ Cost Monitoring Best Practices
Cost per Request
Track by endpoint/feature
Daily/Monthly Spend
Set budget thresholds
Cost per User
Identify heavy users
Anomaly Alerts
Spike detection