Skip to content

fix(relaykit): report cached tokens in Gemini usageMetadata built from chat usage - #8333

Merged
seefs001 merged 2 commits into
QuantumNous:mainfrom
feeeei:fix/gemini-cached-content-tokens
Nov 24, 2026
Merged

seefs001 merged 2 commits into
QuantumNous:mainfrom
feeeei:fix/gemini-cached-content-tokens

Conversation

@feeeei

@feeeei feeeei commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

本 PR 的代码由 AI 辅助生成(Claude Code)。

Agent

  • Tool: Claude Code
  • Tool version: 2.1.325
  • Model (full id): claude-opus-5-5
  • Host (CLI / IDE / GitHub coding agent / other): CLI
  • Date (UTC): 2026-11-14

Links

User request

  • Verbatim: 按用户要求,以整理后的需求描述代替原话:

    Claude 渠道处理 Gemini 格式请求时,new-api 返回的 usageMetadata.cachedContentTokenCount 恒为 0,但缓存读已经计入 promptTokenCount,和同一响应里 billing_usage 记录的缓存读不一致。按 Gemini 标准字段计费的下游会因此把缓存读按普通输入计费。需要修复这个转换,让标准字段如实反映缓存读;不能改变 new-api 自身的结算结果,也不能引入其他副作用。先提 issue,再提 PR。

  • Later constraints or corrections from the user (quote, or none): 已并入上面的整理描述

Out of scope — refuse

  • Matched: no
  • If yes, what was told to the user (stop here; do not open a PR): 不适用

Open gate — do not open unless all are satisfied

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told to the user (stop here): 不适用

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

Change

relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go:ResponseOpenAI2Gemini、StreamResponseOpenAI2Gemini、newGeminiStreamResponse 三处补上 cachedContentTokenCount,取 chat usage 里的缓存读:先读 PromptTokensDetails.CachedTokens,为 0 时读 InputTokensDetails.CachedTokens。流状态里保存的 usage 经过 UsageFromChatUsage 归一化,缓存读放在 InputTokensDetails 里;"finish 之后单独一个 usage chunk"和 Finalize 读的都是它。chat usage 的 prompt_tokens 本身就包含缓存读,和 Gemini promptTokenCount 的语义一致,所以 promptTokenCount 不用改。billing_usage 存在时,geminiBillingMetadataFromOpenAIUsage 仍然整体覆盖为原始的 Gemini 用量,这一行为没变。

Research

Duplicate / prior art

  • Search queries (issues, PRs): cachedContentTokenCount、billing_usage gemini、gemini cache usage、OpenAI2Gemini、claude to gemini、gemini cached tokens
  • What already existed and why this is not a duplicate: fix(gemini): support Gemini 3.5/regional models and preserve thoughts usage #7641 包含同样的映射,但混在不相关的 Gemini 3.5 推理识别改动里,已关闭,没有合并。本 PR 只做这一处。

Docs and code

  • https://docs.newapi.ai/ : 缓存计费只讲 Prompt Cache Ratio,没讲转换后的用量字段
  • https://deepwiki.com/QuantumNous/new-api : 2026-11-14 查询返回 HTTP 429,没能看到内容
  • README / repo docs: 没有相关内容
  • Code paths and what they imply for this change: 本实例的结算用的是上游 usage(claudeInfo.Usage 等)和 billing_usage,不会回读这里生成的 Gemini 字段,所以本实例扣费不变。下游 new-api 有 billing_usage 时以它结算(service/billing_usage.go),也不变;没有 billing_usage 时,现在会按缓存读计费,这和 Gemini 字段本来的语义一致。

Alternatives considered

  • Option A: 把 cachedContentTokenCount 截断到不超过 promptTokenCount。没采用:正常输入下两者本来就满足这个关系;对 prompt 缺失的异常 usage 截断成 0,下游反而偏离更多。
  • Option B: 让流状态改存未归一化的 chat usage。没采用:Usage() / SetUsage() 的返回语义会跟着变,影响面更大。
  • Why this approach: 只在构造 Gemini usage 的三处读取缓存读,不改动任何已有字段或调用方。

Files

Path Why
relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go 三处补 cachedContentTokenCount,新增取缓存读的函数 geminiCachedContentTokenCount
relaykit/relayconvert/response_registry_test.go 表驱动用例,通过公开的转换入口覆盖:Claude 非流式与流式、chat 非流式、chat 流式里 finish 之后单独的 usage chunk、无状态的 chat 流式 chunk

Behavior

  • Before: Claude → Gemini 响应 promptTokenCount=15035, cachedContentTokenCount=0
  • After: promptTokenCount=15035, cachedContentTokenCount=12981;本实例的消费日志不变(quota=5343, cache_tokens=12981)
  • Explicit non-goals / leftover work: 缓存写入没有对应的 Gemini 字段;流式下 DeepSeek 风格的 prompt_cache_hit_tokens 没有读(非流式在 relay/channel/openai/usage.go 已经归一化);上游 message_delta 只带 output_tokens 时,最后一个 chunk 的 promptTokenCount 为 0,这是另一个问题,本 PR 不处理

Verification

  • Commands and results:
    • cd relaykit && GOWORK=off go build ./... → 成功
    • cd relaykit && GOWORK=off go test ./... -count=1 → 全部 ok
    • cd relaykit && GOWORK=off go vet ./relayconvert/ ./relayconvert/internal/oai_chat/ → 无输出
    • go test ./relay/... ./service/... -count=1(根模块)→ exit 0
    • 新测试 TestConvertResponseToGeminiReportsCachedContentTokens:去掉本 PR 的修复后,两个子用例的非流式、流式、无状态断言全部失败(cached 实际为 0);只去掉 InputTokensDetails 那个兜底时,只有 chat 流式最后一个 chunk 的断言失败
  • Manual steps and observed result: 分别用 main b388140ac 和本分支构建,sqlite,新建 Anthropic 渠道指向本地模拟的 Anthropic Messages 服务(usage:input 2054 / cache_read 12981 / output 42,流式 message_delta 带累计 usage),用令牌请求 POST /v1beta/models/claude-sonnet-4-5-20250929:generateContent 和 :streamGenerateContent?alt=sse:
    • main:非流式和流式最后一个 chunk 都是 "promptTokenCount":15035,...,"cachedContentTokenCount":0
    • 本分支:都是 "promptTokenCount":15035,...,"cachedContentTokenCount":12981,billing_usage 和改动前一样
    • 两次构建的消费日志一致:prompt_tokens=2054, completion_tokens=42, cache_tokens=12981, cache_ratio=0.1, quota=5343, usage_billing_path=billing-usage-anthropic
  • UI: screenshot or recording (or why none): 不涉及 UI
  • Tests added or updated, or why none: 在已有的 response_registry_test.go 里新增一个表驱动测试
  • Databases / providers / platforms exercised: sqlite;Anthropic 渠道(上游为模拟服务);macOS arm64
  • Not verified: 真实的 Anthropic API;OpenAI 渠道只有单元测试;MySQL / PostgreSQL(本 PR 不涉及数据库)

Risks

  • Failure modes: 如果某个上游给的 chat usage 里,prompt_tokens 不包含缓存读、cached_tokens 却有值(不符合 OpenAI 的语义),cachedContentTokenCount 会大于 promptTokenCount。new-api 自己构造的 chat usage 都包含缓存读。
  • Billing / quota / auth impact: 本实例的结算不读这个字段,不变;下游 new-api 有 billing_usage 时不变,没有时会按缓存读计费
  • Follow-ups: 上面 non-goals 里列的几项

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

Summary by CodeRabbit

  • Bug Fixes
    • Gemini responses now report cached-content token counts from OpenAI usage data, including in streaming responses. When the primary cached-token count is unavailable, an alternate usage field is used.

…m chat usage

Gemini promptTokenCount includes cached content, but responses converted
from chat usage (e.g. a Claude channel serving a Gemini-format request)
always reported cachedContentTokenCount as 0 while billing_usage carried
the cache read. Fill cachedContentTokenCount from the chat usage cache-read
count in the non-stream, stream chunk, and stream state converters.
@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Caution

Review failed

The pull request is closed.

No actionable comments were generated in the recent review.

Walkthrough

Gemini response conversion now reports cached-content token counts from OpenAI chat usage in non-streaming and streaming responses. Tests cover Claude and OpenAI chat usage across non-streaming responses, finalized streams, and stateless stream conversion.

Changes

Cached-token usage conversion

Layer / File(s) Summary
Populate Gemini cached-token counts
relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go
Non-streaming and streaming Gemini usage metadata now includes cached-content token counts. The helper returns zero for nil usage, prefers nonzero prompt-detail cached tokens, and falls back to input-detail cached tokens.
Verify converted usage
relaykit/relayconvert/response_registry_test.go
Tests check Claude and OpenAI cached-token counts for non-streaming conversion and finalized streams. OpenAI cases also cover stateless stream conversion.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: calcium-ion

Merge Risk: Minimal · previous review d7819

Gemini-format responses now report cache-read tokens in cachedContentTokenCount while prompt counts and billing stay the same. The change is small, additive and covered by tests, so merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the primary change: Gemini usageMetadata now reports cached tokens, built from OpenAI-style chat usage. The raw summary and objectives confirm that the change populates cachedContentTo…
Linked Issues check Passed Issue #8332 requires that chat-to-Gemini usage conversion set usageMetadata.cachedContentTokenCount to the cache-read tokens already included in promptTokenCount, for streaming and non-streaming respo…
Out of Scope Changes check Passed Both changed files are tied to #8332. The production change in to_gemini_chat_resp.go only adds the cachedContentTokenCount field to the three Gemini usage builders and one helper function. It does no…
Full details: Title check

Explanation

The title names the primary change: Gemini usageMetadata now reports cached tokens, built from OpenAI-style chat usage. The raw summary and objectives confirm that the change populates cachedContentTokenCount from PromptTokensDetails.CachedTokens with a fallback to InputTokensDetails.CachedTokens, for non-streaming responses and streams. The title is specific, concise, and in a conventional commit form. It does not cover the Claude test coverage, but that is expected.

Full details: Linked Issues check

Explanation

Issue #8332 requires that chat-to-Gemini usage conversion set usageMetadata.cachedContentTokenCount to the cache-read tokens already included in promptTokenCount, for streaming and non-streaming responses, without changing new-api's own billing. The diff (merge base b388140 to head d781901) adds cachedContentTokenCount at all three requested sites: ResponseOpenAI2Gemini, StreamResponseOpenAI2Gemini, and newGeminiStreamResponse. The new helper geminiCachedContentTokenCount reads PromptTokensDetails.CachedTokens and falls back to InputTokensDetails.CachedTokens, which covers the normalized stream-state usage. promptTokenCount is unchanged. The new table-driven test TestConvertResponseToGeminiReportsCachedContentTokens covers the Claude and chat routes, non-streaming, finalized streaming, and stateless streaming, and asserts promptTokenCount=15035 and cachedContentTokenCount=12981 for the Claude case. The PR reports a manual before/after run against a simulated Anthropic upstream that shows the same values with billing_usage and consumption logs unchanged. Not verified by me: I did not re-read geminiBillingMetadataFromOpenAIUsage, so the claim that the billing_usage override keeps the cache field rests on the author's reported manual run. Real Anthropic API behavior and the OpenAI channel beyond unit tests are not verified. Excluded items (cache writes, DeepSeek-style prompt_cache_hit_tokens in streams, message_delta with output-only usage) are not required here.

Full details: Out of Scope Changes check

Explanation

Both changed files are tied to #8332. The production change in to_gemini_chat_resp.go only adds the cachedContentTokenCount field to the three Gemini usage builders and one helper function. It does not change existing fields, the billing override logic, or other callers. The test file adds one table-driven test in the existing response_registry_test.go that exercises the same conversion paths. No unrelated changes appear in the diff. The PR description lists the excluded cases as non-goals, and the code does not implement them.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the token count,
And finds the cached ones now amount.
Through streams and chats, the numbers show,
Where cached prompt tokens go.
The burrow hums: the fields align,
And all the sums look fine.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eeb36c21-6799-4b51-b0bd-56fc3de28bf4
Commits

Reviewing files that changed from the base of the PR and between b388140 and d781901.

Files selected for processing: 2

  • relaykit/relayconvert/internal/oai_chat/to_gemini_chat_resp.go
  • relaykit/relayconvert/response_registry_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@seefs001
seefs001 merged commit c53dcf3 into QuantumNous:main Nov 24, 2026
1 check was pending
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Claude 渠道响应 Gemini 格式请求时 cachedContentTokenCount 恒为 0,与 billing_usage 不一致

2 participants