@sema-agent/core
Version:
Stateless, task-oriented AI agent core
41 lines (40 loc) • 1.8 kB
JavaScript
const per1M = (tokens, price) => price && tokens ? (tokens * price) / 1e6 : 0;
export function computeCostMicroUsd(counts, pricing) {
const billedCacheRead = pricing.cacheReadPer1M !== undefined ? counts.cacheReadTokens : 0;
const billedCacheWrite = pricing.cacheWritePer1M !== undefined ? counts.cacheWriteTokens : 0;
const billedCacheWriteLong = pricing.cacheWriteLongPer1M !== undefined ? counts.cacheWriteTokensLong : 0;
const fullInput = Math.max(0, counts.totalInputTokens - billedCacheRead - billedCacheWrite - billedCacheWriteLong);
const usd = per1M(fullInput, pricing.inputPer1M) +
per1M(billedCacheRead, pricing.cacheReadPer1M) +
per1M(billedCacheWrite, pricing.cacheWritePer1M) +
per1M(billedCacheWriteLong, pricing.cacheWriteLongPer1M) +
per1M(counts.outputTokens, pricing.outputPer1M);
return Math.round(usd * 1e6);
}
export function isModelPriced(model, pricing) {
return pricing?.[model.id] !== undefined || model.cost !== undefined;
}
export function malformedPricingField(pricing) {
for (const f of ["inputPer1M", "outputPer1M"]) {
const v = pricing[f];
if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
return f;
}
for (const f of ["cacheReadPer1M", "cacheWritePer1M", "cacheWriteLongPer1M"]) {
const v = pricing[f];
if (v === undefined)
continue;
if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
return f;
}
return undefined;
}
export function modelCostToPricing(cost) {
return {
inputPer1M: cost?.input ?? 0,
outputPer1M: cost?.output ?? 0,
cacheReadPer1M: cost?.cacheRead,
cacheWritePer1M: cost?.cacheWrite,
cacheWriteLongPer1M: cost?.cacheWrite,
};
}