new-api icon indicating copy to clipboard operation
new-api copied to clipboard

[Bug] Ollama 渠道 chat completions 的 cache_tokens 恒为 0(原生 /api/chat 未解析 prompt_eval_cached_count)

Open qqbless opened this issue 1 month ago • 1 comments

Agent

  • Tool: ZCode Desktop
  • Tool version: 未提供
  • Model (full id): magpie/group/deepseek-flash
  • Host (CLI / IDE / GitHub coding agent / other): ZCode Desktop(CLI 形态)
  • Date (UTC): 2026-11-03

User request

  • Verbatim:
分析一下  110 这个ollama 渠道 为什么   /v1/chat/completions 请求 就没有缓存记录 ,而 /v1/respones 请求就有缓存!!!

这是个大问题啊! 你网上搜索下大家的反馈 ,也查询下 ollama 的官方说明。

我应该如何解决这个问题?

我最终诉求是 : 这两种协议都可以拿到缓存命中记录 ,否则  走  /v1/chat/completions  的用户 一会儿就没额度了 !

先不开发,先给我方案!
  • Later constraints or corrections from the user (quote, or none):
[$humanizer-zh](C:\Users\50562\.agents\skills\humanizer-zh\SKILL.md) 先用拟人化的口吻 去 github 给 newapi 上报一个 issue

Out of scope — refuse

  • Matched: no
  • If yes, what was told to the user (stop here; do not file):

File gate — do not file unless all are satisfied

  • Out of scope (including pass-through): no
  • Usage / configuration / integration (answered instead of filing): no
  • Required facts present without invention (actual behavior, impact, frequency, evidence in new-api, applicable type fields): yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • File: yes
  • If no, what was told to the user (stop here; do not file):

Kind

  • [x] Bug
  • [ ] Feature
  • [ ] Investigation
  • [ ] Other:

Usage / configuration / integration check

  • https://docs.newapi.ai/ — 查了首页和站内搜索,没有 Ollama 缓存计费或 prompt_eval_cached_count 的说明。
  • https://deepwiki.com/QuantumNous/new-api — 访问时返回 429,未取到内容。
  • README / repo docs: README 只写了通用的 usage / cache accounting,没有 Ollama 渠道的特殊说明。
  • Relevant code paths and conclusion: relay/channel/ollama/adaptor.go 决定 chat 走原生 /api/chat 还是 OpenAI 兼容的 /v1/chat/completions;relay/channel/ollama/stream.go 的原生 handler 只读 prompt_eval_count,没读 Ollama 同时返回的 prompt_eval_cached_count。这不是使用或配置问题。
  • Can the current version already do this? (required for feature requests): 不适用(bug)。
  • Verdict: product bug or new feature / usage question (stop here): product bug。

Environment

  • new-api version / commit / image tag (not latest / unknown): v1.0.0-rc.43
  • Deploy source (repo release / official image / main source / other): 本仓库 Release / 官方镜像(自行部署)
  • Database (sqlite / mysql / postgres): PostgreSQL

Problem facts

  • Actual behavior: 同一个 Ollama 渠道、同一个模型,客户端走 /v1/chat/completions 时,日志里的 cache_tokens 恒为 0;走 /v1/responses 时正常,命中率大约 89%。我一开始以为是 Ollama Cloud 没开缓存,后来对比了同渠道的 responses 日志和 rc.43 的代码,发现缓存其实一直在命中,只是 chat 这条分支没把 cached token 记下来。用户那边看到的就是聊一会儿额度就没了。
  • Impact: 渠道用的是表达式计费 tier("base", p * 2.5 + c * 20 + cr * 0.25)。表达式引用了 cr,new-api 会把缓存 token 从 p 里扣掉;cache_tokens 为 0 时整段 prompt 都按 2.5 计费,而缓存部分本来应该是 0.25,等于贵了 10 倍,用户看到的就是额度掉得特别快。
  • Frequency: 近 3 天同一个渠道里,128 条 chat 请求的 cache_tokens 全是 0;85 条 responses 请求的缓存命中率是 89%。
  • Evidence that the problem is in new-api rather than the client or upstream:
    1. 同一个上游、同一个模型,responses 路径能正常返回缓存,说明 Ollama 侧的 prefix cache 是有效的。
    2. rc.43 的 relay/channel/ollama/stream.go 里,原生 chat 的 handler 没有解析 prompt_eval_cached_count;responses 路径走 OpenAI adaptor,会读 input_tokens_details.cached_tokens,所以只有 responses 有值。
    3. 客户端只是普通 OpenAI 请求,没法决定这个字段;换客户端也一样。

Type-specific details

Relay / API

  • Request endpoint and method: 客户端 POST /v1/chat/completions;上游 POST /api/chat(Ollama 原生)
  • Channel type: Ollama(type=4)
  • Model: Ollama Cloud 上的 deepseek 系列模型(渠道内做了 model mapping)
  • Conversion format: OpenAI chat → Ollama native chat
  • Pass-through enabled: 否
  • Evidence of upstream native support: Ollama 官方 usage 文档明确列出 prompt_eval_cached_count;Ollama 源码 openai/openai.go 的 ToUsage() 会把 PromptEvalCachedCount 映射到 prompt_tokens_details.cached_tokens。
  • Equivalent redacted request sent directly upstream: 未执行。渠道 key 不能通过管理 API 读取(/api/channel/ 返回的 key 为空),我不想在生产环境里碰密钥,所以没有直连。
  • Same request through new-api: chat 日志 cache_tokens=0;同渠道 responses 日志 cache_tokens 接近 prompt_tokens。

Billing

  • Request endpoint and model: POST /v1/chat/completions,deepseek 系列(mapped)
  • Response usage: 日志里 prompt_tokens 正常,cache_tokens 为 0;上游原生 usage 里的 prompt_eval_cached_count 没有被记录下来。
  • Relevant ratio or pricing configuration: tier("base", p * 2.5 + c * 20 + cr * 0.25)。这里只是引用现有配置说明问题,不请求修改倍率。
  • Consumption log: 近 3 天 chat 128 条,prompt 26,539,951,cache 0,quota 34,161,052;responses 85 条,prompt 13,560,591,cache 12,072,944,quota 4,670,499。
  • Expected charge and calculation basis: 如果 chat 也按 89% 命中计算,p 只剩 11%,成本大约是现在的 1/5;缓存部分单价应该从 2.5 降到 0.25。

Frontend

  • not applicable

Deployment / upgrade

  • not applicable(不是部署或升级导致的问题)

Reproduction and expected result

  • Steps to reproduce:
    1. 建一个 Ollama 渠道,ollama_openai_chat 保持默认的 false。
    2. 用同一个长 prompt 连续发两次 /v1/chat/completions,第二次只追加少量 token。
    3. 查 /api/log/ 里的 other.cache_tokens。
    4. 同一渠道、同一模型改走 /v1/responses,再重复一次。
  • Expected result: 两条路径都应该记录 cache_tokens > 0;现在 chat 恒为 0,responses 正常。
  • Related screenshots (optional): 无,日志字段已经脱敏。

Feature (feature requests only)

  • not applicable

Duplicate check

  • Search queries (issues, PRs, discussions): ollama cached_tokens、prompt_eval_cached_count、ollama(最近 15 条)
  • Closest existing threads: #2378(Ollama 流式格式问题)、#7252(Ollama 流式 tool_calls 丢失)
  • Why this is not a duplicate: 这两个都不是缓存字段解析的问题,现有 issue 里没有看到 prompt_eval_cached_count。

Research

Docs

  • https://docs.newapi.ai/ : 首页和站内搜索没有 Ollama 缓存字段的说明。
  • https://deepwiki.com/QuantumNous/new-api : 429,未取到内容。
  • README / other repo docs: 只提到通用 cache accounting,没有 Ollama 专门说明。
  • Conclusions: 文档没有覆盖这个字段,只能看代码。

Code

  • relay/channel/ollama/adaptor.go — GetRequestURL() 在 ollama_openai_chat=false 时返回 /api/chat;DoResponse() 对 chat 走 ollamaStreamHandler / ollamaChatHandler。
  • relay/channel/ollama/stream.go — ollamaChatStreamChunk 只有 prompt_eval_count、eval_count、prompt_eval_duration 等字段,没有 prompt_eval_cached_count;第 191 行和第 319 行构造 usage 时只填了 prompt / completion / total,没有写 PromptTokensDetails.CachedTokens。
  • relay/channel/openai/relay_responses.go、relaykit/dto/openai_response.go — responses 路径会解析 input_tokens_details.cached_tokens,所以有值。
  • pkg/billingexpr/expr.md — 表达式引用 cr 时,p 会自动扣除缓存 token。

Experiments

  • Command or redacted request: 通过管理 API 拉 /api/log/?channel=...(只读,已按日志 id 去重)。
  • Direct upstream result: 未执行(渠道 key 不可读)。
  • Result through new-api: chat cache_tokens=0;responses cache_tokens≈89%。
  • Conclusion: 差异来自 new-api 的原生 Ollama handler,不是上游。

Working theory

  • What is broken or missing: 原生 /api/chat 的 usage 解析漏了 prompt_eval_cached_count。
  • Why: ollamaChatStreamChunk 没定义这个字段,两个 handler 也没写 usage.PromptTokensDetails.CachedTokens。
  • What would falsify this: 如果补上字段后 chat 日志仍然 cache_tokens=0,说明上游原生 API 没有返回该字段,这个判断就不成立。

Scope

  • In scope for a later PR: 给原生 chat handler 补上 prompt_eval_cached_count,流式和非流式都要写进 usage.PromptTokensDetails.CachedTokens。
  • Out of scope / not this repo: Ollama 上游的缓存策略、用户侧的计费表达式。
  • Large or directional feature? no

Proposed direction

验收标准:

  • 同一渠道、同一模型的 /v1/chat/completions 日志出现 cache_tokens > 0。
  • chat 的命中率与同渠道 /v1/responses 接近。
  • prompt_tokens / completion_tokens / total_tokens 的现有统计不受影响。

参考改动点(不是完整实现):ollamaChatStreamChunk 增加 prompt_eval_cached_count 字段;流式 done 帧和非流式 lastChunk 各补一次 usage.PromptTokensDetails.CachedTokens 赋值。

Not verified

  • 没有直连 Ollama 上游做对比(渠道 key 不能通过管理 API 读取)。
  • 没有在 SQLite / MySQL 上重复验证;问题在代码路径,理论上和数据库无关。
  • 没有验证其他 Ollama Cloud 模型是否同样表现;这个渠道目前只挂了一个模型。

Related

  • Ollama usage docs: https://docs.ollama.com/api/usage
  • Ollama OpenAI compatibility docs: https://docs.ollama.com/api/openai-compatibility
  • Ollama source openai/openai.go ToUsage(): https://github.com/ollama/ollama/blob/main/openai/openai.go
  • new-api rc.43 relay/channel/ollama/stream.go: https://github.com/QuantumNous/new-api/blob/v1.0.0-rc.43/relay/channel/ollama/stream.go
  • new-api billing expression docs: https://github.com/QuantumNous/new-api/blob/v1.0.0-rc.43/pkg/billingexpr/expr.md

qqbless avatar Nov 03 '26 02:11 qqbless

[Bot Review]

感谢提交。由于本 Issue 未使用我们规定的模板(Bug Report / Feature Request),我们将暂且关闭。请重新提交并务必保留并填写模板中的各个要求字段,以便我们更好地定位问题,谢谢配合!