npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/ai-cost-tracker

v1.2.0

Published

Token usage and cost tracking for AI providers (OpenAI, Anthropic) with per-model pricing, usage reports, and budget alerts

Readme

@bernierllc/ai-cost-tracker

Token usage and cost tracking for AI providers (OpenAI, Anthropic) with per-model pricing, usage reports, and budget alerts.

Features

  • Multi-Provider Support: OpenAI (GPT-3.5, GPT-4) and Anthropic (Claude 3)
  • Accurate Pricing: Per-model pricing data with separate input/output token costs
  • Budget Management: Set budgets with configurable warning thresholds and exceeded alerts
  • Usage Analytics: Detailed usage reports by provider, model, and time period
  • Flexible Storage: In-memory or file-based storage with custom adapter support
  • Event System: Subscribe to cost tracking, budget warning, and budget exceeded events
  • Type-Safe: Full TypeScript support with strict typing

Installation

npm install @bernierllc/ai-cost-tracker

Quick Start

import { AICostTracker } from '@bernierllc/ai-cost-tracker';

// Create tracker with budget
const tracker = new AICostTracker({
  budget: {
    maxUSD: 100,
    warningThreshold: 0.8 // Alert at 80%
  }
});

// Track AI usage
tracker.track('openai', 'gpt-4', {
  inputTokens: 1000,
  outputTokens: 500,
  totalTokens: 1500
});

// Get current cost
const cost = tracker.getCost(); // $0.06

// Get usage report
const report = tracker.getUsage();
console.log(report.totalCostUSD); // 0.06
console.log(report.totalTokens);  // { inputTokens: 1000, outputTokens: 500, totalTokens: 1500 }

// Check budget status
const status = tracker.getBudgetStatus();
console.log(status.percentageUsed); // 0.06%
console.log(status.remainingUSD);   // $99.94

Usage

Basic Cost Tracking

import { AICostTracker } from '@bernierllc/ai-cost-tracker';

const tracker = new AICostTracker();

// Track OpenAI GPT-4 usage
tracker.track('openai', 'gpt-4', {
  inputTokens: 2000,
  outputTokens: 1000,
  totalTokens: 3000
});

// Track Anthropic Claude 3 Opus usage
tracker.track('anthropic', 'claude-3-opus-20240229', {
  inputTokens: 1500,
  outputTokens: 750,
  totalTokens: 2250
});

// Get total cost across all providers
const totalCost = tracker.getCost(); // $0.18

// Get cost for specific provider
const openaiCost = tracker.getCost('openai'); // $0.12

Usage Reports

// Get overall usage report
const report = tracker.getUsage();
console.log(report);
// {
//   totalCalls: 2,
//   totalTokens: { inputTokens: 3500, outputTokens: 1750, totalTokens: 5250 },
//   totalCostUSD: 0.18,
//   byModel: {
//     'openai:gpt-4': { calls: 1, tokens: {...}, costUSD: 0.12 },
//     'anthropic:claude-3-opus-20240229': { calls: 1, tokens: {...}, costUSD: 0.06 }
//   }
// }

// Get report for specific provider
const openaiReport = tracker.getUsage('openai');
console.log(openaiReport.totalCostUSD); // 0.12

Budget Management

const tracker = new AICostTracker({
  budget: {
    maxUSD: 50,
    warningThreshold: 0.8 // 80%
  }
});

// Subscribe to budget events
tracker.on('budget.warning', (status) => {
  console.log(`Warning: ${status.percentageUsed.toFixed(2)}% of budget used`);
});

tracker.on('budget.exceeded', (status) => {
  console.log(`Budget exceeded! Spent $${status.spentUSD.toFixed(2)}`);
});

// Track usage
tracker.track('openai', 'gpt-4', {
  inputTokens: 100000,
  outputTokens: 50000,
  totalTokens: 150000
}); // Cost: $6.00

// Check budget status
const status = tracker.getBudgetStatus();
console.log(status);
// {
//   budgetUSD: 50,
//   spentUSD: 6.00,
//   remainingUSD: 44.00,
//   percentageUsed: 12,
//   isExceeded: false,
//   isWarning: false
// }

File-Based Storage

import { AICostTracker, FileStorage } from '@bernierllc/ai-cost-tracker';

// Use file storage (persists across restarts)
const tracker = new AICostTracker({
  storage: new FileStorage('./cost-data.json')
});

tracker.track('openai', 'gpt-4', {
  inputTokens: 1000,
  outputTokens: 500,
  totalTokens: 1500
});

// Data is automatically saved to ./cost-data.json
// On next run, data is automatically loaded

Custom Storage Adapter

import { AICostTracker, CostStorageAdapter, CostData } from '@bernierllc/ai-cost-tracker';

class DatabaseStorage implements CostStorageAdapter {
  async store(record: CostData): Promise<void> {
    await db.insert('cost_records', record);
  }

  async getAll(): Promise<CostData[]> {
    return await db.query('SELECT * FROM cost_records');
  }

  async filter(criteria: any): Promise<CostData[]> {
    // Implement filtering logic
  }

  async clear(): Promise<void> {
    await db.delete('cost_records');
  }
}

const tracker = new AICostTracker({
  storage: new DatabaseStorage()
});

Filtering Records

// Get records for date range
const januaryRecords = tracker.getRecords({
  startDate: new Date('2025-01-01'),
  endDate: new Date('2025-01-31')
});

// Get records for specific provider and model
const gpt4Records = tracker.getRecords({
  provider: 'openai',
  model: 'gpt-4'
});

API Reference

AICostTracker

Main class for tracking AI costs.

Constructor

new AICostTracker(config?: CostTrackerConfig)

Config Options:

  • budget?: BudgetConfig - Budget configuration (optional)
  • storage?: CostStorageAdapter - Storage adapter (defaults to in-memory)
  • enableLogging?: boolean - Enable logging (defaults to true)

Methods

track(provider, model, tokens): void

Track token usage for an AI operation.

  • provider: 'openai' | 'anthropic' - AI provider
  • model: string - Model name (e.g., 'gpt-4', 'claude-3-opus-20240229')
  • tokens: TokenUsage - Token usage ({ inputTokens, outputTokens, totalTokens })

getCost(provider?: AIProvider): number

Get total cost in USD (optionally filtered by provider).

getUsage(provider?: AIProvider): UsageReport

Get detailed usage report (optionally filtered by provider).

getBudgetStatus(): BudgetStatus | undefined

Get current budget status (returns undefined if no budget configured).

getRecords(criteria?): CostData[]

Get cost records filtered by criteria:

  • provider?: 'openai' | 'anthropic'
  • model?: string
  • startDate?: Date
  • endDate?: Date

on(event, handler): void

Subscribe to events:

  • 'cost.tracked' - Emitted when cost is tracked
  • 'budget.warning' - Emitted when warning threshold reached
  • 'budget.exceeded' - Emitted when budget exceeded

off(event, handler): void

Unsubscribe from events.

clear(): void

Clear all tracking data.

Supported Models

OpenAI:

  • GPT-4: gpt-4, gpt-4-turbo, gpt-4-turbo-preview, gpt-4-32k
  • GPT-3.5: gpt-3.5-turbo, gpt-3.5-turbo-16k

Anthropic:

  • Claude 3: claude-3-opus-20240229, claude-3-sonnet-20240229, claude-3-haiku-20240307
  • Claude 2: claude-2.1, claude-2.0, claude-instant-1.2

See MODEL_PRICING export for complete list.

Utility Functions

import {
  getModelPricing,
  isModelSupported,
  getSupportedModels,
  calculateCost
} from '@bernierllc/ai-cost-tracker';

// Get pricing for a model
const pricing = getModelPricing('openai', 'gpt-4');
// { inputPer1k: 0.03, outputPer1k: 0.06 }

// Check if model is supported
const supported = isModelSupported('openai', 'gpt-4'); // true

// Get all supported models for a provider
const models = getSupportedModels('openai');
// ['gpt-4', 'gpt-3.5-turbo', ...]

// Calculate cost manually
const cost = calculateCost('openai', 'gpt-4', {
  inputTokens: 1000,
  outputTokens: 500,
  totalTokens: 1500
}); // 0.06

TypeScript Support

This package is written in TypeScript and includes full type definitions.

import type {
  AIProvider,
  TokenUsage,
  CostData,
  UsageReport,
  BudgetConfig,
  BudgetStatus,
  ModelPricing,
  CostStorageAdapter,
  CostTrackerConfig
} from '@bernierllc/ai-cost-tracker';

Integration Status

Logger Integration

Status: Integrated

Justification: This package uses @bernierllc/logger for structured logging of cost tracking operations. Logs include token usage, cost calculations, budget warnings, and cost aggregation events to help with debugging and monitoring AI spending.

Pattern: Direct integration - logger is a required dependency for this package.

NeverHub Integration

Status: Not applicable

Justification: This is a core utility package that performs cost tracking calculations. It does not participate in service discovery, event publishing, or service mesh operations. Cost tracking is a stateless utility operation that doesn't require service registration or discovery.

Pattern: Core utility - no service mesh integration needed.

Docs-Suite Integration

Status: Ready

Format: TypeDoc-compatible JSDoc comments are included throughout the source code. All public APIs are documented with examples and type information.

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

Related Packages