src/context/usage.ts
3 KB - Voir le fichier brut
// Turning token counts into money and into "how full is the context" (lab 03).
//
// The API reports four kinds of tokens separately, and they are priced differently:
// input_tokens not cached: full input price
// cache_creation_input_tokens written to the cache: more than the input price
// cache_read_input_tokens read from the cache: a small fraction of the input price
// output_tokens generated (including thinking): the output price
import type { StewardConfig } from '../config/config.ts';
import type { TurnUsage } from '../core/turn-loop.ts';
export type Price = StewardConfig['pricing'][string];
type Tokens = Pick<
TurnUsage,
'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'
>;
/**
* Cost in USD of one request, or of tokens priced as one block. A model with a long-context
* tier (Claude Haiku 5.5) charges the higher rates for the whole request when its prompt, all
* input including cache reads and writes, is over the threshold.
*/
export function costOf(usage: Tokens, price: Price | undefined): number | undefined {
if (!price) return undefined;
const prompt = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
const rates =
price.longContext && prompt > price.longContext.overTokens ? price.longContext : price;
const perToken = (perMillion: number) => perMillion / 1_000_000;
return (
usage.inputTokens * perToken(rates.input) +
usage.cacheWriteTokens * perToken(rates.cacheWrite) +
usage.cacheReadTokens * perToken(rates.cacheRead) +
usage.outputTokens * perToken(rates.output)
);
}
/**
* Cost in USD of a turn: each request at the price of the model that served it. Turns from
* older logs have no request list and are priced as one block at the turn's model. Undefined
* when a model has no price in the config.
*/
export function costOfTurn(
usage: TurnUsage,
turnModel: string,
pricing: StewardConfig['pricing'],
): number | undefined {
if (!usage.requests?.length) return costOf(usage, pricing[turnModel]);
let usd = 0;
for (const request of usage.requests) {
const cost = costOf(request, pricing[request.model]);
if (cost === undefined) return undefined;
usd += cost;
}
return usd;
}
/** Total cost of turns that may have used different models. */
export function totalCost(
turns: readonly { model: string; usage: TurnUsage }[],
pricing: StewardConfig['pricing'],
): { usd: number; unpriced: number } {
let usd = 0;
let unpriced = 0;
for (const turn of turns) {
const cost = costOfTurn(turn.usage, turn.model, pricing);
if (cost === undefined) unpriced++;
else usd += cost;
}
return { usd, unpriced };
}
/** Share of all input tokens that were served from the cache. */
export function cacheHitRate(usage: TurnUsage): number {
const all = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
return all === 0 ? 0 : usage.cacheReadTokens / all;
}
export function formatUsd(usd: number): string {
return usd < 0.01 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`;
}