token-cost-analyzer
Use this skill when analyzing and optimizing LLM API costs. Activate when the user wants to reduce AI API spending, understand token usage, audit LLM costs, optimize prompts for cost efficiency, or track and report on AI expenditure.
What this skill does
# Token Cost Analyzer
Audit, analyze, and optimize your LLM API spending.
## When to Use
- Monthly AI bill higher than expected
- Need to understand where tokens are spent
- Optimizing prompts for cost efficiency
- Setting up cost monitoring
- Budgeting for AI features
## Token Pricing Reference (2026)
### Anthropic Claude
| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|-------|----------------------|------------------------|
| Claude 3 Opus | $15.00 | $75.00 |
| Claude 3.5 Sonnet | $3.00 | $15.00 |
| Claude 3 Haiku | $0.25 | $1.25 |
### OpenAI
| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|-------|----------------------|------------------------|
| GPT-4 Turbo | $10.00 | $30.00 |
| GPT-4o | $5.00 | $15.00 |
| GPT-4o mini | $0.15 | $0.60 |
| o1 | $15.00 | $60.00 |
### Google
| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|-------|----------------------|------------------------|
| Gemini 1.5 Pro | $3.50 | $10.50 |
| Gemini 1.5 Flash | $0.075 | $0.30 |
## Cost Calculation
```typescript
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
```
## Cost Tracking System
```typescript
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);
}
}
```
## Cost Analysis Report
```typescript
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
const haiku = byModel.get('claude-haiku-4-5') || 0;
const opus = byModel.get('claude-opus-4-6') || 0;
if (opus > haiku * 10) {
opportunities.push('Consider using Haiku for simpler tasks - Opus usage is 10x higher');
}
// 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
}
};
}
```
## Optimization Strategies
### 1. Model Selection
```typescript
type TaskComplexity = 'simple' | 'medium' | 'complex';
function selectCostEffectiveModel(
task: string,
complexity: TaskComplexity
): string {
const modelMap = {
simple: 'gpt-4o-mini', // $0.15/$0.60 per 1M
medium: 'claude-haiku-4-5', // $0.25/$1.25 per 1M
complex: 'claude-sonnet-4-6' // $3/$15 per 1M
};
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';
}
```
### 2. Prompt Optimization
```typescript
// 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}`;
// Savings: ~80% reduction in input tokens
```
### 3. Response Length Control
```typescript
// 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: 'claude-haiku-4-5',
max_tokens: 500, // Limit outputRelated 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.