UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

40 lines (39 loc) • 2.11 kB
import { servedAtFastSpeed, wasRefusedBeforeAnyStream } from "../../brain/usage-reading.js"; import { callRatesOf, computeCostMicroUsd } from "../pricing.js"; export function cacheFamilyOf(model) { const override = model.params?.promptCacheFamily; if (override === "input-excludes-cached" || override === "anthropic") return "input-excludes-cached"; if (override === "input-includes-cached" || override === "openai") return "input-includes-cached"; return model.api === "anthropic-messages" || model.api === "bedrock-converse-stream" ? "input-excludes-cached" : "input-includes-cached"; } export function promptTokensOf(family, u) { return family === "input-excludes-cached" ? u.input + u.cacheRead + u.cacheWrite : u.input; } export function uncachedInputTokensOf(family, u) { return Math.max(0, promptTokensOf(family, u) - u.cacheRead - u.cacheWrite); } export function usageCostMicroUsd(family, u, pricing) { const { rates, tierDeclared } = callRatesOf(pricing, servedAtFastSpeed(u)); const normalized = { input: u.input || 0, cacheRead: u.cacheRead || 0, cacheWrite: u.cacheWrite || 0 }; const totalInputTokens = promptTokensOf(family, normalized); const uncachedInputTokens = uncachedInputTokensOf(family, normalized); const longWrites = rates.cacheWriteLongPer1M !== undefined ? Math.max(0, Math.min(u.cacheWriteLong || 0, normalized.cacheWrite)) : 0; const costMicroUsd = computeCostMicroUsd({ totalInputTokens, cacheReadTokens: normalized.cacheRead, cacheWriteTokens: normalized.cacheWrite - longWrites, cacheWriteTokensLong: longWrites, outputTokens: u.output || 0, }, rates); return { totalInputTokens, uncachedInputTokens, costMicroUsd, tierPriced: tierDeclared }; } export function callPriced(tableExists, tierPriced, u, usageMissing) { if (tableExists && tierPriced) return true; const billedNothing = !(u.input || u.output || u.cacheRead || u.cacheWrite || u.totalTokens); return billedNothing && (!usageMissing || wasRefusedBeforeAnyStream(u)); }