Audits, analyzes, and optimizes LLM API spending. Tracks token usage, calculates costs per model, and aggregates spending by operation.
Ships in llmops-guardian. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Audit, analyze, and optimize your LLM API spending.
Prices change often and differ by model, cache tier, batch mode, and cloud platform. Never hard-code a price table from memory — load prices from config that you refresh from the official pages:
| Provider | Official pricing page |
|---|---|
| Anthropic (Claude API) | https://platform.claude.com/docs/en/about-claude/pricing |
| OpenAI | https://openai.com/api/pricing/ |
| Google (Gemini API) | https://ai.google.dev/gemini-api/docs/pricing |
Pricing dimensions to capture per model: base input, output, cache writes (Anthropic has separate 5-minute and 1-hour write prices), cache reads, and batch discounts.
interface TokenUsage {
inputTokens: number;
outputTokens: number;
cachedTokens?: number;
}
interface ModelPricing {
inputPer1M: number;
outputPer1M: number;
cachedPer1M?: number;
}
function calculateCost(usage: TokenUsage, pricing: ModelPricing): number {
const inputCost = (usage.inputTokens / 1_000_000) * pricing.inputPer1M;
const outputCost = (usage.outputTokens / 1_000_000) * pricing.outputPer1M;
const cachedCost = usage.cachedTokens
? (usage.cachedTokens / 1_000_000) * (pricing.cachedPer1M || pricing.inputPer1M * 0.1)
: 0;
return inputCost + outputCost + cachedCost;
}
// Example
const usage = { inputTokens: 50000, outputTokens: 10000 };
const claude35Sonnet = { inputPer1M: 3.00, outputPer1M: 15.00 };
const cost = calculateCost(usage, claude35Sonnet);
// $0.15 + $0.15 = $0.30
interface UsageRecord {
timestamp: Date;
model: string;
operation: string;
userId?: string;
inputTokens: number;
outputTokens: number;
cost: number;
metadata: Record<string, unknown>;
}
class CostTracker {
private records: UsageRecord[] = [];
record(usage: Omit<UsageRecord, 'timestamp' | 'cost'>): void {
const pricing = this.getPricing(usage.model);
const cost = calculateCost(
{ inputTokens: usage.inputTokens, outputTokens: usage.outputTokens },
pricing
);
this.records.push({
...usage,
timestamp: new Date(),
cost
});
}
// Aggregation methods
getTotalCost(since: Date): number {
return this.records
.filter(r => r.timestamp >= since)
.reduce((sum, r) => sum + r.cost, 0);
}
getCostByOperation(): Map<string, number> {
const byOp = new Map<string, number>();
for (const r of this.records) {
byOp.set(r.operation, (byOp.get(r.operation) || 0) + r.cost);
}
return byOp;
}
getCostByModel(): Map<string, number> {
const byModel = new Map<string, number>();
for (const r of this.records) {
byModel.set(r.model, (byModel.get(r.model) || 0) + r.cost);
}
return byModel;
}
getTopExpensiveOperations(limit: number = 10): UsageRecord[] {
return [...this.records]
.sort((a, b) => b.cost - a.cost)
.slice(0, limit);
}
}
interface CostReport {
period: { start: Date; end: Date };
summary: {
totalCost: number;
totalInputTokens: number;
totalOutputTokens: number;
uniqueOperations: number;
avgCostPerRequest: number;
};
breakdown: {
byModel: { model: string; cost: number; percentage: number }[];
byOperation: { operation: string; cost: number; requests: number }[];
byDay: { date: string; cost: number }[];
};
insights: {
mostExpensiveOperation: string;
fastestGrowingCost: string;
optimizationOpportunities: string[];
};
}
function generateCostReport(
records: UsageRecord[],
period: { start: Date; end: Date }
): CostReport {
const filtered = records.filter(
r => r.timestamp >= period.start && r.timestamp <= period.end
);
const totalCost = filtered.reduce((sum, r) => sum + r.cost, 0);
// Group by model
const byModel = new Map<string, number>();
for (const r of filtered) {
byModel.set(r.model, (byModel.get(r.model) || 0) + r.cost);
}
// Group by operation
const byOperation = new Map<string, { cost: number; count: number }>();
for (const r of filtered) {
const existing = byOperation.get(r.operation) || { cost: 0, count: 0 };
byOperation.set(r.operation, {
cost: existing.cost + r.cost,
count: existing.count + 1
});
}
// Find optimization opportunities
const opportunities: string[] = [];
// Check for expensive model usage on simple tasks
// SMALL_MODEL_ID / LARGE_MODEL_ID: the IDs you actually route to
const small = byModel.get(SMALL_MODEL_ID) || 0;
const large = byModel.get(LARGE_MODEL_ID) || 0;
if (large > small * 10) {
opportunities.push('Consider a smaller model for simpler tasks - large-model spend dominates this report');
}
// Check for high output token ratio
const totalInput = filtered.reduce((s, r) => s + r.inputTokens, 0);
const totalOutput = filtered.reduce((s, r) => s + r.outputTokens, 0);
if (totalOutput > totalInput * 2) {
opportunities.push('High output ratio - consider asking for more concise responses');
}
return {
period,
summary: {
totalCost,
totalInputTokens: totalInput,
totalOutputTokens: totalOutput,
uniqueOperations: byOperation.size,
avgCostPerRequest: totalCost / filtered.length
},
breakdown: {
byModel: Array.from(byModel.entries()).map(([model, cost]) => ({
model,
cost,
percentage: (cost / totalCost) * 100
})),
byOperation: Array.from(byOperation.entries()).map(([op, data]) => ({
operation: op,
cost: data.cost,
requests: data.count
})),
byDay: groupByDay(filtered)
},
insights: {
mostExpensiveOperation: [...byOperation.entries()]
.sort((a, b) => b[1].cost - a[1].cost)[0]?.[0] || 'none',
fastestGrowingCost: calculateGrowth(filtered),
optimizationOpportunities: opportunities
}
};
}
type TaskComplexity = 'simple' | 'medium' | 'complex';
function selectCostEffectiveModel(
task: string,
complexity: TaskComplexity
): string {
const modelMap = {
// Map tiers to current model IDs; check prices on the provider pricing page
simple: SMALL_MODEL_ID,
medium: MEDIUM_MODEL_ID,
complex: LARGE_MODEL_ID
};
return modelMap[complexity];
}
// Auto-detect complexity
function assessComplexity(task: string): TaskComplexity {
const complexIndicators = ['analyze', 'compare', 'synthesize', 'evaluate', 'complex'];
const simpleIndicators = ['format', 'extract', 'classify', 'summarize short'];
const lower = task.toLowerCase();
if (complexIndicators.some(i => lower.includes(i))) return 'complex';
if (simpleIndicators.some(i => lower.includes(i))) return 'simple';
return 'medium';
}
// Before: Verbose prompt (many input tokens)
const verbosePrompt = `
You are an expert assistant. Your task is to help users with their questions.
Please be thorough and comprehensive in your responses. Make sure to consider
all aspects of the question and provide detailed explanations. If you're unsure
about something, please say so. Always be polite and professional.
User question: ${question}
`;
// After: Concise prompt (fewer input tokens)
const concisePrompt = `Answer concisely: ${question}`;
// Fewer input tokens per call; measure the quality impact with your evals
// Instruct the model to be concise
const prompt = `
${task}
Respond in under 100 words. Use bullet points.
`;
// Or use max_tokens parameter
const response = await client.messages.create({
model: SMALL_MODEL_ID,
max_tokens: 500, // Limit output
messages: [{ role: 'user', content: prompt }]
});
// Use Anthropic prompt caching
const response = await client.messages.create({
model: MODEL_ID,
max_tokens: 1024,
messages: [{
role: 'user',
content: [
{
type: 'text',
text: longSystemContext,
cache_control: { type: 'ephemeral' } // Cache this
},
{ type: 'text', text: userQuestion }
]
}]
});
// Cache reads are billed at a fraction of base input price; cache writes cost more
// than base input. Check usage.cache_read_input_tokens to confirm hits.
interface CostAlert {
type: 'threshold' | 'spike' | 'anomaly';
threshold: number;
action: 'notify' | 'throttle' | 'block';
}
class CostAlertSystem {
private alerts: CostAlert[] = [
{ type: 'threshold', threshold: 100, action: 'notify' }, // $100/day
{ type: 'threshold', threshold: 500, action: 'throttle' }, // $500/day
{ type: 'spike', threshold: 5, action: 'notify' } // 5x normal
];
async checkAlerts(currentCost: number, historicalAvg: number): Promise<void> {
for (const alert of this.alerts) {
if (alert.type === 'threshold' && currentCost > alert.threshold) {
await this.triggerAlert(alert, `Daily cost $${currentCost} exceeds $${alert.threshold}`);
}
if (alert.type === 'spike' && currentCost > historicalAvg * alert.threshold) {
await this.triggerAlert(alert, `Cost spike: $${currentCost} is ${(currentCost/historicalAvg).toFixed(1)}x normal`);
}
}
}
}
interface CostDashboard {
// Real-time
currentHourCost: number;
currentDayCost: number;
currentMonthCost: number;
// Trends
costTrend7d: { date: string; cost: number }[];
projectedMonthEnd: number;
// Breakdown
topOperations: { name: string; cost: number; trend: 'up' | 'down' | 'stable' }[];
modelMix: { model: string; percentage: number }[];
// Alerts
activeAlerts: string[];
budgetUtilization: number;
}
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
/llmops-guardian:token-cost-analyzerfrom llmops-guardian
npx claudepluginhub latestaiagents/agent-skills --plugin llmops-guardian7 skills in this plugin
/ai-audit-loggingUse this skill when implementing audit logging for AI systems. Activate when the user needs to track
AI decisions for compliance, implement audit trails for LLM usage, meet regulatory requirements
(EU AI Act, SOC2), or create accountability records for AI-generated content.
/llm-fallback-chainsUse this skill when implementing fallback strategies for LLM applications. Activate when the user needs
graceful degradation for AI services, multi-provider failover, handling LLM outages, or building
resilient AI systems.
/llm-rate-limitingUse this skill when implementing rate limiting for LLM APIs. Activate when the user needs to prevent
API quota exhaustion, implement backoff strategies, handle rate limit errors, or manage concurrent
LLM requests.
/model-routing-strategyUse this skill when implementing model selection for LLM applications. Activate when the user needs to
choose between different AI models, implement cost-efficient model routing, balance quality vs cost,
or build intelligent model selection systems.
/prompt-caching-patternsUse this skill when implementing caching for LLM applications. Activate when the user wants to reduce
API costs through caching, implement semantic caching, cache LLM responses, optimize repeated prompts,
or set up efficient caching strategies for AI applications.
/prompt-injection-guardUse this skill when securing AI applications against prompt injection. Activate when the user needs to
prevent prompt injection attacks, validate AI inputs, implement input sanitization, or protect against
adversarial prompts.
3 plugins in one repository ship this exact skill · first indexed Nov 5, 2026