claude-pricing
v0.1.0
Published
Calculate and track Claude API costs from token usage. Bundled pricing table + custom override. Zero dependencies.
Maintainers
Readme
claude-pricing
Calculate and track Claude API costs from token usage. Bundled pricing table + custom overrides. Zero dependencies.
import { calculateCost, formatUSD, CostTracker } from "claude-pricing";
// One-shot cost calculation
const cost = calculateCost("claude-opus-4-7", {
input_tokens: 1500,
output_tokens: 800,
cache_read_input_tokens: 5000,
});
console.log(formatUSD(cost.total)); // "$0.0900"
// Session tracker with budget alert
const tracker = new CostTracker({
budgetUSD: 1.0,
onBudgetExceeded: (total, budget) =>
alert(`Budget blown: ${formatUSD(total)} > ${formatUSD(budget)}`),
});
tracker.add("claude-opus-4-7", usage, { label: "planning" });
tracker.add("claude-sonnet-4-6", usage, { label: "draft" });
console.log(formatUSD(tracker.total().total));
console.log(tracker.byModel());Why this exists
You're running Claude API in production. You want to know:
- What did this one call cost? The SDK returns
usagebut doesn't tell you the dollars. - Did this session blow my budget? You want a running total across an agent loop.
- Where's my money going? Per-model breakdown for cost optimization.
- What about cache and batch? The pricing math is non-obvious (1.25× input for cache write, 50% off for batch).
This package is ~180 lines of TypeScript. Zero deps. Bundled with up-to-date Anthropic pricing, but everything is overridable because list prices change and you may have a custom contract.
Install
npm install claude-pricingAPI
calculateCost(model, usage, options?)
function calculateCost(
model: string,
usage: TokenUsage,
options?: { pricing?: ModelPricing | Record<string, ModelPricing>; batch?: boolean }
): CostBreakdown;Returns { input, output, cacheWrite, cacheRead, total } — all in USD.
CostTracker
const tracker = new CostTracker({
pricing?: customTable,
budgetUSD?: 5.00,
onBudgetExceeded?: (total, budget) => ...,
});
tracker.add(model, usage, { label?: 'step-1', batch?: true });
tracker.total(); // { input, output, cacheWrite, cacheRead, total }
tracker.byModel(); // { 'claude-opus-4-7': { calls, usage, breakdown }, ... }
tracker.reset();
tracker.getEntries(); // readonly array of { model, usage, breakdown, timestamp, label }formatUSD(amount)
Smart-precision formatter:
$1.23for amounts ≥ $1$0.0123for amounts ≥ $0.01$0.000123for sub-cent
ANTHROPIC_PRICING
The bundled default table (USD per million tokens):
| Model | Input | Output | Cache write | Cache read | |---|---|---|---|---| | claude-opus-4-7 | $15 | $75 | $18.75 | $1.50 | | claude-sonnet-4-6 | $3 | $15 | $3.75 | $0.30 | | claude-haiku-4-5 | $0.80 | $4 | $1.00 | $0.08 |
⚠️ Snapshot taken 2026-05. Verify against Anthropic pricing for production. Pass your own table via options.pricing for current rates.
Recipes
Override pricing for current rates
const myPricing = {
"claude-opus-4-7": { input: 14, output: 70 }, // discounted contract
};
const cost = calculateCost(model, usage, { pricing: myPricing });Use for any custom/fine-tuned model
const cost = calculateCost(
"my-fine-tune",
usage,
{ pricing: { input: 8, output: 24 } } // single ModelPricing
);Pair with claude-stream-collector
import { collectStream } from "claude-stream-collector";
import { calculateCost, formatUSD } from "claude-pricing";
const result = await collectStream(stream);
const cost = calculateCost(result.model, result.usage);
console.log(formatUSD(cost.total));The TokenUsage shape is compatible — pass result.usage directly.
Track an agent loop with budget cap
const tracker = new CostTracker({
budgetUSD: 0.10,
onBudgetExceeded: () => { throw new Error("Cost limit reached"); }
});
for (const step of agent.run()) {
tracker.add(step.model, step.usage, { label: step.name });
// throws automatically when total > $0.10
}
console.log(tracker.byModel());Batch API (50% off)
calculateCost(model, usage, { batch: true });
// Or per add():
tracker.add(model, usage, { batch: true });Tests & build
npm install
npm test # vitest run
npm run build # tscLicense
MIT — © 2026 xiangnuans
Part of a series
The 3rd package in small, focused Claude SDK helpers built in public.
- ✅
claude-stream-collector— Consume streaming events into typed result - ✅
claude-retry— Smart retry with backoff - ✅
claude-pricing— Cost calculation + session tracker (this package) - 🚧
claude-prompt-toolkit— Prompt templating, versioning
Follow the journey: ship-log-2026.
