Skip to content

fix: preserve reasoning in Responses tool history - #6395

Closed
AmPlace wants to merge 1 commit into
QuantumNous:mainfrom
AmPlace:codex/fix-responses-chat-reasoning
Closed

AmPlace wants to merge 1 commit into
QuantumNous:mainfrom
AmPlace:codex/fix-responses-chat-reasoning

Conversation

@AmPlace

@AmPlace AmPlace commented Jul 21, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

Note

实现、最小复现和描述初稿由 OpenAI Codex 协助完成;我已经确认了问题、修复和测试

📝 变更描述 / Description

Responses→Chat 请求转换此前未识别 standalone reasoning input item,也没有保留 function/custom tool call 上内联的 reasoning_content。在 Agent 多轮工具调用历史中,这会让转换后的 assistant tool_calls 缺少 reasoning;严格要求完整回传 reasoning 的 Chat Completions 上游会在下一轮返回 HTTP 400。这个bug会影响到小米mimo在Codex中的调用,会出现只输出一句话就完成的问题,小米文档:Agent 多轮会话开启深度思考且历史存在工具调用时,后续请求必须完整回传带工具调用 assistant 的 reasoning_content,没回传的话就会 400 文档:https://mimo.mi.com/docs/zh-CN/usage-guide/passing-back-reasoning_content。

本改动仅修改 Responses 请求转换层:

  • 收集 reasoning item,并绑定到拥有工具调用的 assistant message;
  • 支持标准 summary、New API 生成的 content,以及内联 reasoning_content / reasoning;
  • 支持并行 function calls 和 custom tool calls;
  • 仅对完全相同的 reasoning 去重,不生成占位内容;
  • 不增加供应商特判、共享 DTO、全局缓存或 previous_response_id 状态管理。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 已搜索现有 Issues 与 PRs,未发现同一 Responses→Chat reasoning 历史丢失修复。
  • Bug fix 说明: 已关联可独立复现转换层数据丢失的 fix: Responses→Chat 转换丢失工具调用历史的 reasoning_content #6396。
  • 变更理解: 已确认 reasoning item、assistant tool calls 和 Chat reasoning_content 的映射关系。
  • 范围聚焦: 本 PR 仅修改请求转换实现及其回归测试。
  • 本地验证: 已运行修复前/后对照测试、转换层测试和静态检查。
  • 安全合规: 代码中无凭据、供应商密钥、日志隐私数据或新的持久化状态。

📸 运行证明 / Proof of Work

同一个回归测试仅应用到未修复的 main @ 1721144 时:

--- FAIL: TestResponsesRequestToChatCompletionsRequestPreservesToolCallReasoning
    --- FAIL: reasoning_before_parallel_function_calls
        expected 3 messages, got 4
        standalone reasoning was converted into a user message
    --- FAIL: reasoning_between_assistant_text_and_function_call
        expected 2 messages, got 4
    --- FAIL: reasoning_embedded_in_function_call
        expected reasoning_content: "Need the lookup."
        actual: ""
FAIL

应用本 PR 后,同一测试通过:

ok github.com/QuantumNous/new-api/service/relayconvert/internal/oai_responses

完整验证:

go test ./service/relayconvert/internal/oai_responses -count=1
go test ./service/relayconvert/... -count=1
go vet ./service/relayconvert/...
git diff --check

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The Responses-to-chat conversion now recognizes reasoning inputs, preserves reasoning across tool-call sequences, attaches it to assistant messages without duplication, and treats reasoning_text as plain text. A table-driven test covers multiple input orderings.

Changes

Reasoning preservation

Layer / File(s) Summary
Accumulate and attach reasoning
service/relayconvert/internal/oai_responses/to_oai_chat_req.go, service/relayconvert/internal/oai_responses/to_oai_chat_req_test.go
Reasoning items are accumulated across input arrays, attached to assistant messages around function and custom tool calls, deduplicated, and validated across multiple ordering scenarios. reasoning_text parts are converted as text.

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

Suggested reviewers: calcium-ion

Poem

A rabbit found thoughts in a tool-call trail,
And tucked them where assistant words prevail.
No duplicate echoes, neatly stored,
Reasoning now crosses every chord.
“Hop!” said the bunny, “the messages align!”

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly matches the main change: preserving reasoning in Responses tool history during conversion.
✨ 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.

@AmPlace
AmPlace marked this pull request as ready for review July 21, 2026 18:48

@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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
service/relayconvert/internal/oai_responses/to_oai_chat_req.go (1)

169-219: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated boilerplate between function_call and custom_tool_call cases.

Both branches follow the identical build→appendPendingReasoning→appendToolCallToLastAssistant→attach sequence, differing only in which constructor is called. Extracting a shared helper reduces duplication and centralizes the reasoning-attachment logic (which is exactly where the bugs above live) in one place.

♻️ Proposed refactor
+func responsesToolCallItemToChatMessages(item map[string]any, messages []dto.Message, pendingReasoning *string, build func(map[string]any) (dto.ToolCallRequest, error)) ([]dto.Message, error) {
+	toolCall, err := build(item)
+	if err != nil {
+		return nil, err
+	}
+	appendPendingReasoning(pendingReasoning, responsesItemReasoningText(item))
+	messages = appendToolCallToLastAssistant(messages, toolCall)
+	attachPendingReasoningToLastAssistant(messages, pendingReasoning)
+	return messages, nil
+}
+
 	case responsesInputTypeFunctionCall:
-		toolCall, err := responsesFunctionCallItemToChatToolCall(item)
-		if err != nil {
-			return nil, err
-		}
-		appendPendingReasoning(pendingReasoning, responsesItemReasoningText(item))
-		messages = appendToolCallToLastAssistant(messages, toolCall)
-		attachPendingReasoningToLastAssistant(messages, pendingReasoning)
-		return messages, nil
+		return responsesToolCallItemToChatMessages(item, messages, pendingReasoning, responsesFunctionCallItemToChatToolCall)
 	case responsesInputTypeCustomToolCall:
-		toolCall, err := responsesCustomToolCallItemToChatToolCall(item)
-		if err != nil {
-			return nil, err
-		}
-		appendPendingReasoning(pendingReasoning, responsesItemReasoningText(item))
-		messages = appendToolCallToLastAssistant(messages, toolCall)
-		attachPendingReasoningToLastAssistant(messages, pendingReasoning)
-		return messages, nil
+		return responsesToolCallItemToChatMessages(item, messages, pendingReasoning, responsesCustomToolCallItemToChatToolCall)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/relayconvert/internal/oai_responses/to_oai_chat_req.go` around lines
169 - 219, Refactor responsesInputItemToChatMessages by extracting the shared
tool-call handling sequence from the responsesInputTypeFunctionCall and
responsesInputTypeCustomToolCall cases into a helper. The helper should accept
the appropriate tool-call constructor result, pendingReasoning, and messages,
then perform appendPendingReasoning, appendToolCallToLastAssistant, and
attachPendingReasoningToLastAssistant; keep each case responsible only for
constructing the correct tool call and propagating errors.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@service/relayconvert/internal/oai_responses/to_oai_chat_req.go`:
- Around line 239-244: Update appendPendingReasoning and appendReasoningContent
so separately flushed reasoning segments are joined with a consistent delimiter,
preserving readable boundaries across reasoning→tool-call rounds. Replace
whole-buffer equality checks with segment-aware deduplication that prevents
replayed or overlapping reasoning from being appended while retaining distinct
content.
- Around line 246-256: Update attachPendingReasoningToLastAssistant so it checks
that the last message is an assistant before clearing *pending or extracting it
for attachment. Preserve pending reasoning unchanged when messages are empty or
the last message has another role, and clear it only after
appendReasoningContent successfully attaches it.

---

Nitpick comments:
In `@service/relayconvert/internal/oai_responses/to_oai_chat_req.go`:
- Around line 169-219: Refactor responsesInputItemToChatMessages by extracting
the shared tool-call handling sequence from the responsesInputTypeFunctionCall
and responsesInputTypeCustomToolCall cases into a helper. The helper should
accept the appropriate tool-call constructor result, pendingReasoning, and
messages, then perform appendPendingReasoning, appendToolCallToLastAssistant,
and attachPendingReasoningToLastAssistant; keep each case responsible only for
constructing the correct tool call and propagating errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d258f47e-7b34-4ed7-9975-3f3dd8cb88f8

📥 Commits

Reviewing files that changed from the base of the PR and between 1721144 and bbbf9ed.

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

@AmPlace

AmPlace commented Aug 1, 2026

Copy link
Copy Markdown
Author

由于当前仓库限制同一作者同时维护的开放 PR 数量,先暂时关闭。本分支和提交会保留;该补丁基于 relaykit 迁移前的 service/relayconvert 路径,后续会适配当前 relaykit 目录并补齐评审意见后再重新提交。

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.

fix: Responses→Chat 转换丢失工具调用历史的 reasoning_content

1 participant