Skip to content

fix: 修复 Message.ReasoningContent/Reasoning 空思考内容在请求转发时被静默丢弃 - #4520

Merged
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
heimoshuiyu:fix/message-reasoning-content-preserve-empty-string
Apr 29, 2026
Merged

fix: 修复 Message.ReasoningContent/Reasoning 空思考内容在请求转发时被静默丢弃#4520
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
heimoshuiyu:fix/message-reasoning-content-preserve-empty-string

Conversation

@heimoshuiyu

@heimoshuiyu heimoshuiyu commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

问题

在非 passThrough 模式下,客户端发送的 reasoning_content: "" 经过 Go struct 反序列化再序列化后,因 string + omitempty 无法区分空串和字段缺失,导致空的思考内容被静默丢弃。

违反 AGENTS.md Rule 6:可选标量字段必须使用指针类型。

复现场景

客户端发送:

{"messages": [{"role": "assistant", "content": "hello", "reasoning_content": ""}]}

上游收到(修复前):

{"messages": [{"role": "assistant", "content": "hello"}]}

reasoning_content 字段消失。

修复

dto.MessageReasoningContentReasoning 字段类型从 string 改为 *string

  • nil(字段缺失)→ JSON 中省略
  • &""(显式空串)→ JSON 中保留 "reasoning_content": ""

改动清单

文件 改动
dto/openai_request.go string*string,新增 GetReasoningContent()
relay/channel/openai/relay-openai.go 读取处改用 GetReasoningContent()
relay/channel/claude/relay-claude.go 写入处加 & + 空串守卫
relay/channel/gemini/relay-gemini.go 写入处加 &
relay/channel/ollama/stream.go 写入处加 &
dto/message_reasoning_test.go 新增测试

测试

=== RUN   TestMessageReasoningContentPreservesEmptyString
--- PASS
=== RUN   TestMessageReasoningContentOmitsAbsentField
--- PASS
=== RUN   TestMessageGetReasoningContent
--- PASS (4 sub-tests)

Summary by CodeRabbit

  • Bug Fixes

    • Improved reasoning content field handling to correctly omit absent fields in JSON responses while preserving explicit empty values across Claude, Gemini, Ollama, and OpenAI integrations.
  • Tests

    • Added comprehensive test coverage for reasoning content serialization, field precedence, and JSON marshaling/unmarshaling behavior.

关联 Issue

根因一致性:当上游(DeepSeek V4、Kimi K2.6、GLM-5.1 等)返回空的 reasoning_content: "" 后,客户端将其作为历史消息回传。NewAPI 在非 passThrough 模式下反序列化→再序列化时,string + omitempty 将空串静默丢弃。下一个请求缺少 reasoning_content 字段,导致上游拒绝请求并报错 reasoning_content is missing

问题:
在非 passThrough 模式下,客户端发送的 reasoning_content: "" 经过
Go struct 反序列化再序列化后,因 string + omitempty 无法区分空串和
字段缺失,导致空的思考内容被静默丢弃。

根因:
dto.Message.ReasoningContent 和 Message.Reasoning 使用 string(非指针)
加 omitempty,违反 AGENTS.md Rule 6(可选标量字段必须用指针类型)。

修复:
1. Message.ReasoningContent/Reasoning 类型从 string 改为 *string
   - nil = 字段缺失 → JSON 省略
   - &"" = 显式空串 → JSON 保留 reasoning_content: ""
2. 新增 Message.GetReasoningContent() 辅助方法
3. 更新所有读写处:relay-openai, relay-claude, relay-gemini, ollama
4. 新增测试覆盖空串保留、字段省略、getter 回退逻辑
@coderabbitai

coderabbitai Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

The PR refactors the Message model's ReasoningContent and Reasoning fields from string values to optional *string pointers across the DTO and relay handlers. This enables proper JSON omitempty behavior to distinguish between absent and empty-string values, with a new GetReasoningContent() accessor method providing safe field access.

Changes

Cohort / File(s) Summary
Core DTO Changes
dto/openai_request.go, dto/message_reasoning_test.go
Changed Message.ReasoningContent and Message.Reasoning from string to *string types; added GetReasoningContent() accessor that safely retrieves reasoning content with nil-handling and fallback logic; new test file validates JSON marshaling/unmarshaling preserves empty strings vs. absent fields.
Relay Handler Updates
relay/channel/claude/relay-claude.go, relay/channel/gemini/relay-gemini.go, relay/channel/ollama/stream.go
Updated assignments to use pointer references (&value) instead of direct string values when populating ReasoningContent fields; Claude handler includes conditional assignment only when content is non-empty.
Token Estimation
relay/channel/openai/relay-openai.go
Changed token estimation fallback logic to use choice.Message.GetReasoningContent() instead of manually concatenating separate reasoning fields.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • seefs001
  • Calcium-Ion

Poem

🐰 From strings to pointers, we leap and bound,
Reasoning fields now optional, safer and sound,
Empty or absent—each distinction clear,
No more ambiguity in the data here!
A getter to guide us through the nil-filled night,
This refactoring shines oh-so-bright! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main fix: preserving empty reasoning content during request forwarding by using pointer types instead of string types.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
relay/channel/gemini/relay-gemini.go (1)

1084-1101: ⚠️ Potential issue | 🟠 Major

Use common.GetPointer() instead of taking address of range variable.

Line 1100 assigns &part.Text from a range variable. In Go, range variables are reused across iterations, so this pointer will reference the final loop value rather than the value at each iteration, causing incorrect reasoning content to be set.

✅ Fix
 				} else if part.Thought {
-					choice.Message.ReasoningContent = &part.Text
+					choice.Message.ReasoningContent = common.GetPointer(part.Text)
 				} else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/gemini/relay-gemini.go` around lines 1084 - 1101, The code
takes the address of the range variable `part` when setting
`choice.Message.ReasoningContent = &part.Text`, which is unsafe because Go
reuses the range variable; instead call the helper to create a stable pointer
(e.g., use `common.GetPointer` with `part.Text`) inside the loop over
`candidate.Content.Parts` so each iteration gets its own pointer; update the
assignment in the branch that handles `part.Thought` to use
`common.GetPointer(part.Text)` (or the project's equivalent) rather than
`&part.Text`.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@relay/channel/gemini/relay-gemini.go`:
- Around line 1084-1101: The code takes the address of the range variable `part`
when setting `choice.Message.ReasoningContent = &part.Text`, which is unsafe
because Go reuses the range variable; instead call the helper to create a stable
pointer (e.g., use `common.GetPointer` with `part.Text`) inside the loop over
`candidate.Content.Parts` so each iteration gets its own pointer; update the
assignment in the branch that handles `part.Thought` to use
`common.GetPointer(part.Text)` (or the project's equivalent) rather than
`&part.Text`.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 839b69e2-9818-4365-8d76-0563197b1979

📥 Commits

Reviewing files that changed from the base of the PR and between db48108 and d77c709.

📒 Files selected for processing (6)
  • dto/message_reasoning_test.go
  • dto/openai_request.go
  • relay/channel/claude/relay-claude.go
  • relay/channel/gemini/relay-gemini.go
  • relay/channel/ollama/stream.go
  • relay/channel/openai/relay-openai.go

@Calcium-Ion
Calcium-Ion merged commit 6f57dcd into QuantumNous:main Apr 29, 2026
1 check passed
@code-new-bie

Copy link
Copy Markdown

已经更新 v1.0.0-rc.1 在使用 deepseek-v4系列模型 调用链 claude -> new api -> opencode go 还是存在 API Error: 400 {"error":{"type":"invalid_request_error","message":"Error from provider (DeepSeek): The reasoning_content in the thinking mode must be passed back to the API. (request id: 202604291245528727940798268d9d6QqhX3TZQ)"},"type":"error"}
image

@chuxiacxx

Copy link
Copy Markdown
QQ20260429-222537

Read(D:\source\repos\cxxdriver\Kernel\io\irp_dispatch.cpp · lines
2840-2859)
⎿ Read 20 lines

● Read(D:\source\repos\cxxdriver\Kernel\hv\hv_manager.cpp · lines
245-259)
⎿ Read 15 lines
● Read(D:\source\repos\cxxdriver\Kernel\hv\hv_backend.h · lines 260-279)
⎿ Read 20 lines
10:24 PM
⎿ API Error: 400 {"error":{"type":"","message":"thinking is
enabled but reasoning_content is missing in assistant tool call
message at index 2 (request id:
202604291424189043121368268d9d6lQuXpzIL)"},"type":"error"}

 使用更新后的版本依然在kimi k2.6上存在问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants