UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

58 lines (57 loc) • 2.9 kB
import { callRatesOf, priceTableOf } from "../core/pricing.js"; import { isExactCount } from "./usage-reasoning.js"; export function servedAtFastSpeed(usage) { return usage.speed === "fast"; } const refusedBeforeAnyStream = new WeakSet(); export function markRefusedBeforeAnyStream(usage) { refusedBeforeAnyStream.add(usage); } export function wasRefusedBeforeAnyStream(usage) { return typeof usage === "object" && usage !== null && refusedBeforeAnyStream.has(usage); } export function usageOfStatement(model, family, statement, reasoning) { let unreadable = false; const stated = (v) => { if (v === undefined || v === null) return undefined; if (isExactCount(v)) return v; unreadable = true; return undefined; }; const inputStated = stated(statement.input); const outputStated = stated(statement.output); const cacheRead = stated(statement.cacheRead); const cacheWrite = stated(statement.cacheWrite); const longStated = stated(statement.cacheWriteLong); const subsetBroken = longStated !== undefined && (cacheWrite === undefined || longStated > cacheWrite); if (subsetBroken) unreadable = true; const cacheWriteLong = subsetBroken ? undefined : longStated; const totalStated = stated(statement.total); const input = inputStated ?? 0; const output = outputStated ?? 0; const speed = statement.speed === "fast" ? "fast" : undefined; const c = callRatesOf(priceTableOf(model, undefined).table, servedAtFastSpeed({ speed })).rates; const costInput = (input / 1e6) * (c.inputPer1M ?? 0); const costOutput = (output / 1e6) * (c.outputPer1M ?? 0); const excludes = family === "input-excludes-cached"; const totalTokens = excludes ? input + output + (cacheRead ?? 0) + (cacheWrite ?? 0) : (totalStated ?? input + output); const costCacheRead = excludes ? ((cacheRead ?? 0) / 1e6) * (c.cacheReadPer1M ?? 0) : 0; const costCacheWrite = excludes ? (((cacheWrite ?? 0) - (cacheWriteLong ?? 0)) / 1e6) * (c.cacheWritePer1M ?? 0) + ((cacheWriteLong ?? 0) / 1e6) * (c.cacheWriteLongPer1M ?? c.cacheWritePer1M ?? 0) : 0; const usage = { input, output, ...(cacheRead !== undefined ? { cacheRead } : {}), ...(cacheWrite !== undefined ? { cacheWrite } : {}), ...(cacheWriteLong !== undefined ? { cacheWriteLong } : {}), totalTokens, ...(reasoning.reasoning !== undefined ? { reasoning: reasoning.reasoning } : {}), ...(speed !== undefined ? { speed } : {}), cost: { input: costInput, output: costOutput, cacheRead: costCacheRead, cacheWrite: costCacheWrite, total: costInput + costOutput + costCacheRead + costCacheWrite }, }; return { usage, missing: inputStated === undefined || outputStated === undefined || unreadable || reasoning.unreadable }; }