usage
Token usage tracking, cost estimation, and usage analytics
What this skill does
# Usage - Complete API Reference
Track token usage, estimate costs, and analyze AI consumption across sessions and users.
---
## Chat Commands
### View Usage
```
/usage Current session usage
/usage today Today's total usage
/usage week This week's usage
/usage month This month's usage
```
### Detailed Breakdown
```
/usage breakdown [today] Cost breakdown by model
/usage by-model Usage by AI model (alias)
/usage by-user Usage by user
/usage history [days] Historical usage (default 7 days)
/usage estimate <model> <in> <out> Estimate cost for tokens
/usage user <id> [today] User-specific usage
```
### Management
```
/usage reset Clear all usage data
```
---
## TypeScript API Reference
### Create Usage Service
```typescript
import { createUsageService } from 'clodds/usage';
const usage = createUsageService({
// Storage
storage: 'sqlite', // 'sqlite' | 'postgres' | 'memory'
dbPath: './usage.db',
// Pricing (per 1M tokens)
pricing: {
'claude-3-opus': { input: 15.00, output: 75.00 },
'claude-3-sonnet': { input: 3.00, output: 15.00 },
'claude-3-haiku': { input: 0.25, output: 1.25 },
'gpt-4': { input: 30.00, output: 60.00 },
'gpt-4o': { input: 5.00, output: 15.00 },
},
// Footer mode
footerMode: 'tokens', // 'off' | 'tokens' | 'full'
});
```
### Record Usage
```typescript
// Record a request
await usage.record({
userId: 'user-123',
sessionId: 'session-456',
model: 'claude-3-sonnet',
inputTokens: 1500,
outputTokens: 800,
durationMs: 2300,
cached: false,
});
```
### Get Session Usage
```typescript
const session = await usage.getSessionUsage('session-456');
console.log(`Session: ${session.sessionId}`);
console.log(`Requests: ${session.requests}`);
console.log(`Input tokens: ${session.inputTokens.toLocaleString()}`);
console.log(`Output tokens: ${session.outputTokens.toLocaleString()}`);
console.log(`Total tokens: ${session.totalTokens.toLocaleString()}`);
console.log(`Est. cost: $${session.estimatedCost.toFixed(4)}`);
console.log(`Duration: ${session.totalDurationMs}ms`);
```
### Get User Usage
```typescript
const user = await usage.getUserUsage('user-123', {
period: 'month', // 'day' | 'week' | 'month' | 'all'
});
console.log(`User: ${user.userId}`);
console.log(`Sessions: ${user.sessions}`);
console.log(`Total tokens: ${user.totalTokens.toLocaleString()}`);
console.log(`Est. cost: $${user.estimatedCost.toFixed(2)}`);
```
### Get Total Usage
```typescript
const total = await usage.getTotalUsage({
from: '2024-01-01',
to: '2024-01-31',
});
console.log(`Total requests: ${total.requests}`);
console.log(`Total tokens: ${total.totalTokens.toLocaleString()}`);
console.log(`Total cost: $${total.estimatedCost.toFixed(2)}`);
```
### Usage by Model
```typescript
const byModel = await usage.getUsageByModel({
period: 'month',
});
for (const [model, stats] of Object.entries(byModel)) {
console.log(`${model}:`);
console.log(` Requests: ${stats.requests}`);
console.log(` Tokens: ${stats.totalTokens.toLocaleString()}`);
console.log(` Cost: $${stats.cost.toFixed(2)}`);
}
```
### Format Footer
```typescript
// Get formatted usage footer for messages
const footer = usage.formatFooter({
inputTokens: 1500,
outputTokens: 800,
model: 'claude-3-sonnet',
});
// Output: "Tokens: 1.5k in / 800 out | Cost: ~$0.02"
```
### Format Summary
```typescript
// Get formatted summary
const summary = await usage.formatSummary({
userId: 'user-123',
period: 'today',
});
console.log(summary);
// "Today: 15 requests | 45k tokens | ~$0.85"
```
### Estimate Cost
```typescript
// Estimate cost for a request
const cost = usage.estimateCost({
model: 'claude-3-opus',
inputTokens: 5000,
outputTokens: 2000,
});
console.log(`Estimated cost: $${cost.toFixed(4)}`);
```
---
## Model Pricing (per 1M tokens)
| Model | Input | Output |
|-------|-------|--------|
| **claude-3-opus** | $15.00 | $75.00 |
| **claude-3-sonnet** | $3.00 | $15.00 |
| **claude-3-haiku** | $0.25 | $1.25 |
| **gpt-4** | $30.00 | $60.00 |
| **gpt-4o** | $5.00 | $15.00 |
| **gpt-4o-mini** | $0.15 | $0.60 |
---
## Footer Modes
| Mode | Output |
|------|--------|
| `off` | No usage shown |
| `tokens` | `Tokens: 1.5k in / 800 out` |
| `full` | `Tokens: 1.5k in / 800 out | Cost: ~$0.02` |
---
## Budget Alerts
```typescript
// Set monthly budget
usage.setBudget({
userId: 'user-123',
monthly: 50.00, // $50/month
alertAt: [0.5, 0.8, 0.95], // Alert at 50%, 80%, 95%
});
// Check budget status
const budget = await usage.checkBudget('user-123');
console.log(`Budget: $${budget.limit}`);
console.log(`Used: $${budget.used.toFixed(2)} (${budget.percent}%)`);
console.log(`Remaining: $${budget.remaining.toFixed(2)}`);
```
---
## Best Practices
1. **Monitor regularly** — Check usage weekly
2. **Set budgets** — Prevent unexpected costs
3. **Use appropriate models** — Haiku for simple tasks
4. **Cache when possible** — Reduce duplicate queries
5. **Review by user** — Identify heavy users
Related in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.