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

tokencost-js

v1.0.1

Published

JavaScript port of tokencost

Readme

tokencost-js

A JavaScript/TypeScript port of the tokencost library that works in any JavaScript runtime.

This library calculates token counts and costs for prompts and completions of various LLM models. It supports Anthropic Claude models using their token counting API endpoint from their official SDK. This requires for the Anthropic SDK to be configured via environment variables for Anthropic cost calculations to work. If you calculate the costs of a completion for an Anthropic model, it will fail unless you set these environment variables.

[!CAUTION] Make sure you do not expose your ANTHROPIC_API_KEY on the internet! You should never expose any secrets in the bundle of a web or mobile app. The demo site supports Anthropic calculations because it uses a Backmesh LLM API Gatekeeper for communication with the Anthropic API. The ANTHROPIC_BASE_URL is set to the Backmesh URL and the ANTHROPIC_API_KEY is set to a JWT generated using anonymous Firebase authentication. Backmesh is an open source Backend as a Service (BaaS) available here.

Installation

npm install tokencost-js

Usage

Basic Usage

import { 
  countMessageTokens, 
  countStringTokens, 
  calculatePromptCost, 
  calculateCompletionCost, 
  calculateAllCostsAndTokens 
} from 'tokencost-js';

// Count tokens in a string
const stringTokens = countStringTokens("Hello, world!", "gpt-4");
console.log(`String tokens: ${stringTokens}`);

// Count tokens in messages
const messages = [
  { role: "user", content: "Hello, how are you?" },
  { role: "assistant", content: "I'm doing well, thank you for asking!" }
];
const messageTokens = countMessageTokens(messages, "gpt-3.5-turbo");
console.log(`Message tokens: ${messageTokens}`);

// Calculate prompt cost
const promptCost = calculatePromptCost("What is the capital of France?", "gpt-4");
console.log(`Prompt cost: $${promptCost.toFixed(6)}`);

// Calculate completion cost
const completionCost = calculateCompletionCost("The capital of France is Paris.", "gpt-4");
console.log(`Completion cost: $${completionCost.toFixed(6)}`);

// Calculate all costs and tokens
const allCosts = calculateAllCostsAndTokens(
  "What is the capital of France?",
  "The capital of France is Paris.",
  "gpt-4"
);
console.log(allCosts);

Working with Messages

import { calculatePromptCost, type Message } from 'tokencost-js';

const messages: Message[] = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "Tell me about the solar system." },
  { role: "assistant", content: "The solar system consists of the Sun and everything that orbits around it." },
  { role: "user", content: "How many planets are there?" }
];

const cost = calculatePromptCost(messages, "gpt-4");
console.log(`Cost to process these messages: $${cost.toFixed(6)}`);

Updating Token Costs

The library comes with a static set of token costs, but you can update them with the latest costs from the LiteLLM cost tracker:

import { updateTokenCosts, TOKEN_COSTS } from 'tokencost-js';

// Update token costs
await updateTokenCosts();
console.log("Token costs updated:", TOKEN_COSTS);

Supported Models

The library supports a wide range of models including:

  • OpenAI models (GPT-3.5, GPT-4, GPT-4o, etc.)
  • Claude models (with estimated token counts)
  • And many more