Skip to content

fix(relayconvert): 修复 Responses→Chat 工具输出图片被拍平成 base64 文本 - #7502

Closed
MOON-DREAM-STARS wants to merge 2 commits into
QuantumNous:mainfrom
MOON-DREAM-STARS:fix/7498-tool-output-media-hoist
Closed

MOON-DREAM-STARS wants to merge 2 commits into
QuantumNous:mainfrom
MOON-DREAM-STARS:fix/7498-tool-output-media-hoist

Conversation

@MOON-DREAM-STARS

@MOON-DREAM-STARS MOON-DREAM-STARS commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Agent

  • Tool: Codex desktop app
  • Tool version: codex-cli 0.155.0-alpha.9
  • Model (full id): deepseek-v4.1-flash
  • Host: Codex desktop app (Windows)
  • Date (UTC): 2026-09-21

Links

User request

  • Verbatim: 工具输出图片被拍平成 base64 文本,这个缺陷在哪里修?你先别着急,你看看我本地的Newapi worktree,应该有一个new-api-upstream-sync,这个worktree是专门对齐上游master的,用来生成issue和提交PR。我希望你先提交ISSUE(具体格式可以看我提交的那个issue),然后,从这个worktree中分出来一个fix/XXXX(issue)分支,专门修复这个bug。修复完成之后合并到main,并且从这个分支提交PR
  • Later constraints or corrections from the user (quote, or none): 首先按照上面说的,按「只改 Responses→Chat + 图片改放到后续 user 消息」这个方向,去走你原来那套流程(提 issue → fix/<issue#> 分支 → 修 → 合并本地 main → 从分支提 PR)

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

Kind

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

Issue facts

  • Actual behavior: function_call_output.output 为内容块数组且含图片/文件等非文本块时,responseToolOutputToChatContent 把整个数组 JSON 序列化成 tool 消息的字符串 content,图片以 base64 文本形式进入发往上游的请求体。
  • Impact: 图片不再作为图像内容传给上游,并被当作文本计入上下文与费用。生产实测一张 1,309,020 字节的 PNG 使单次请求 prompt_tokens 达 1,070,945,超过上游 1,048,576 上限并返回 HTTP 400 code 11115(context_length_exceeded);同形态成功请求 prompt_tokens 在 823,561–912,487 区间。
  • Frequency: 对「含图片的内容块数组」形态 100% 确定性复现(见 Verification 的基线失败);生产日志中连续观测到 3 次超限与 8 次高 token 计费。
  • Evidence that the problem is in new-api rather than the client or upstream: 直接调用 ResponsesRequestToChatCompletionsRequest 即可观察到 base64 进入 tool 消息 content,全程不涉及上游、数据库或真实模型;触发项是 OpenAI Responses 规范允许的标准输入项(FunctionCallOutputItemParam.output = string | array(text|image|file))。
  • Applicable types and their fields:
    • relay: POST /v1/responses 的 OpenAI Responses → OpenAI Chat Completions 转换;function_call_output.output 内容块数组的消息映射。渠道类型 Advanced Custom(type 58),converter openai_responses_to_openai_chat_completions。
    • billing: not applicable(本 PR 不改计费逻辑;token 虚高是上游按文本计数的直接结果)。
    • frontend: not applicable.
    • deployment: not applicable.

Change

Chat Completions 的 tool 消息按规范只能承载文本,因此不再把内容块数组整体字符串化:

  • function_call_output 分支改为可能产出两条消息:tool 消息 +(仅当存在非文本块时)一条紧随其后的 user 消息。
  • output 为非空内容块数组且每个元素的 type 属于已知内容块集合(input_text/output_text/text/input_image/input_file/input_audio/input_video)时,文本块拼进 tool 消息的 content,非文本块经既有 responsesContentPartsToChatContent 同一映射(input_image → image_url 等)放入 user 消息;文本块之间以单个 \n 连接(跳过空字符串);无文本块时 tool content 使用类型感知的非空占位(按类型去重、空格连接:input_image → [image]、input_file → [file]、input_audio → [audio]、input_video → [video];纯图片即 [image])。
  • 其余形态(字符串、对象、任意 JSON 数组、纯文本内容块数组)继续走既有 responseToolOutputToChatContent 字符串化路径,行为不变。
  • 媒体块相对文本块的原始顺序在拆成两条消息后不再保留;这是该形态的已知取舍。

Research

Duplicate / prior art

Docs and code

  • https://docs.newapi.ai/ : 本机不可达(SSL 连接失败),未检索。
  • https://deepwiki.com/QuantumNous/new-api : 可达(HTTP 200),未作为判定依据。
  • README / repo docs: relaykit/README.md — 支持矩阵把 OpenAI Responses → OpenAI Chat 标为 Good;工具损耗默认 allow 并以诊断形式返回。
  • Code paths and what they imply for this change:
    • relaykit/relayconvert/internal/oai_responses/to_oai_chat_req.go — responsesInputItemToChatMessages 的 function_call_output 分支与 responseToolOutputToChatContent;同文件的 responsesContentPartsToChatContent 对普通消息内容已正确把 input_image 映射为 image_url,两者口径原本不一致。
    • relaykit/dto/openai_request.go — Message.Content 为 any,可承载内容块数组。
    • relay/advancedcustom/adaptor.go — 该转换器在生产路径上的调用点。

Alternatives considered

  • Option A: 在 tool 消息里直接产出 image_url 内容块。拒绝:Chat Completions 的 tool 消息按规范只允许文本内容块,严格校验的上游会直接 400。
  • Option B: 丢弃媒体、只留文本占位并上报损耗诊断。拒绝:图像语义仍然丢失,不能满足原始用例。
  • Why this approach: 把媒体块提升到紧随其后的 user 消息,既守住 Chat 对 tool 消息的约束,又让视觉上游仍能拿到图片。

Files

Path Why
relaykit/relayconvert/internal/oai_responses/to_oai_chat_req.go function_call_output 内容块数组的拆分:文本以 \n 连接留在 tool(无文本时用类型感知非空占位)、非文本块转后续 user 消息
relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go 回归测试:媒体提升 + object / [1,2] / 纯文本内容块数组三个负向形态

Behavior

  • Before: output 为 [{input_text}, {input_image data URL}] 时只产出 1 条 tool 消息,content 是包含 data:image/png;base64,… 的 JSON 字符串。
  • After: 产出 tool 消息(有文本时为其以 \n 连接的结果;无文本时为类型感知非空占位,如 [image]、[image] [file])+ 一条 user 消息(content 为 image_url/file 等内容块数组);tool 消息不再包含 base64。
  • Explicit non-goals / leftover work: 不改 Claude→Chat(claude_messages/to_oai_chat_req.go 对 tool_result 非文本内容同样 JSON 序列化);不改 Gemini→Chat(functionResponse 只能是 JSON 对象);不加体积上限、不新增配置项、不改渠道配置。

Verification

Only what was actually run.

  • Commands and results:
    • 基线(仅新增测试、未改生产代码,upstream/main @ 9c293e8c0):
      cd relaykit && GOWORK=off go test ./relayconvert/internal/oai_responses -run 'TestResponsesRequestToChatCompletionsRequest(HoistsToolOutputMedia|KeepsNonContentToolOutputs)' -count=1 -v
      → TestResponsesRequestToChatCompletionsRequestHoistsToolOutputMedia FAIL:should have 3 item(s), but has 2;实际 tool 消息 content 为含 data:image/png;base64,… 的 JSON 字符串。三个负向子测试 PASS(说明负向形态在修复前已是期望行为)。
    • 修复后同一包:GOWORK=off go test ./relayconvert/internal/oai_responses -count=1 → ok。
    • relaykit 模块:GOWORK=off go test ./... -count=1 → 全部 ok;GOWORK=off go vet ./... → 通过;GOWORK=off go build ./... → 通过。
    • golden:relaykit 下 GOWORK=off go test ./relayconvert -run TestGolden -count=1 → ok(本次改动不需要更新快照;openai_responses_to_openai.golden.json 不含 function_call_output)。
    • 根模块:GOWORK=off go vet ./... → 通过;GOWORK=off go build ./... → 通过;make test(root Go module + relaykit 两个模块)→ 全部 ok,无失败项。
    • 格式:gofmt -l relayconvert/internal/oai_responses/ → 无输出。
    • 后续跟进(新 head 6bd5af3bd):先在 06a363645 上只改测试运行 oai_responses 包的三个定向用例
      (HoistsToolOutputMedia / HoistsToolOutputMediaForms / KeepsNonContentToolOutputs,Docker golang:1.26,GOWORK=off,-count=1 -v)
      → HoistsToolOutputMediaForms 的三个子用例 FAIL:"firstsecond" vs "first\nsecond"、"" vs "[image]"、"" vs "[image] [file]";
      修复后同一命令全 ok。并重跑 relaykit go test ./... -count=1、go vet ./...、go build ./...、go test ./relayconvert -run TestGolden -count=1,
      根模块 go vet ./...、go build ./...、make test,以及 gofmt -l relayconvert/internal/oai_responses/(无输出),全部通过。
  • Manual steps and observed result: 无额外手工步骤;上述协议回归测试即为可重复验证。
  • UI: 本次无 UI 变更。
  • Tests added or updated: TestResponsesRequestToChatCompletionsRequestHoistsToolOutputMedia、TestResponsesRequestToChatCompletionsRequestKeepsNonContentToolOutputs。
  • Databases / providers / platforms exercised: Linux/amd64 Docker(golang:1.26 / golang:1.26-alpine)运行单元测试;根模块使用 SQLite fixture;未调用真实 provider。
  • Not verified:
    • 未对真实上游发送请求(无付费模型调用),因此未验证各 OpenAI 兼容上游对「tool 消息后紧跟 user 消息」形态与 [image] 等占位文案的接受度差异。
    • 未覆盖 custom_tool_call_output 等其它 Responses item 类型。
    • 未在 macOS / Windows 上重复运行测试。
    • 附带观察(与本 PR 无关):relaykit/dto/usage_merge_test.go 在未修改的 upstream/main 上即不符合 gofmt -l;本 PR 未触碰该文件。

Risks

  • Failure modes: 只有「output 为含非文本块的 Responses 内容块数组」这一形态的报文形状会变化(无文本时 tool 内容为 [image] 等合成占位,多文本块以 \n 连接);若某上游不接受 tool 消息后紧跟 user 消息或占位文案,该请求会以 400/422 失败,而不是此前的 context 超限。
  • Billing / quota / auth impact: 不再把 base64 当文本计入 prompt tokens(输入 token 会下降),未修改任何计费逻辑、倍率或鉴权路径。
  • Follow-ups: Claude→Chat 的同类字符串化由 fix(relaykit): hoist tool_result images instead of stringifying them #7444 处理;本 PR 与其对齐占位与文本连接策略,但不引入其混合数组丢块行为。

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
    • Improved conversion of tool results containing mixed text and media.
    • Text remains associated with the tool response, while images and other media appear in a separate chat message.
    • Media-only results now display clear type-based placeholders instead of empty tool content.
    • Multiple text blocks are combined consistently, and duplicate media labels are avoided.
    • Non-media results, including objects, arrays, and text-only responses, continue to display as tool message content.
  • Tests
    • Added coverage for mixed media, media-only, text-only, object, and array tool-result formats.

… user message

修复 QuantumNous#7498:function_call_output.output 为内容块数组且含图片/文件等非文本块时,
responseToolOutputToChatContent 会把整个数组 JSON 序列化成 tool 消息的 content,
图片以 base64 文本形式进入请求体——上游会把二进制当作文本计数,触发
context_length_exceeded(实测一张 1,309,020 字节 PNG 使 prompt_tokens 达
1,070,945),且图像语义完全丢失。

- 内容块数组含非文本块时,文本留在 tool 消息,非文本块经
  responsesContentPartsToChatContent 同一映射落到紧随其后的一条 user 消息
  (Chat Completions 的 tool 消息按规范只能承载文本)。
- 字符串 / 对象 / 任意 JSON 数组 / 纯文本内容块数组保持既有字符串化行为。
- 新增回归测试:媒体提升,以及 object、[1,2]、纯文本内容块数组三个负向形态。
Copilot AI lite review requested due to automatic review settings September 21, 2026 05:32

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 40f94eb2-c8ba-4d14-a54e-bcd5ffb15014

📥 Commits

Reviewing files that changed from the base of the PR and between 06a3636 and 6bd5af3.

📒 Files selected for processing (2)
  • relaykit/relayconvert/internal/oai_responses/to_oai_chat_req.go
  • relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go

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


Walkthrough

The Responses-to-Chat converter now separates text and media in recognized function_call_output content-block arrays. Text remains in a tool message, while media becomes a following user message. Other output shapes retain their existing serialization.

Changes

Function call output media conversion

Layer / File(s) Summary
Content partitioning and message emission
relaykit/relayconvert/internal/oai_responses/to_oai_chat_req.go
Recognized content-block arrays are split into text and media. Text blocks are joined with newlines. Media is emitted in a following user message. Media-only output receives type-aware placeholders. Other shapes use the existing fallback serialization.
Conversion regression coverage
relaykit/relayconvert/internal/oai_responses/to_oai_chat_req_test.go
Tests verify image and file hoisting, preserved data URLs, placeholder deduplication, newline-separated text, and unchanged serialization for other output shapes.

Priority: ⬆️ High

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: calcium-ion

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed 变更满足 Issue #7498 的编码要求。splitFunctionCallOutputToChatMessages 将 function_call_output.output 的内容块分离。文本块使用换行连接并保留在 tool 消息中。非文本块通过既有 responsesContentPartsToChatContent 转换,并放入紧随其后的 user 消息。媒体不会进…
Out of Scope Changes check ✅ Passed 变更仅涉及 relaykit/relayconvert/internal/oai_responses/to_oai_chat_req.go 中的 Responses→Chat 转换逻辑及对应回归测试。媒体分离、既有输出行为保持和测试变更均直接支持 Issue #7498。未发现无关变更。
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确概括了主要变更:修复 Responses→Chat 转换将工具输出图片错误拍平成 base64 文本的问题。
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

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 hops where tool texts meet,
Images travel on a user’s feet.
Files wear labels, neat and bright,
Text joins softly with a newline’s light.
Base64 stays out of the prose,
And every content block now knows where it goes.

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

@Calcium-Ion

Copy link
Copy Markdown
Member

感谢贡献,但是经过审阅,我们决定新建pr,已标注您为co author,因此,此pr将被关闭

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.

[BUG] Responses→Chat 转换器把 function_call_output 的图片内容拍平成 base64 文本,触发上游 prompt 超限

3 participants