Skip to content

fix: 避免 Responses 流重复输出同一工具调用 - #6279

Closed
GreyKa-x wants to merge 1 commit into
QuantumNous:mainfrom
ANIMO-TECH:bug/codex/dedupe-responses-tool-call
Closed

fix: 避免 Responses 流重复输出同一工具调用#6279
GreyKa-x wants to merge 1 commit into
QuantumNous:mainfrom
ANIMO-TECH:bug/codex/dedupe-responses-tool-call

Conversation

@GreyKa-x

@GreyKa-x GreyKa-x commented Jul 18, 2026

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

Important

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

📝 变更描述 / Description

Responses 流在增量事件中已经输出工具调用后,终止事件的完整 response.output 可能再次携带同一 function_call。此前状态机在终止阶段因缺少 output_index,会按 item_id 创建第二个工具状态。

本 PR 在创建工具状态前先查询已有的 output_index、item_id 和 call_id 映射,命中时复用原状态;只有均未命中时才沿用原逻辑创建新 key。同时加入完整事件序列的回归测试。

本 PR 的代码与测试由 AI 辅助生成,提交者已对改动范围、状态机逻辑和测试结果进行审查。

🚀 变更类型 / Type of change

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

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

修复前,真实事件序列生成的工具 index 为:

[0, 0, 1]

修复后回归测试结果为:

[0, 0]

已通过:

go test ./service/relayconvert/...
go test ./relay/channel/openai

Summary by CodeRabbit

  • Bug Fixes
    • Improved streaming tool-call tracking to prevent duplicate tool entries when terminal responses repeat previously emitted tool calls.
    • Enhanced tool-call identity preservation so tool calls stay consistently associated across related stream events.
  • Tests
    • Added coverage verifying that terminal output repeating prior tool calls does not introduce unexpected duplicate tool-call entries.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The stream converter reuses existing tool mappings before generating keys, preventing duplicate tool calls when terminal output repeats an earlier streamed function call. A regression test covers the complete event sequence.

Changes

Responses tool-call deduplication

Layer / File(s) Summary
Reuse tool mappings and verify terminal output
service/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go, service/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go
ensureToolForEvent reuses item-ID or call-ID mappings; the regression test confirms terminal output does not create an additional tool index.

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

Possibly related issues

Possibly related PRs

Suggested reviewers: calcium-ion

Poem

I’m a rabbit guarding calls in the stream,
No duplicate tools shall burst from the seam.
Mappings stay linked, from delta to done,
The terminal echoes, but adds not one.
Hop, hop—clean chunks for everyone!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly states the main fix: preventing duplicate tool calls in Responses-to-Chat Completions streaming.
Linked Issues check ✅ Passed The code reuses existing tool state across output_item added, delta, done, and completed events, matching the #6278 fix and regression test.
Out of Scope Changes check ✅ Passed The changes stay focused on the duplicate-tool-call fix and its regression test, with no obvious unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@GreyKa-x
GreyKa-x force-pushed the bug/codex/dedupe-responses-tool-call branch from da6f19a to 3efbbab Compare July 18, 2026 04:46

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

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

272-288: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Flatten the nested lookups to improve readability.

As per coding guidelines, prefer clear branches and well-named local variables over deep nesting or layered control flow. Flattening the fallback lookups with an else if branch and short-circuit evaluation makes the code much more direct and easier to read.

♻️ Proposed refactor
 	if tool == nil {
-		if itemID := responseStreamEventItemID(event); itemID != "" {
-			if existingKey := s.itemIDToKey[itemID]; existingKey != "" {
-				tool = s.toolByKey[existingKey]
-			}
-		}
-		if tool == nil {
-			if callID := strings.TrimSpace(event.Item.CallId); callID != "" {
-				if existingKey := s.callIDToKey[callID]; existingKey != "" {
-					tool = s.toolByKey[existingKey]
-				}
-			}
-		}
+		itemID := responseStreamEventItemID(event)
+		callID := strings.TrimSpace(event.Item.CallId)
+
+		if itemID != "" && s.itemIDToKey[itemID] != "" {
+			tool = s.toolByKey[s.itemIDToKey[itemID]]
+		} else if callID != "" && s.callIDToKey[callID] != "" {
+			tool = s.toolByKey[s.callIDToKey[callID]]
+		}
+
 		if tool != nil {
 			s.toolByKey[key] = tool
 		}
 	}
🤖 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_stream_resp.go`
around lines 272 - 288, Refactor the fallback lookup in the tool-resolution
block to use clear short-circuit branches: resolve by item ID first, then use an
else-if fallback for the trimmed call ID lookup only when no tool was found.
Preserve the existing mappings and final s.toolByKey[key] assignment, while
reducing nested conditionals and retaining the current lookup behavior.

Source: Coding guidelines

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

Nitpick comments:
In `@service/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go`:
- Around line 272-288: Refactor the fallback lookup in the tool-resolution block
to use clear short-circuit branches: resolve by item ID first, then use an
else-if fallback for the trimmed call ID lookup only when no tool was found.
Preserve the existing mappings and final s.toolByKey[key] assignment, while
reducing nested conditionals and retaining the current lookup behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e91b774e-1bc0-48d6-bc98-8489dab3ef3a

📥 Commits

Reviewing files that changed from the base of the PR and between da6f19a and 3efbbab.

📒 Files selected for processing (2)
  • service/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go
  • service/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • service/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go

@GreyKa-x

Copy link
Copy Markdown
Author

Closing this duplicate submission; the fix remains available on our fork branch for internal use.

@GreyKa-x GreyKa-x closed this Jul 18, 2026
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.

Responses 流转 Chat Completions 时可能重复输出同一工具调用

1 participant