AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] OpenAI 兼容 provider:usage 中 cached_tokens 大于 prompt_tokens 时 input_other 为负,用量统计失真

Open xiaoyuyu6420 opened this issue 3 months ago • 1 comments

问题描述

OpenAI 兼容 provider 的 token 用量统计在 cached_tokens > prompt_tokens(畸形或非 OpenAI 兼容的 usage 响应)时会出现负值。

astrbot/core/provider/sources/openai_source.py(约 737-738 行):

return TokenUsage(
    input_other=prompt_tokens - cached,
    ...
)

对 prompt_tokens - cached 没有做 max(0, ...) 保护。cached_tokens 字段已有类型防护(约 727-729 行,None 安全),但没有幅度防护。astrbot/core/provider/sources/openai_responses_source.py(约 601 行)存在同样的减法。

影响

若上游渠道/中转返回的 usage 中 cached 字段大于 prompt_tokens(部分非官方兼容服务会出现),input_other 为负,TokenUsage.total 与 input 失真(可能小于 output),上下文占用统计与用量记录被污染。

建议修复

input_other=max(0, prompt_tokens - cached),

total 汇总处同样保证非负。改动为纯增量、低风险。

xiaoyuyu6420 avatar Sep 01 '26 11:09 xiaoyuyu6420

fixed

Soulter avatar Sep 03 '26 16:09 Soulter