October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

Cost per Task, Not Cost per Token: Build an LLM Cost Calculator in TypeScript

A practical TypeScript guide to estimating what an LLM task costs, accounting for token categories, tools, retries, provider-specific rates, and actual usage.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An LLM task costs more—or less—than a headline input-token rate suggests. To estimate it, count the task’s input and output usage by billable category, include tool or modality fees, and account for retries. The TypeScript calculator below makes those assumptions visible so you can revise them against provider pricing and, after a call, actual usage records.

Why cost per task is a better comparison

A rate per million tokens is only one part of the bill. A representative task can consume input and output tokens at different rates, qualify for cached-input pricing, incur cache-write charges, use tools with separate fees, or require multiple attempts. Tokenization also varies by provider and model: the same prompt may produce different input counts, and models can generate different amounts of output or reasoning.

As an Amazon Associate I earn from qualifying purchases.

OpenAI’s Help Center cautions that “A lower price per million tokens does not necessarily produce a lower total cost: models can tokenize the same text differently and generate different amounts of output or reasoning.” The practical comparison is therefore the estimated cost for the same representative task, with comparable assumptions—not the price of one token category in isolation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For each provider, compare task cost alongside quality, latency, and reliability. Treat quality and success rates as measured or user-supplied inputs; price alone does not identify the best model.

#1 Best Overall
Sale
Desk Calculator with Erasable LCD Notepad Calculators ROATEE Desktop Basic Calculators for Middle School Cute Pocket Simple Calculator Office Desk Accessories Supplies Home Office Essential Big Button
  • 2 in 1with Calculator,Notepad,Stylu: This basic calculator comes with a LCD writing pad and stylus, so you can jot down steps or notes while calculating. Suit for school or office use, it’s a great office desk accessories for both calculations and writing.⚠Note: The erase button work only once the lock key is unlocked
  • Practical Desktop Calculator: This calculators desktop will meet most needs, including basic arithmetic operations like addition, subtraction, multiplication, division, and more.Can meet the computing needs of middle school students. It’s a sleek, practical addition to your desk, ideal for basic office calculations or everyday tasks at home and school
  • Ergonomic Design for Easy Use: Display angled to suit your sight and has a larger size and a clearer display making it easy to see whether you are holding it or laying it flat on a table.Large, well-spaced, responsive keys more comfortable to use and the clearance key is conveniently placed above the notepad for quick erasing, while the textured surface not only enhances the look but also prevents slipping. A smart addition to your aesthetic office supplies
  • Dual Power: Solar & Battery: This pocket calculator is powered by both a solar panel and a replaceable coin battery, ensuring you’ll never run out of power. Say goodbye to battery worries with this eco-friendly solar calculator, perfect for everyday use in any setting
  • Slim, Portable, and Durable Design: Weighing just 5 ounces and designed to be compact like an iPhone 15, this foldable small calculator is easy to carry around. It features a drop-proof body and a built-in stylus that slides neatly into the side prevent loss making it ideal for the office, classroom, or business environments. It’s a cute school or office supplies for you

What usage belongs in the estimate?

Token categories

At minimum, distinguish ordinary input, cached input, cache writes, and output when the provider prices them separately. Do not count cached tokens again as ordinary input. The model below treats input categories as mutually exclusive: inputTokens means uncached input, while cached and cache-write tokens are separate counts.

A request’s billable input may include more than the visible prompt text: message roles and boundaries, tool schemas, images, files, and other non-text inputs can matter. Character counts and rough words-to-tokens conversions are not exact request counts. For example, OpenAI offers an input-token counting API for complete Responses inputs; Gemini documents a countTokens call in its Node.js SDK. These preflight counts can help with input estimates, but neither predicts generated output in advance.

Tools, modalities, and attempts

Tool use may add tokens for definitions, calls, and results, as well as separate server-side tool charges. Media and other capabilities can also have their own billing rules. Record explicit fees rather than folding them into a token rate unless the provider’s published pricing does so.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Desk Portable Calculator, Small Calculator with Writing Notepad, Black
  • 【Multifunctional Calculator】This calculator desktop integrates a calculator and notebook with a stylus pen. No paper is needed, pursuing paperless. You can take notes while calculating, calling, and meetings to improve your study and work efficiency.
  • 【Lightweight and Portable】This is a lightweight calculator with a writing pad and foldable design, and it weighs only 3.73 ounces. It is portable that you can carry it anywhere and it can be removed and used immediately when needed.
  • 【Healthy and Eco-friendly】This calculator features a blue light-free LCD screen to protect your eyes, and you can use it as a notepad on your desk when you're not using the calculator. It is re-writable and can be rewritten over 100,000 times. Reduce paper consumption.
  • 【Mute Design】The calculator is made of comfortable silicone, and soft touch keys, easier to rebound, quiet, and no noise. Bring you a more comfortable touch and quiet using experience. The Mute button does not disturb others, suitable for office, learning, and a variety of use scenarios.
  • 【Multi-scenario use】This high-quality calculator is strong enough to handle calculations in a variety of environments such as business accounting, school, home, office, etc., and would also suitable for various occasions. Whether you are a student, a teacher, or a business person, it offers a fast, efficient experience!

Retries and multiple completions add usage. Decide whether token counts represent one attempt or the whole task before multiplying anything. The example calculator below takes counts for one attempt and applies the expected attempt count once.

TypeScript calculator for one task

This implementation keeps rates and their provenance in data, supports optional billing categories, and calculates expected cost across attempts. The rates are expressed in USD per million units; requests is the number of requests in one attempt, while token counts are totals across those requests. Tool or modality fees are also per attempt.

type Rate = {
  usdPerMillion: number;
  effectiveFrom: string;
  source: string;
};

type Rates = {
  input: Rate;
  cachedInput?: Rate;
  cacheWrite?: Rate;
  output: Rate;
};

type UsagePerAttempt = {
  inputTokens: number;       // Uncached input only
  cachedInputTokens: number;
  cacheWriteTokens: number;
  outputTokens: number;
  requests: number;          // Request count represented by these totals
  toolAndModalityFeesUsd: number;
};

type TaskAssumptions = {
  attempts: number;           // Expected attempts per task
  successProbability: number; // Probability an attempt succeeds, from 0 to 1
};

function tokenCharge(tokens: number, rate: Rate): number {
  return (tokens / 1_000_000) * rate.usdPerMillion;
}

function estimateAttemptCost(usage: UsagePerAttempt, rates: Rates): number {
  const cachedRate = rates.cachedInput ?? rates.input;
  const writeRate = rates.cacheWrite ?? rates.input;

  return (
    tokenCharge(usage.inputTokens, rates.input) +
    tokenCharge(usage.cachedInputTokens, cachedRate) +
    tokenCharge(usage.cacheWriteTokens, writeRate) +
    tokenCharge(usage.outputTokens, rates.output) +
    usage.toolAndModalityFeesUsd
  );
}

function estimateTaskCost(
  usagePerAttempt: UsagePerAttempt,
  assumptions: TaskAssumptions,
  rates: Rates,
) {
  if (!Number.isFinite(assumptions.attempts) || assumptions.attempts <= 0) {
    throw new Error("attempts must be a positive number");
  }
  if (assumptions.successProbability <= 0 || assumptions.successProbability > 1) {
    throw new Error("successProbability must be greater than 0 and at most 1");
  }

  const oneAttemptUsd = estimateAttemptCost(usagePerAttempt, rates);
  const expectedTaskUsd = oneAttemptUsd * assumptions.attempts;

  return {
    oneAttemptUsd,
    expectedTaskUsd,
    expectedCostPerSuccessfulTaskUsd:
      expectedTaskUsd / assumptions.successProbability,
  };
}

const rates: Rates = {
  input: {
    usdPerMillion: 0.05,
    effectiveFrom: "2026-10-04",
    source: "https://openai.com/api/pricing/",
  },
  cachedInput: {
    usdPerMillion: 0.005,
    effectiveFrom: "2026-10-04",
    source: "https://openai.com/api/pricing/",
  },
  cacheWrite: {
    usdPerMillion: 0.0625,
    effectiveFrom: "2026-10-04",
    source: "https://openai.com/api/pricing/",
  },
  output: {
    usdPerMillion: 0.25,
    effectiveFrom: "2026-10-04",
    source: "https://openai.com/api/pricing/",
  },
};

const usagePerAttempt: UsagePerAttempt = {
  inputTokens: 2_000,
  cachedInputTokens: 1_000,
  cacheWriteTokens: 0,
  outputTokens: 500,
  requests: 1,
  toolAndModalityFeesUsd: 0,
};

const estimate = estimateTaskCost(
  usagePerAttempt,
  { attempts: 1.2, successProbability: 0.9 },
  rates,
);

console.log(estimate);

The example uses OpenAI’s GPT-6 Luna standard short-context list rates shown on its pricing page accessed October 4, 2026: $0.05 per million uncached input tokens, $0.005 per million cached input tokens, $0.0625 per million cache-write tokens, and $0.25 per million output tokens. These are illustrative, volatile rates—not a recommendation or a durable budget. Check the live page for the exact model, context and other applicable terms before using them.

Rank #3
Portable Memo Book with Calculator Pen Holder Set, A7 Pocket Jotter Note Pad PU Leather Memo Pad, Mini Business Notepad, Scratch Pad,Handy Writing Pad, Pocket Flip Notebook
  • Package Content - 1 x jotter note pad, 1 x calculator, 1 x pen. 3 in 1 memo pad with pen holder set, simple yet professional, you can have this mini notebook at all times, never forget any important information, thoughts, ideas, notes, etc.
  • Portable Size - 8.8cm x 13.8cm/ 3.5" x 5.4", Weight: 129gr, A little bit larger than A7 size(74mmx105mm). Compact and lightweight to take it anywhere, perfect fit for pocket, briefcase or bag, also suitable for comfortable writing in the palm of the hand.
  • Material - The notepad cover is made from soft & durable PU leather with accent stitching for a clean and professional appearance. An elastic pen holder for convenient pen storage. 30 sheets memo, acid-free paper, lined pages, write comfortably.
  • Multifunctional Uses - Reusable notepad cover with lightweight calculator & pen, the memo pad is refillable, pen can be replaced, it can company you for a long time use. Perfect jotter note pad, memo book, writing pad, scratch pad, business notepad, flip notebook, etc.
  • Occasions - This scratch pad is perfect for school, office, meeting, business, daily life use. A great helper for recording important information, class note, meeting conference summary. Little gift for students, office workers, teachers, kids, parents, etc.

In this example, the usage totals describe one attempt. The 1.2 attempts value is an expected attempt count, not a literal fractional request; it scales the per-attempt cost to represent a workload average. Dividing expected cost by success probability gives an expected cost per successful task under the stated simplifying assumption that each attempt has the same expected cost and success probability. If attempts differ or success depends on attempt number, model that sequence directly instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate the inputs and round only for display

Production code should validate that token counts, request counts, fees, and rates are finite and non-negative; check that each required rate and date is present; and reject a success probability outside the interval (0, 1]. The snippet illustrates the arithmetic, not a tested production package. JavaScript numbers use binary floating point, so preserve precision during calculation and round only after summing charges. For accounting-grade display or aggregation, use decimal arithmetic or integer micro-units.

From estimate to observed bill

Keep three kinds of numbers separate in the product or API:

Rank #4
Desk Calculator with Erasable Writing Pad, 12-Digit Wide Screen Display, 100,000+ Reusable LCD Notepad, One-Click Clear & Lock Function, Solar and Battery Dual Power for Office,School,Business (Black)
  • 【All-in-One Desk Tool: Calculate & Write Without Paper】: Solve math and take notes on the same device! The built-in erasable LCD writing pad supports over 100,000 rewrites—eliminating sticky notes, scratch paper, and clutter. Ideal for accountants, engineers, teachers, and students.
  • 【One-Click Clear + Lock to Protect Critical Calculations】: Erase your notes instantly with the dedicated clear button. Press “Lock” to freeze important numbers during audits, exams, or client meetings—no more accidental wipes when you need accuracy most.
  • 【Integrated Pull-Out Stylus – Never Lose Your Pen Again】: The smooth-sliding stylus stores inside the calculator body for instant access. No magnets—just reliable, secure storage that keeps your workspace tidy and your tool always ready.
  • 【12-Digit Wide Screen & Dual Power for All-Day Reliability】: Large, high-contrast digits reduce errors in complex calculations. Solar-powered with a CR2032 backup battery, it works flawlessly in bright offices, dim classrooms, or during power outages.
  • 【Professional Design for Office Desks, Classrooms & Home Use】: Sleek black finish with anti-slip base stays stable during use. Compact enough for backpacks or briefcases—perfect for business professionals, remote workers, and families managing budgets or homework.
  • Estimate from assumptions: Expected input and output tokens, cache mix, feature fees, attempts, and success probability supplied by the user or estimated from representative tasks.
  • Preflight input count: A provider counting endpoint or SDK result where available. It can improve the input estimate, but it cannot know the output tokens before generation.
  • Observed usage: Usage fields returned after a call, used to reconcile the estimate and calibrate future task assumptions. Fields and accounting detail vary by endpoint.

OpenAI’s usage documentation notes endpoint-specific usage fields. Use the provider’s actual response or billing records as the authoritative basis for observed usage; do not present an assumption-based estimate as an invoice. Log the model and usage categories alongside each result so unusually expensive tasks can be traced to a larger prompt, output, retry, or feature charge.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Compare providers on the same representative task

Build the comparison from a task that resembles real work: the same input materials, instruction, output format, tool needs, and success criteria. Then enter provider-specific counts and rates. Do not assume identical tokenization or output size just because the textual task is the same.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Comparison item What to record
Model and pricing basis Model name, API surface, currency, billing unit, service tier, applicable context or modality, effective date, and source.
Usage mix Input, cached input, cache writes, output, and any other billed token or media categories; note how each count was obtained.
Features and fees Tools, media, server-side capabilities, batch mode, or other explicit charges included in the task.
Task reliability Expected attempts or retries and success probability, with the basis stated as measured or user-supplied.
Outcome dimensions Estimated cost per task and per successful task, assessed alongside latency and task quality on the same evaluation.

Leave a category visible when a provider’s applicable price or usage count is unknown; do not silently treat it as free. If the relevant pricing page does not state a value for your model, modality, or service tier, mark it as not stated and avoid presenting the resulting total as directly comparable.

Best Value
Desk Calculator, Desktop Small Calculators with Writing Notepad, Basic 4-Function Math Large Button Calculator, School Supplies, Middle/High School Students (White)
  • Best School Supplies :The large button calculator and notepad are designed in one piece,you can make notes while calculating,improve study and work efficiency.The calculator supports calculations with up to 12 digits and notepad acts as a cover to protect the calculator from dirt.Press the clear button to erase the notes and protect personal privacy .
  • Lightweight and Portable:This is a lightweight calculator with writing tablet,foldable design, weighs only 4 oz.It is so compact that you can carry it in your pocket,can be quickly removed and used immediately when needed,convenient for taking notes on phone calls, quick notes, and meeting minutes .
  • Healthy and Sustainable: The LCD screen is designed to protect your eyes from blue light. When you're not using the calculator, it can also serve as a notepad on your desk. It can be written on repeatedly, helping to reduce paper usage, and eliminating the need for a shredder to dispose of paper .
  • Mute Design:Adopt high quality silicone large button, feel comfortable, suitable for daily calculations.Mute button do not disturb others, suitable for office,learning and a variety of use scenarios .
  • 1-Year Protection Plan: The product includes a 1-year protection plan with detailed instructions. If any issues arise within this period, it can be directly replaced. Feel free to contact us at any time, and we will respond as quickly as possible .

Keep rates current and auditable

Store rates as configuration rather than burying them in the arithmetic. Along with each category’s price, retain the model, currency, billing unit, effective date, and source URL. Add metadata for region, context length, modality, service tier, discounts, and API surface wherever those conditions affect the rate. Let users supply custom rates when their contract or deployment differs from a public list price.

Pricing changes, and provider pages may include future-dated rates. As of the official pages accessed October 4, 2026, Anthropic lists Claude Sonnet 4.6 at $1.50 per million input tokens and $7.50 per million output tokens; its page should be checked for cache, batch, context, and tool details before applying those rates. Google’s Gemini pricing page includes a text-input rate of $0.25 per million tokens through December 31, 2026, changing to $0.50 from January 1, 2027; verify the associated model row and service tier on the live page. These examples show why a price needs its model and effective-date context, not just a number.

Refresh the rate data before using estimates for budgets, and keep the previous version if you need to explain an older estimate. A task estimate is only as useful as its usage assumptions and applicable rates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.