跳到主要内容
CNode

Node.js 用量核对:避免重复计算缓存读取费用

分享
Aairelaycheck发布于 20 小时前
0710

在处理用量账单时,首先要确认:缓存读取量是总输入的一部分,还是单独统计的数量。两种口径不能套用同一公式。

下面只演示“总输入已经包含缓存读取”的情况。普通输入量等于总输入减去缓存读取量,再分别乘对应费率。函数要求显式传入 inputIncludesCache,校验数量和费率;缺失或未知值不能默认补零。

function billSnapshot(s) {
  if (s.inputIncludesCache !== true) {
    throw new Error('请先确认输入总数包含缓存读取');
  }
  for (const n of [s.totalInput, s.cacheRead, s.output]) {
    if (!Number.isSafeInteger(n) || n < 0) throw new Error('Token 数无效');
  }
  if (s.cacheRead > s.totalInput) throw new Error('缓存不能大于总输入');
  for (const n of [s.inputRate, s.cacheRate, s.outputRate, s.billed]) {
    if (!Number.isFinite(n) || n < 0) throw new Error('费率或实扣无效');
  }
  const uncached = s.totalInput - s.cacheRead;
  const expected = (uncached * s.inputRate + s.cacheRead * s.cacheRate
    + s.output * s.outputRate) / 1_000_000;
  return { uncached, expected: expected.toFixed(6), billed: s.billed.toFixed(6),
    delta: (s.billed - expected).toFixed(6) };
}

console.log(billSnapshot({
  inputIncludesCache: true, totalInput: 42508, cacheRead: 40320, output: 70,
  inputRate: 8, cacheRate: 0.8, outputRate: 40, billed: 0.052559,
}));
// { uncached: 2188, expected: '0.052560', billed: '0.052559', delta: '-0.000001' }

示例取自 AI Relay Check 的一份历史记录:2026-09-19 的 OpenOx 十次请求汇总,2026-09-24 复核后台逐笔账单。请求型号 ID 为 gpt-6-astra,分组为 GPT統一 / GPT限時車道;这些标识不能证明真实上游型号。历史输入、缓存读取、输出费率分别为每百万 Token 8、0.8、40 美元,不代表当前报价。

总输入 42,508 中包括缓存读取 40,320,因此普通输入只有 2,188。复算为 0.052560 美元,记录实扣为 0.052559 美元,差额为 0.000001 美元。差额原因尚未确认;代码没有模拟逐笔舍入,toFixed(6) 也只负责显示精度。

如果把总输入全部按普通费率计算,再额外叠加缓存,错误结果会是 0.375120 美元。这是复算公式重复计数的示例,不是平台实际多扣费。

用于生产系统时,还要分别处理字段映射、缓存写入、分组倍率、账单币种和请求匹配;这个函数只覆盖已确认的一种计数口径。

历史记录与计算依据

关系说明:我是 AI Relay Check 的维护者,本站部分商家链接有推广或返佣关系。上面的链接指向公开证据页。本文由 AI 起草,数据取自历史记录,示例代码已经执行核对。

你们会把不同计数口径留在供应商适配器里,还是统一字段后另存原始用量?

查看回复

回复 (0)

暂无回复,成为第一个参与讨论的人。

参与回复

登录后即可参与回复。登录