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

openai-cost

v1.0.19

Published

OpenAI token usage cost calculator and fetch-based call tracker utilities.

Readme

openai-cost

Utilities to estimate OpenAI API call costs from response.usage, plus a fetch wrapper to track each OpenAI call.

This folder currently provides:

  • OpenAiCostCalculator: computes USD cost for one call.
  • OpenAICallTracker: wraps fetch so you can process each API response in a callback.

What It Solves

  • Convert OpenAI usage tokens into per-call USD cost.
  • Handle cached input tokens (when pricing supports cache discounts).
  • Support pricing tiers via priorityType: batch, flex, standard, priority.
  • Track costs per bucket/team/project with a callback-based fetch wrapper.

Install

From this folder:

npm install

Project dependency currently used here:

  • @jeromeetienne/openai-cache

Examples also use:

  • openai
  • cacheable
  • @keyv/sqlite
  • chalk (comparator example)

Quick Start: Cost Per Response

import OpenAI from "openai";
import { OpenAiCostCalculator } from "../src/openai_cost_calculator";

const openaiClient = new OpenAI();

const modelName = "gpt-4.1-nano";
const response = await openaiClient.responses.create({
	model: modelName,
	input: "say hello",
});

const usage = response.usage!;
const cost = await OpenAiCostCalculator.calculateCost(modelName, usage);

console.log(cost);
// {
//   inputCost: number,
//   cacheInputCost: number,
//   outputCost: number,
//   totalCost: number
// }

API

OpenAiCostCalculator.calculateCost(modelName, usage, priorityType?)

Signature:

calculateCost(
	modelName: string,
	openaiUsage: OpenAI.Responses.ResponseUsage,
	priorityType: "batch" | "flex" | "standard" | "priority" = "standard"
): Promise<OpenAiCostResponse>

Returns:

  • inputCost: input token cost in USD
  • cacheInputCost: cached input token cost in USD
  • outputCost: output token cost in USD
  • totalCost: total USD cost

Behavior notes:

  • Normalizes date-suffixed models such as gpt-4o-2024-05-13 to gpt-4o.
  • Handles special pricing split for:
    • gpt-5.4 (<272K vs >272K context length)
    • gpt-5.4-pro (<272K vs >272K context length)
  • Throws if no pricing is found for the model.

OpenAICallTracker.getFetchFn(trackerCallback, options?)

Signature:

getFetchFn(
	trackerCallback: (bucketId: string, response: Response) => Promise<void>,
	options?: {
		bucketId?: string;
		originalFetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>;
	}
): Promise<(input: RequestInfo, init?: RequestInit) => Promise<Response>>

Behavior:

  • Calls the provided originalFetch (default: global fetch).
  • Clones the response and passes it to trackerCallback(bucketId, response.clone()).
  • Returns the original response untouched.

Running The Included Examples

From contribs/openai-cost:

npm run sample:basic
npm run sample:comparator
npm run sample:tracker

What they show:

  • examples/openai_cost_example.ts: one call, print usage and cost.
  • examples/openai_cost_comparator.ts: compare cost per call across multiple models.
  • examples/openai_cost_tracker_example.ts: combine cache + tracker callback + persisted sample DB.

Tracker + Cache Pattern

openai_cost_tracker_example.ts demonstrates:

  • wrapping @jeromeetienne/openai-cache fetch with OpenAICallTracker,
  • grouping tracked costs by bucketId,
  • splitting spending into spent (live calls) and saved (cache hits),
  • persisting tracked totals to JSON.

Pricing Table

Pricing is hardcoded in:

  • src/openai_cost_calculator.ts (pricingPerModel)

Update that object when OpenAI pricing changes.

Caveats

  • Cost results are estimates based on the local pricing table.
  • Unknown/new model names will throw until added to pricingPerModel.
  • The calculator currently mutates model pricing values when priorityType is not standard; if you call it repeatedly with mixed priorities in one process, results can drift. If you need strict correctness, clone pricing values before applying priority multipliers.

License

MIT