Skip to main content

Developer library

AI API Cost Estimation Snippets

Copy small dependency-free helpers for planning AI API cost inside prototypes, internal tools, and product dashboards.

Rough token estimators are not exact tokenizers. Provider billing, cache eligibility, long-context tiers, and account-specific rates can differ.

TypeScript

TypeScript LLM cost estimator

Calculate standard input and output token cost for one request.

type TokenPricing = {
  inputPerMillion: number;
  outputPerMillion: number;
};

export function estimateRequestCost(
  inputTokens: number,
  outputTokens: number,
  pricing: TokenPricing,
) {
  const inputCost =
    (Math.max(0, inputTokens) / 1_000_000) *
    pricing.inputPerMillion;
  const outputCost =
    (Math.max(0, outputTokens) / 1_000_000) *
    pricing.outputPerMillion;

  return inputCost + outputCost;
}

TypeScript

TypeScript monthly projection helper

Project a request estimate across active users and a 30-day month.

export function projectMonthlyCost({
  costPerRequest,
  requestsPerActiveUserPerDay,
  activeUsersPerDay,
}: {
  costPerRequest: number;
  requestsPerActiveUserPerDay: number;
  activeUsersPerDay: number;
}) {
  const dailyRequests =
    Math.max(0, requestsPerActiveUserPerDay) *
    Math.max(0, activeUsersPerDay);

  return costPerRequest * dailyRequests * 30;
}

JavaScript

JavaScript API budget guard

Check whether a new request fits inside a client-side daily budget.

export function canSpend({
  spentToday,
  estimatedRequestCost,
  dailyBudget,
  reservePercent = 10,
}) {
  const safeBudget =
    Math.max(0, dailyBudget) *
    (1 - Math.min(100, Math.max(0, reservePercent)) / 100);

  return spentToday + estimatedRequestCost <= safeBudget;
}

Python

Python rough token estimator

Use a conservative character heuristic before exact tokenizer counts are available.

import math

def estimate_tokens(text: str) -> int:
    """Planning estimate only; provider tokenizers differ."""
    normalized = text or ""
    return math.ceil(len(normalized) / 4)

print(estimate_tokens("Estimate this prompt."))

TypeScript

TypeScript embedding cost estimator

Estimate one embedding batch from corpus token volume.

export function estimateEmbeddingBatchCost({
  documents,
  chunksPerDocument,
  tokensPerChunk,
  pricePerMillionTokens,
}: {
  documents: number;
  chunksPerDocument: number;
  tokensPerChunk: number;
  pricePerMillionTokens: number;
}) {
  const totalTokens =
    documents * chunksPerDocument * tokensPerChunk;

  return (totalTokens / 1_000_000) * pricePerMillionTokens;
}

TypeScript

TypeScript SaaS margin helper

Calculate a model-only gross-margin percentage for one monthly cohort.

export function estimateGrossMargin({
  monthlyRevenue,
  monthlyApiCost,
}: {
  monthlyRevenue: number;
  monthlyApiCost: number;
}) {
  if (monthlyRevenue <= 0) return 0;

  return (
    ((monthlyRevenue - monthlyApiCost) / monthlyRevenue) *
    100
  );
}