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

llm-cost-tracker

v1.0.2

Published

Professional NPM package for tracking LLM API costs, managing budgets, and monitoring usage across multiple providers

Readme

LLM Cost Tracker

npm version License: MIT

A professional TypeScript library for tracking and managing costs across multiple LLM providers (OpenAI, Anthropic, Google, etc.). Monitor your AI spending, set budgets, and receive alerts when thresholds are reached.

Features

  • 🎯 Multi-Provider Support - Track costs across OpenAI, Anthropic, Google, and custom providers
  • 💰 Budget Management - Set spending limits with customizable threshold alerts
  • 📊 Detailed Analytics - Get comprehensive cost summaries by provider, model, and time period
  • 🔔 Real-time Alerts - Receive callbacks when budget thresholds are reached or exceeded
  • 🚀 REST API Server - Optional HTTP server for remote cost tracking
  • 💾 Flexible Storage - In-memory storage included, easily extend with your own
  • 🎨 Custom Pricing - Override default pricing for custom models or special rates
  • 📦 Zero Dependencies - Lightweight with minimal production dependencies
  • 🔒 Type-Safe - Full TypeScript support with comprehensive type definitions

Installation

npm install llm-cost-tracker

Quick Start

Basic Usage

import {
  CostTracker,
  InMemoryStorage,
  PriceRegistry,
  BudgetManager,
} from "llm-cost-tracker";

// Initialize components
const storage = new InMemoryStorage();
const priceRegistry = new PriceRegistry();
const budgetManager = new BudgetManager(storage, {
  limitUSD: 100.0,
  thresholdPercent: 80,
});

// Create tracker
const tracker = new CostTracker(storage, priceRegistry, budgetManager);

// Track a cost
const event = await tracker.track({
  provider: "openai",
  model: "gpt-4",
  inputTokens: 1000,
  outputTokens: 500,
});

console.log(`Cost: $${event.totalCostUSD}`);

// Get summary
const summary = await tracker.getSummary();
console.log(`Total spent: $${summary.totalCostUSD}`);
console.log(`Total events: ${summary.eventCount}`);

With Budget Alerts

import { BudgetManager } from "llm-cost-tracker";

const budgetManager = new BudgetManager(storage, {
  limitUSD: 100.0,
  thresholdPercent: 80,
});

// Set up alert callbacks
budgetManager.onThreshold((status) => {
  console.log(`⚠️ Warning: ${status.percentUsed}% of budget used!`);
  console.log(`Spent: $${status.usedUSD} / $${status.limitUSD}`);
});

budgetManager.onExceeded((status) => {
  console.log(`🚨 Budget exceeded! Spent: $${status.usedUSD}`);
  // Take action: disable API calls, send notifications, etc.
});

Using the MCP Server

import { MCPServer } from "llm-cost-tracker/server";

const server = new MCPServer({
  port: 3000,
  host: "localhost",
  costTracker: tracker,
  budgetManager: budgetManager,
});

await server.start();
console.log("MCP Server running on http://localhost:3000");

API Endpoints

Track Cost

POST /cost.track
Content-Type: application/json

{
  "provider": "openai",
  "model": "gpt-4",
  "inputTokens": 1000,
  "outputTokens": 500
}

Get Summary

GET /cost.summary

Get Budget Status

GET /budget.status

Set Budget

POST /budget.set
Content-Type: application/json

{
  "limitUSD": 100.0,
  "thresholdPercent": 80
}

Reset Data

POST /cost.reset

Supported Providers & Models

OpenAI

  • gpt-4 - $0.03/1K input, $0.06/1K output
  • gpt-4-turbo - $0.01/1K input, $0.03/1K output
  • gpt-3.5-turbo - $0.0005/1K input, $0.0015/1K output

Anthropic

  • claude-3-opus - $0.015/1K input, $0.075/1K output
  • claude-3-sonnet - $0.003/1K input, $0.015/1K output
  • claude-3-haiku - $0.00025/1K input, $0.00125/1K output

Google

  • gemini-pro - $0.00025/1K input, $0.0005/1K output
  • gemini-pro-vision - $0.00025/1K input, $0.0005/1K output

Advanced Usage

Custom Pricing

import { PriceRegistry } from "llm-cost-tracker";

const priceRegistry = new PriceRegistry();

// Add custom pricing for a model
priceRegistry.register("openai", "gpt-4-custom", {
  inputPricePerThousand: 0.025,
  outputPricePerThousand: 0.05,
});

// Use it
const event = await tracker.track({
  provider: "openai",
  model: "gpt-4-custom",
  inputTokens: 1000,
  outputTokens: 500,
});

Namespaces for Multi-Tenant Applications

// Track costs for different users/projects
await tracker.track({
  provider: "openai",
  model: "gpt-4",
  inputTokens: 1000,
  outputTokens: 500,
  namespace: "user-123",
});

// Get summary for specific namespace
const userSummary = await tracker.getSummary("user-123");

Cost Simulation (No Persistence)

// Calculate cost without saving to storage
const simulatedEvent = tracker.simulateCost({
  provider: "openai",
  model: "gpt-4",
  inputTokens: 1000,
  outputTokens: 500,
});

console.log(`Estimated cost: $${simulatedEvent.totalCostUSD}`);

Custom Storage Provider

import { StorageProvider, CostEvent } from "llm-cost-tracker";

class DatabaseStorage implements StorageProvider {
  async save(event: CostEvent): Promise<void> {
    // Save to your database
  }

  async loadAll(namespace?: string): Promise<CostEvent[]> {
    // Load from your database
  }

  async reset(namespace?: string): Promise<void> {
    // Clear your database
  }
}

const storage = new DatabaseStorage();
const tracker = new CostTracker(storage, priceRegistry);

API Reference

CostTracker

track(request: TrackingRequest): Promise<CostEvent>

Track a new LLM API call and return the cost event.

Parameters:

  • provider (string) - Provider name (e.g., 'openai', 'anthropic')
  • model (string) - Model name (e.g., 'gpt-4', 'claude-3-opus')
  • inputTokens (number) - Number of input tokens
  • outputTokens (number) - Number of output tokens
  • namespace (string, optional) - Namespace for multi-tenant tracking

Returns: CostEvent with calculated costs

simulateCost(request: TrackingRequest): CostEvent

Calculate cost without persisting to storage.

getSummary(namespace?: string): Promise<CostSummary>

Get aggregated cost summary with breakdowns by provider and model.

reset(namespace?: string): Promise<void>

Clear all tracking data.

BudgetManager

constructor(storage: StorageProvider, config: BudgetConfig)

Create a new budget manager.

Config Options:

  • limitUSD (number) - Maximum spending limit in USD
  • thresholdPercent (number) - Percentage threshold for warnings (0-100)
  • resetInterval (string, optional) - 'daily', 'weekly', 'monthly', or 'manual'
  • namespace (string, optional) - Namespace to track

onThreshold(callback: BudgetCallback): void

Set callback for threshold warnings.

onExceeded(callback: BudgetCallback): void

Set callback for limit exceeded.

checkBudget(): Promise<BudgetStatus>

Check current spending against budget and trigger callbacks.

getStatus(): Promise<BudgetStatus>

Get current budget status without triggering callbacks.

updateConfig(config: Partial<BudgetConfig>): void

Update budget configuration.

reset(): Promise<void>

Reset budget usage data.

PriceRegistry

register(provider: string, model: string, pricing: ModelPricing): void

Register custom pricing for a model.

getPricing(provider: string, model: string): ModelPricing

Get pricing for a specific provider and model.

calculateCost(tokens: number, pricePerThousand: number): number

Calculate cost for a given number of tokens.

Types

interface CostEvent {
  id: string;
  timestamp: Date;
  provider: string;
  model: string;
  inputTokens: number;
  outputTokens: number;
  inputCostUSD: number;
  outputCostUSD: number;
  totalCostUSD: number;
  namespace?: string;
}

interface CostSummary {
  totalCostUSD: number;
  totalInputTokens: number;
  totalOutputTokens: number;
  eventCount: number;
  byProvider: Record<string, ProviderSummary>;
  byModel: Record<string, ModelSummary>;
}

interface BudgetStatus {
  limitUSD: number;
  usedUSD: number;
  percentUsed: number;
  remainingUSD: number;
  thresholdReached: boolean;
  limitExceeded: boolean;
  resetInterval: string;
  nextResetDate?: Date;
}

Examples

Check out the examples directory for complete working examples:

Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Building

npm run build

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © Dominique Houessou

Support

Changelog

1.0.0 (2024-11-20)

Initial release with:

  • Multi-provider cost tracking (OpenAI, Anthropic, Google)
  • Budget management with threshold alerts
  • In-memory storage implementation
  • REST API server (MCP Server)
  • Custom pricing support
  • Namespace support for multi-tenant applications
  • Comprehensive test coverage (92%+)
  • Full TypeScript support