llm-cost-optimizer
Track, analyze, and reduce LLM API costs — model routing, prompt caching, semantic caching, and budget alerts. Use when someone asks to "reduce AI costs", "track LLM spending", "optimize API costs", "set up model routing", "cache LLM responses", "compare model costs", "set budget limits for AI", or "my OpenAI bill is too high". Covers cost tracking per feature/user, smart model routing (expensive model for hard tasks, cheap for easy), semantic caching, prompt compression, and budget alerting.
What this skill does
# LLM Cost Optimizer
## Overview
LLM API costs grow fast — a chatbot doing 10K conversations/day at $0.01 each is $3K/month. This skill builds cost controls: track spending per feature and user, route simple tasks to cheap models, cache repeated queries, compress prompts, and alert before budgets blow up.
## When to Use
- Monthly LLM bill is growing and you need visibility into what's driving it
- Some features use GPT-4o when GPT-4o-mini would work fine
- Users ask the same questions repeatedly — cache those responses
- Need budget limits per team, feature, or API key
- Comparing total cost of ownership between providers
## Instructions
### Strategy 1: Cost Tracking Middleware
Wrap every LLM call to log tokens, cost, model, and feature. Know exactly where money goes.
```typescript
// cost-tracker.ts — Track LLM costs per feature, model, and user
/**
* Middleware that wraps LLM API calls, logs token usage
* and estimated cost, and enforces budget limits.
* Drop-in replacement for direct API calls.
*/
interface CostEntry {
timestamp: string;
model: string;
feature: string; // Which product feature made this call
userId?: string;
inputTokens: number;
outputTokens: number;
cachedTokens: number;
costUsd: number;
latencyMs: number;
}
// Pricing per 1M tokens (input / output) — update as providers change
const PRICING: Record<string, { input: number; output: number; cached?: number }> = {
"gpt-4o": { input: 2.50, output: 10.00, cached: 1.25 },
"gpt-4o-mini": { input: 0.15, output: 0.60, cached: 0.075 },
"claude-sonnet-4-20250514": { input: 3.00, output: 15.00, cached: 0.30 },
"claude-haiku-3-20250722": { input: 0.25, output: 1.25, cached: 0.025 },
"llama-3.1-8b": { input: 0.05, output: 0.05 }, // Self-hosted estimate
};
export class CostTracker {
private entries: CostEntry[] = [];
private budgets: Map<string, number> = new Map(); // feature → monthly limit USD
/**
* Calculate cost for a single LLM call.
*/
calculateCost(model: string, inputTokens: number, outputTokens: number, cachedTokens: number = 0): number {
const pricing = PRICING[model];
if (!pricing) return 0;
const inputCost = ((inputTokens - cachedTokens) * pricing.input) / 1_000_000;
const cachedCost = pricing.cached
? (cachedTokens * pricing.cached) / 1_000_000
: 0;
const outputCost = (outputTokens * pricing.output) / 1_000_000;
return inputCost + cachedCost + outputCost;
}
/**
* Log an LLM call and check budget.
*/
track(entry: Omit<CostEntry, "costUsd" | "timestamp">): CostEntry {
const costUsd = this.calculateCost(
entry.model, entry.inputTokens, entry.outputTokens, entry.cachedTokens
);
const full: CostEntry = {
...entry,
costUsd,
timestamp: new Date().toISOString(),
};
this.entries.push(full);
// Check budget
const monthlySpend = this.getMonthlySpend(entry.feature);
const budget = this.budgets.get(entry.feature);
if (budget && monthlySpend > budget) {
console.warn(`⚠️ Budget exceeded for "${entry.feature}": $${monthlySpend.toFixed(2)} / $${budget}`);
}
return full;
}
setBudget(feature: string, monthlyLimitUsd: number): void {
this.budgets.set(feature, monthlyLimitUsd);
}
getMonthlySpend(feature?: string): number {
const now = new Date();
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
return this.entries
.filter((e) => new Date(e.timestamp) >= monthStart)
.filter((e) => !feature || e.feature === feature)
.reduce((sum, e) => sum + e.costUsd, 0);
}
/**
* Generate a cost report grouped by feature and model.
*/
report(): Record<string, { calls: number; tokens: number; cost: number }> {
const groups: Record<string, { calls: number; tokens: number; cost: number }> = {};
for (const entry of this.entries) {
const key = `${entry.feature} → ${entry.model}`;
if (!groups[key]) groups[key] = { calls: 0, tokens: 0, cost: 0 };
groups[key].calls++;
groups[key].tokens += entry.inputTokens + entry.outputTokens;
groups[key].cost += entry.costUsd;
}
return groups;
}
}
```
### Strategy 2: Smart Model Router
Route tasks to the cheapest model that can handle them. Hard tasks → expensive model. Easy tasks → cheap model.
```typescript
// model-router.ts — Route LLM calls to the cheapest capable model
/**
* Analyzes task complexity and routes to the appropriate model.
* Simple classification/extraction → mini model (~95% cheaper).
* Complex reasoning/coding → full model.
*/
interface RouteDecision {
model: string;
reason: string;
estimatedCostRatio: number; // 1.0 = full price, 0.1 = 10% of full price
}
export function routeModel(task: string, context?: string): RouteDecision {
const taskLower = task.toLowerCase();
const contextLength = (context || "").length;
// Simple extraction / classification → mini model
if (
taskLower.includes("extract") ||
taskLower.includes("classify") ||
taskLower.includes("categorize") ||
taskLower.includes("summarize") ||
taskLower.includes("translate") ||
taskLower.includes("format")
) {
return {
model: "gpt-4o-mini",
reason: "Simple extraction/classification task",
estimatedCostRatio: 0.06, // ~6% of GPT-4o cost
};
}
// Short context + simple question → mini
if (contextLength < 2000 && !requiresReasoning(taskLower)) {
return {
model: "gpt-4o-mini",
reason: "Short context, simple task",
estimatedCostRatio: 0.06,
};
}
// Code generation / debugging → full model
if (
taskLower.includes("write code") ||
taskLower.includes("debug") ||
taskLower.includes("refactor") ||
taskLower.includes("architect")
) {
return {
model: "claude-sonnet-4-20250514",
reason: "Code generation requires strong reasoning",
estimatedCostRatio: 1.0,
};
}
// Complex reasoning → full model
return {
model: "gpt-4o",
reason: "Complex task requiring strong reasoning",
estimatedCostRatio: 0.8,
};
}
function requiresReasoning(task: string): boolean {
const reasoningKeywords = [
"analyze", "compare", "evaluate", "design", "architect",
"debug", "optimize", "explain why", "trade-off", "recommend",
];
return reasoningKeywords.some((k) => task.includes(k));
}
```
### Strategy 3: Semantic Cache
Cache LLM responses by meaning, not exact match. "What's the weather?" and "How's the weather today?" should hit the same cache.
```python
# semantic_cache.py — Cache LLM responses by semantic similarity
"""
Caches LLM responses using embedding similarity.
If a new query is semantically similar to a cached one,
return the cached response instead of calling the API.
Saves 30-60% on repetitive workloads.
"""
import hashlib
import json
import time
from typing import Optional
import numpy as np
import openai
class SemanticCache:
"""LLM response cache using embedding similarity."""
def __init__(self, similarity_threshold: float = 0.92, ttl_seconds: int = 3600):
"""
Args:
similarity_threshold: Min cosine similarity to consider a cache hit (0.92 = very similar)
ttl_seconds: Cache entry expiration time
"""
self.threshold = similarity_threshold
self.ttl = ttl_seconds
self.cache: list[dict] = [] # In production, use Redis or a vector DB
self.client = openai.OpenAI()
self.stats = {"hits": 0, "misses": 0, "saved_usd": 0.0}
def get(self, query: str) -> Optional[str]:
"""Check cache for a semantically similar query.
Args:
query: The user's query
Returns:
Cached response if found, None otherwise
"""
query_embedding = self._embed(query)
now = time.time()
best_match = None
best_score = 0.0
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.