Skip to content

fix(relaykit): Gemini stream token details, Responses tool-output media on Gemini, Opus 5.5 default effort - #7687

Merged
Calcium-Ion merged 3 commits into
mainfrom
fix/gemini-stream-usage-and-tool-media
Oct 7, 2026
Merged

Calcium-Ion merged 3 commits into
mainfrom
fix/gemini-stream-usage-and-tool-media

Conversation

@Calcium-Ion

@Calcium-Ion Calcium-Ion commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

🔗 关联任务 / Related Issue

  • 无对应 Issue。三处问题都是在 AstrLink 上做转换实测时发现的,每个修复单独一个提交。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

📝 变更描述 / Description

1. Gemini 流式按模态重复计费(relaykit/dto/usage_merge.go)
Gemini 每个流式帧的 usageMetadata 都是累计值,mergeGeminiTokenDetails 却把每帧的 prompt / toolUsePrompt / candidates 分模态 token 累加。转换流还会在多个管线步骤重复 remember 同一个 sidecar,所以一个带图片的 Responses 流式请求按 3 × 1089 个图片 token 计费。改为与标量字段相同的覆盖语义:新帧报告的模态替换旧值,未报告的保留,同一快照内的重复条目仍在结算时相加。所有调用方(host Gemini 流、转换流的 MergeBillingUsageNonZero)喂进来的都是累计快照,没有按帧增量的生产者。

2. Responses → Gemini 的 function_call_output 媒体(oai_responses/to_gemini_chat_req.go)
内容数组形式的工具输出原来被整体序列化进 functionResponse.response,base64 被当文本分词。现在文本留在 response,input_image / input_file 经 relaymedia.ResolveBase64Data(SSRF 防护路径)转为 inlineData;custom_tool_call_output 同样处理。按代际选择文档里的形状:

  • Gemini 3 及无法识别为旧代的模型:放进 functionResponse.parts(Gemini API "For Gemini 3 series models";Vertex 列出 png/jpeg/webp/pdf/text-plain)。音频、视频在这里丢弃并记 error 级 unsupported_media_type,交给 ToolLossPolicy:文档列表没有,实测 3.7 返回 200 但不计 AUDIO token,2.5 返回 400 "function_response.parts is not supported for this model"。
  • 上游模型 id(去掉 models/ 后)以 gemini-1. / gemini-2. 开头:作为普通 inlineData 放在同一 user 轮所有 functionResponse 之后,并行调用的分组和顺序不变,音频视频也照常携带。

同时把 SupportedMimeTypes 对齐 Blob.mimeType 参考:补上 image/gif、image/avif、audio/、video/ 以及列出的 text / application 类型。原来的白名单过小,普通 Chat / Responses 消息里带 GIF 等文件会被本地直接拒绝。普通消息路径其余逻辑不变。golden 文件无变化。

3. Opus 5.5 默认 effort 是 medium(reasoning/claude.go、shared/claude/reasoning.go)
effort 文档:"Most Claude models default to high effort ... Claude Opus 5.5 defaults to medium"。Claude 能力表新增按模型的 defaultEffort(claude-opus-5-5 为 medium,其余 high),用于客户端未给 effort 的路径:无推理意图、仅 include_thoughts、adaptive / enabled 无强度、原生透传标注、ResolveClaudeDefault。最后一处会让 Claude 客户端经 OpenAI 上游时真的发送 reasoning_effort: high,消耗推理 token。显式 effort 和 budget 映射不变。该值只被 service/log_info_generate.go(消费日志 reasoning_effort)、relay/channel/openai/adaptor.go(OpenAI 参数能力判断)和 RelayInfo 调试输出读取,计费不读取。

📸 运行证明 / Proof of Work

gofmt -l <本 PR 改动的 .go 文件>            # 无输出
cd relaykit && GOWORK=off go build ./... && GOWORK=off go vet ./... && GOWORK=off go test -count=1 ./...
# 9 个包全部 ok
go build ./... && go test -count=1 ./relay/... ./service/... ./controller/...
# 21 个包 ok,无 FAIL

新测试在旧代码上的结果:usage_merge_test.go 的多帧用例在旧实现下得到 IMAGE 3267(3 × 1089)、TEXT 126;intent_test.go 的默认 effort 表只有 opus-5-5 的 4 个用例失败,opus-5 / sonnet-5-5 不变。

实测:同一 worktree 分别构建修复前(973cf8ef4)和修复后的二进制,独立 SQLite、干净 cwd,经 AstrLink。

Fix 1,gemini-3.7-flash,提示词带一张图(上游 prompt 约 1130,其中 IMAGE 1089);括号内为按日志 token 与倍率重算的期望值:

入口 修复前 修复后
Responses 非流式 1931(1931) 1952(1952)
Responses 流式 5093(1887) 2030(2030)
Gemini 原生 流式 / 非流式 1931 / 1901 1880 / 1925
Chat 流式 / 非流式 2012 / 1874 1881 / 1880

修复后流式与非流式的差额来自输出长度不同。

Fix 2,修复前 → 修复后(上游 prompt token,回答):

  • 3.7 图片:24,363,答 green → 1,216,答 blue,图片在 functionResponse.parts
  • 3.7 PDF:无回答 → 653,答 PINEAPPLE
  • 3.7 并行(含流式):24,416 → 1,269,blue + NOTE_42,两个 functionResponse 按调用顺序
  • 3.7 仅音频:{"content":"[audio]"},记 unsupported_media_type
  • 2.5 图片 / PDF / 并行(含流式):24,288 / 263 / 24,323 → 329 / 1,365(DOCUMENT)/ 363,媒体位于全部 functionResponse 之后,回答正确
  • 2.5 仅音频:作为 inlineData audio/wav 发送,上游计 AUDIO 75 token;quota 133 符合 2.5 单独的音频输入价

Fix 3(日志 reasoning_effort / 上游实际发送):

  • Claude 客户端 claude-opus-5-5 → OpenAI 渠道(映射 gpt-5.6-sol),无 thinking 或 adaptive 无 effort:high / high → medium / medium
  • 同样请求换 claude-opus-5:修复前后都是 high / high
  • 原生 /v1/messages claude-opus-5-5 adaptive 透传:日志 high → medium,请求体不变
  • Chat → Claude claude-opus-5-5 无推理:日志 high → medium;claude-sonnet-5-5 仍为 high

未验证:claude-sonnet-5-5 的原生透传标注只有单测。AstrLink 这段时间对该模型多次返回自身的 500"可用渠道不存在",claude-opus-5 在 Claude 渠道上同样不可用。

✅ 提交前检查项 / Checklist

  • 人工确认: 无论描述是否由 AI 生成,我已审阅并精炼全文,仅保留可复核的要点,并声明对其准确性与完整性负责。PR 正文及后续评论均未直接粘贴未经人工过滤的大段 AI 文本。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • 新功能关联 Issue: 若此 PR 标记为 New feature,我已关联对应 Issue;若尚无 Issue,我已先自行创建。
  • 事前沟通: 若改动较大或涉及方向性变更,已在关联 Issue 中与维护者沟通并达成一致。
  • 功能范围: 本 PR 不是 Coding Plan、逆向渠道、第三方封装接口,也不是对 Codex 渠道类型的改动。
  • 非透传: 本 PR 不是针对开启透传后的转发行为;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 范围聚焦: 本 PR 为一项聚焦改动,未包含无关代码。
  • 本地验证: 已按变更路径实际验证,并写明命令与观察结果。仅声明 go build 通过或测试通过,不视为有效证明。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Streaming Gemini usage now retains the latest reported token counts for each modality, helping keep billing usage aligned with non-streaming responses.
    • Gemini requests now recognize supported audio and video MIME types consistently. Responses with tool-generated media are handled according to the upstream Gemini model, with unsupported media omitted and reported.
    • Claude requests without an explicit reasoning effort now use a model-specific default. Explicit effort settings remain unchanged.

Gemini usageMetadata on every stream frame is a cumulative snapshot, but
mergeGeminiTokenDetails added each frame's per-modality counts to the
previous ones. Prompt, tool-use prompt and candidates details were
multiplied by the number of frames carrying usage, and converted streams
multiplied them again because the same sidecar is remembered at several
pipeline steps. A streamed image prompt was billed as 3 x 1089 image
tokens.

A modality reported by the incoming frame now replaces all earlier
entries for it, matching how the scalar counts are merged; modalities
the frame omits keep their earlier value, and duplicate entries inside
one snapshot are still summed at settlement.
…ne data

A function_call_output or custom_tool_call_output holding a Responses
content-part array was stringified into functionResponse.response, so
Gemini tokenized the base64 media as text (an image tool output cost
24,366 prompt tokens and the model could not see it).

Text parts now stay in response and images and documents become
inlineData resolved through the SSRF-protected media resolver. Gemini 3
documents multimodal function responses, so the media go into
functionResponse.parts there and for any model id not known to be older.
Gemini 1.x and 2.x get them as ordinary inlineData parts after every
functionResponse of the same turn, which keeps parallel calls grouped.
Media a target cannot carry (audio or video inside
functionResponse.parts, unsupported MIME types, failed loads) is dropped
with an unsupported_media_type diagnostic for the tool-loss policy.

The inline-data MIME allowlist now follows the Blob.mimeType list in the
Gemini API reference, adding image/gif, image/avif, audio/*, video/* and
the listed text and application types, so ordinary Chat and Responses
messages with those files are no longer rejected locally.
Claude Opus 5.5 runs at medium effort when a request sets none; every
other model, including Opus 5, Sonnet 5.5 and Fable 5.1, runs at high
(platform.claude.com/docs/en/build-with-claude/effort). The converter
assumed high everywhere, so Opus 5.5 requests without an effort were
logged as high, and a Claude client on claude-opus-5-5 routed to an
OpenAI upstream sent reasoning effort high instead of the model's
default.

Claude capabilities now carry a per-model default effort, used when the
client gave none: the no-intent and include_thoughts-only paths,
adaptive or enabled thinking without a strength, the native passthrough
label, and ResolveClaudeDefault for Claude-to-OpenAI conversions.
Explicit efforts and budget mappings are unchanged. The value feeds the
consume-log reasoning_effort field, OpenAI parameter filtering and the
RelayInfo debug string; billing does not read it.
@coderabbitai

coderabbitai Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f5a724d6-7051-4a86-97b2-aea5909d5b40
📥 Commits

Reviewing files that changed from the base of the PR and between 973cf8e and 39fcd43.

📒 Files selected for processing (10)
  • relaykit/dto/usage_merge.go
  • relaykit/dto/usage_merge_test.go
  • relaykit/relayconvert/internal/oai_chat/to_gemini_chat_req.go
  • relaykit/relayconvert/internal/oai_responses/to_gemini_chat_req.go
  • relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go
  • relaykit/relayconvert/internal/shared/claude/reasoning.go
  • relaykit/relayconvert/internal/shared/gemini/request.go
  • relaykit/relayconvert/reasoning/claude.go
  • relaykit/relayconvert/reasoning/intent_test.go
  • relaykit/relayconvert/request_registry_test.go
 _______________________________________________
< Show me the code! And I'll show you the bugs. >
 -----------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · 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

Comment @coderabbitai help to get the list of available commands.

@Calcium-Ion
Calcium-Ion merged commit 78bd5b1 into main Oct 7, 2026
2 of 3 checks passed
Javabcd pushed a commit to Javabcd/new-api that referenced this pull request Oct 9, 2026
…ia on Gemini, Opus 5.5 default effort (QuantumNous#7687)

* fix(relaykit): stop summing cumulative Gemini stream token details

Gemini usageMetadata on every stream frame is a cumulative snapshot, but
mergeGeminiTokenDetails added each frame's per-modality counts to the
previous ones. Prompt, tool-use prompt and candidates details were
multiplied by the number of frames carrying usage, and converted streams
multiplied them again because the same sidecar is remembered at several
pipeline steps. A streamed image prompt was billed as 3 x 1089 image
tokens.

A modality reported by the incoming frame now replaces all earlier
entries for it, matching how the scalar counts are merged; modalities
the frame omits keep their earlier value, and duplicate entries inside
one snapshot are still summed at settlement.

* fix(relayconvert): send Responses tool-output media to Gemini as inline data

A function_call_output or custom_tool_call_output holding a Responses
content-part array was stringified into functionResponse.response, so
Gemini tokenized the base64 media as text (an image tool output cost
24,366 prompt tokens and the model could not see it).

Text parts now stay in response and images and documents become
inlineData resolved through the SSRF-protected media resolver. Gemini 3
documents multimodal function responses, so the media go into
functionResponse.parts there and for any model id not known to be older.
Gemini 1.x and 2.x get them as ordinary inlineData parts after every
functionResponse of the same turn, which keeps parallel calls grouped.
Media a target cannot carry (audio or video inside
functionResponse.parts, unsupported MIME types, failed loads) is dropped
with an unsupported_media_type diagnostic for the tool-loss policy.

The inline-data MIME allowlist now follows the Blob.mimeType list in the
Gemini API reference, adding image/gif, image/avif, audio/*, video/* and
the listed text and application types, so ordinary Chat and Responses
messages with those files are no longer rejected locally.

* fix(relayconvert): use medium as the Opus 5.5 default effort

Claude Opus 5.5 runs at medium effort when a request sets none; every
other model, including Opus 5, Sonnet 5.5 and Fable 5.1, runs at high
(platform.claude.com/docs/en/build-with-claude/effort). The converter
assumed high everywhere, so Opus 5.5 requests without an effort were
logged as high, and a Claude client on claude-opus-5-5 routed to an
OpenAI upstream sent reasoning effort high instead of the model's
default.

Claude capabilities now carry a per-model default effort, used when the
client gave none: the no-intent and include_thoughts-only paths,
adaptive or enabled thinking without a strength, the native passthrough
label, and ResolveClaudeDefault for Claude-to-OpenAI conversions.
Explicit efforts and budget mappings are unchanged. The value feeds the
consume-log reasoning_effort field, OpenAI parameter filtering and the
RelayInfo debug string; billing does not read it.
@Calcium-Ion
Calcium-Ion deleted the fix/gemini-stream-usage-and-tool-media branch October 22, 2026 04:57
timwenx pushed a commit to timwenx/new-api that referenced this pull request Nov 18, 2026
…ia on Gemini, Opus 5.5 default effort (QuantumNous#7687)

* fix(relaykit): stop summing cumulative Gemini stream token details

Gemini usageMetadata on every stream frame is a cumulative snapshot, but
mergeGeminiTokenDetails added each frame's per-modality counts to the
previous ones. Prompt, tool-use prompt and candidates details were
multiplied by the number of frames carrying usage, and converted streams
multiplied them again because the same sidecar is remembered at several
pipeline steps. A streamed image prompt was billed as 3 x 1089 image
tokens.

A modality reported by the incoming frame now replaces all earlier
entries for it, matching how the scalar counts are merged; modalities
the frame omits keep their earlier value, and duplicate entries inside
one snapshot are still summed at settlement.

* fix(relayconvert): send Responses tool-output media to Gemini as inline data

A function_call_output or custom_tool_call_output holding a Responses
content-part array was stringified into functionResponse.response, so
Gemini tokenized the base64 media as text (an image tool output cost
24,366 prompt tokens and the model could not see it).

Text parts now stay in response and images and documents become
inlineData resolved through the SSRF-protected media resolver. Gemini 3
documents multimodal function responses, so the media go into
functionResponse.parts there and for any model id not known to be older.
Gemini 1.x and 2.x get them as ordinary inlineData parts after every
functionResponse of the same turn, which keeps parallel calls grouped.
Media a target cannot carry (audio or video inside
functionResponse.parts, unsupported MIME types, failed loads) is dropped
with an unsupported_media_type diagnostic for the tool-loss policy.

The inline-data MIME allowlist now follows the Blob.mimeType list in the
Gemini API reference, adding image/gif, image/avif, audio/*, video/* and
the listed text and application types, so ordinary Chat and Responses
messages with those files are no longer rejected locally.

* fix(relayconvert): use medium as the Opus 5.5 default effort

Claude Opus 5.5 runs at medium effort when a request sets none; every
other model, including Opus 5, Sonnet 5.5 and Fable 5.1, runs at high
(platform.claude.com/docs/en/build-with-claude/effort). The converter
assumed high everywhere, so Opus 5.5 requests without an effort were
logged as high, and a Claude client on claude-opus-5-5 routed to an
OpenAI upstream sent reasoning effort high instead of the model's
default.

Claude capabilities now carry a per-model default effort, used when the
client gave none: the no-intent and include_thoughts-only paths,
adaptive or enabled thinking without a strength, the native passthrough
label, and ResolveClaudeDefault for Claude-to-OpenAI conversions.
Explicit efforts and budget mappings are unchanged. The value feeds the
consume-log reasoning_effort field, OpenAI parameter filtering and the
RelayInfo debug string; billing does not read it.
xiaolanawaqaq pushed a commit to xiaolanawaqaq/new-apiaaa that referenced this pull request Nov 26, 2026
…ia on Gemini, Opus 5.5 default effort (QuantumNous#7687)

* fix(relaykit): stop summing cumulative Gemini stream token details

Gemini usageMetadata on every stream frame is a cumulative snapshot, but
mergeGeminiTokenDetails added each frame's per-modality counts to the
previous ones. Prompt, tool-use prompt and candidates details were
multiplied by the number of frames carrying usage, and converted streams
multiplied them again because the same sidecar is remembered at several
pipeline steps. A streamed image prompt was billed as 3 x 1089 image
tokens.

A modality reported by the incoming frame now replaces all earlier
entries for it, matching how the scalar counts are merged; modalities
the frame omits keep their earlier value, and duplicate entries inside
one snapshot are still summed at settlement.

* fix(relayconvert): send Responses tool-output media to Gemini as inline data

A function_call_output or custom_tool_call_output holding a Responses
content-part array was stringified into functionResponse.response, so
Gemini tokenized the base64 media as text (an image tool output cost
24,366 prompt tokens and the model could not see it).

Text parts now stay in response and images and documents become
inlineData resolved through the SSRF-protected media resolver. Gemini 3
documents multimodal function responses, so the media go into
functionResponse.parts there and for any model id not known to be older.
Gemini 1.x and 2.x get them as ordinary inlineData parts after every
functionResponse of the same turn, which keeps parallel calls grouped.
Media a target cannot carry (audio or video inside
functionResponse.parts, unsupported MIME types, failed loads) is dropped
with an unsupported_media_type diagnostic for the tool-loss policy.

The inline-data MIME allowlist now follows the Blob.mimeType list in the
Gemini API reference, adding image/gif, image/avif, audio/*, video/* and
the listed text and application types, so ordinary Chat and Responses
messages with those files are no longer rejected locally.

* fix(relayconvert): use medium as the Opus 5.5 default effort

Claude Opus 5.5 runs at medium effort when a request sets none; every
other model, including Opus 5, Sonnet 5.5 and Fable 5.1, runs at high
(platform.claude.com/docs/en/build-with-claude/effort). The converter
assumed high everywhere, so Opus 5.5 requests without an effort were
logged as high, and a Claude client on claude-opus-5-5 routed to an
OpenAI upstream sent reasoning effort high instead of the model's
default.

Claude capabilities now carry a per-model default effort, used when the
client gave none: the no-intent and include_thoughts-only paths,
adaptive or enabled thinking without a strength, the native passthrough
label, and ResolveClaudeDefault for Claude-to-OpenAI conversions.
Explicit efforts and budget mappings are unchanged. The value feeds the
consume-log reasoning_effort field, OpenAI parameter filtering and the
RelayInfo debug string; billing does not read it.
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.

1 participant