Repository navigation
Conversation
WalkthroughOpenAI Responses streaming now assigns sequence numbers to emitted events, emits ChangesOpenAI streaming error handling
Estimated code review effort: 3 (Moderate) | ~15 minutes Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@controller/relay.go`:
- Around line 102-106: The Relay response-handling path must prevent retries
after OaiChatToResponsesStreamHandler writes a terminal response.failed or
response.error SSE. Mark streamErr as non-retryable before returning the handler
error, or bypass the post-handler retry path whenever the response has already
been written, while preserving normal retries for failures without a written
terminal response.
In `@relay/channel/openai/chat_via_responses_test.go`:
- Around line 210-219: Update the test assertions around the response.created
and response.failed events to decode both payloads and verify the required
response identity fields: matching response IDs, matching creation timestamps,
and model set to gpt-test. Preserve the existing failure status, code, message,
and event-order assertions.
In `@relay/channel/openai/responses_via_chat.go`:
- Around line 140-168: Centralize the post-write terminal-error handling
currently implemented for scanner-phase streamErr into a reusable finalization
path near the response streaming flow. Update the FinalizeStreamResponse and
final-result conversion error branches to invoke that path after
response.created has been written, so each emits response.failed with the same
code/message fallback behavior instead of returning directly; preserve direct
returns for errors that occur before any response is written.
🪄 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 Plus
Run ID: bdcfbe71-0911-400d-aeff-6b0e92255fc6
📒 Files selected for processing (3)
controller/relay.gorelay/channel/openai/chat_via_responses_test.gorelay/channel/openai/responses_via_chat.go
| if !c.Writer.Written() { | ||
| c.JSON(newAPIError.StatusCode, gin.H{ | ||
| "error": newAPIError.ToOpenAIError(), | ||
| }) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline controller/relay.go --items all --match 'Relay|shouldRetry'
rg -n -C 10 --glob '*.go' \
'func shouldRetry\b|shouldRetry\s*\(' \
.
rg -n -C 10 --glob '*.go' \
'OaiChatToResponsesStreamHandler|response\.failed' \
controller relayRepository: QuantumNous/new-api
Length of output: 22872
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the control flow around handler calls, error handling, retry guard, and channel reset after a retry.
sed -n '68,240p' controller/relay.go | cat -n
sed -n '295,365p' controller/relay.go | cat -nRepository: QuantumNous/new-api
Length of output: 10112
Prevent retries after terminal streaming failures.
If OaiChatToResponsesStreamHandler emits response.failed, it writes SSE and then returns http.StatusInternalServerError; when retry is still allowed, Relay can invoke getChannel again and select another channel. response.failed/response.error from OpenAI responses streams must be terminal, so mark streamErr as a skip-retry error before returning it or bypass the post-handler retry path after a written response.
🤖 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 `@controller/relay.go` around lines 102 - 106, The Relay response-handling path
must prevent retries after OaiChatToResponsesStreamHandler writes a terminal
response.failed or response.error SSE. Mark streamErr as non-retryable before
returning the handler error, or bypass the post-handler retry path whenever the
response has already been written, while preserving normal retries for failures
without a written terminal response.
| got := recorder.Body.String() | ||
| require.Contains(t, got, `event: response.created`) | ||
| require.Contains(t, got, `event: response.failed`) | ||
| require.Contains(t, got, `"status":"failed"`) | ||
| require.Contains(t, got, `"code":"upstream_failure"`) | ||
| require.Contains(t, got, `"message":"upstream failed"`) | ||
| require.NotContains(t, got, `event: response.completed`) | ||
| requireOrderedSubstrings(t, got, | ||
| `event: response.created`, | ||
| `event: response.failed`, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert the failed response identity fields.
This test does not verify the required reused response ID, creation time, and model. Decode the response.created and response.failed payloads, then assert matching ID/created values and model gpt-test.
As per coding guidelines, backend tests must protect API contracts.
🤖 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 `@relay/channel/openai/chat_via_responses_test.go` around lines 210 - 219,
Update the test assertions around the response.created and response.failed
events to decode both payloads and verify the required response identity fields:
matching response IDs, matching creation timestamps, and model set to gpt-test.
Preserve the existing failure status, code, message, and event-order assertions.
Source: Coding guidelines
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
relay/channel/openai/chat_via_responses_test.go (1)
262-265: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTwo identical require/assert mismatches for non-fatal per-event checks. Both loops correctly use
require.NotNilfto guard the nil dereference, but follow it withrequire.Equalffor a non-fatal value comparison that should useassert.Equalfso all mismatched events surface instead of stopping at the first failure.
relay/channel/openai/chat_via_responses_test.go#L262-L265: changerequire.Equalf(t, int64(i), *event.SequenceNumber, ...)toassert.Equalf(...), keeprequire.NotNilfas-is.relay/channel/openai/chat_via_responses_test.go#L334-L337: same change toassert.Equalf(...), keeprequire.NotNilfas-is.🤖 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 `@relay/channel/openai/chat_via_responses_test.go` around lines 262 - 265, In both event-validation loops in relay/channel/openai/chat_via_responses_test.go at lines 262-265 and 334-337, replace the non-nil-guarded require.Equalf sequence-number comparison with assert.Equalf while keeping require.NotNilf unchanged, so all mismatched events are reported without stopping at the first failure.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.
Inline comments:
In `@relay/channel/openai/chat_via_responses_test.go`:
- Around line 339-346: Extend the failure-event assertions in the relevant
response stream tests, including
TestOaiChatToResponsesStreamHandlerEmitsFailureAfterOutput, to verify
failed.Payload["response"] reuses the original response ID, created timestamp,
and model. Capture or reference the initial response values and compare them
against the corresponding fields on response.failed while preserving the
existing error.code and error.message checks.
---
Nitpick comments:
In `@relay/channel/openai/chat_via_responses_test.go`:
- Around line 262-265: In both event-validation loops in
relay/channel/openai/chat_via_responses_test.go at lines 262-265 and 334-337,
replace the non-nil-guarded require.Equalf sequence-number comparison with
assert.Equalf while keeping require.NotNilf unchanged, so all mismatched events
are reported without stopping at the first failure.
🪄 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 Plus
Run ID: 2b4ea8e6-312a-404a-89b5-1dbb5563eb45
📒 Files selected for processing (6)
dto/openai_response.gorelay/channel/openai/chat_via_responses_test.gorelay/channel/openai/responses_via_chat.goservice/relayconvert/internal/oai_chat/to_oai_responses_resp.goservice/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.goservice/relayconvert/response_registry.go
💤 Files with no reviewable changes (1)
- service/relayconvert/internal/oai_chat/to_oai_responses_resp.go
🚧 Files skipped from review as they are similar to previous changes (1)
- relay/channel/openai/responses_via_chat.go
| failed := events[len(events)-1] | ||
| require.Equal(t, "response.failed", failed.Type) | ||
| response, ok := failed.Payload["response"].(map[string]any) | ||
| require.True(t, ok) | ||
| errorObject, ok := response["error"].(map[string]any) | ||
| require.True(t, ok) | ||
| require.Equal(t, "upstream_failure", errorObject["code"]) | ||
| require.Equal(t, "upstream failed", errorObject["message"]) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert reused response identity (ID/created/model) on response.failed.
Only error.code/error.message are checked. Per the PR objective, the failure event must reuse the original response's ID, created time, and model — this new test still doesn't verify that, the same gap flagged on the earlier (unchanged) TestOaiChatToResponsesStreamHandlerEmitsFailureAfterOutput test.
🤖 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 `@relay/channel/openai/chat_via_responses_test.go` around lines 339 - 346,
Extend the failure-event assertions in the relevant response stream tests,
including TestOaiChatToResponsesStreamHandlerEmitsFailureAfterOutput, to verify
failed.Payload["response"] reuses the original response ID, created timestamp,
and model. Capture or reference the initial response values and compare them
against the corresponding fields on response.failed while preserving the
existing error.code and error.message checks.
|
由于当前仓库限制同一作者同时维护的开放 PR 数量,先暂时关闭。本分支和提交会保留;该补丁跨越 relaykit 迁移且目前与 main 冲突,后续会按当前流处理结构拆小、补充关联 Issue 后再提交。 |
Important
📝 变更描述 / Description
这个 PR 修的是
/v1/responses转发到 Chat Completions 时,流式请求中途报错会把 SSE 和普通 JSON 混在一起的问题。目前 Chat SSE 可能已经转换并输出了
response.created或其他 Responses 事件,后面上游才返回错误。之前OaiChatToResponsesStreamHandler检测到错误以后,会直接把错误返回给上层控制器;控制器发现有错误后,又会在已经开始输出的 SSE 后面继续写一段普通 JSON,最后响应会变成这样:这里主要有两个问题:
response.failed。这个 PR 把首包前和首包后的错误分开处理:
response.failed结束;response.failed.response.error会保留原来的code和message;新增回归测试:
response.created,之后才返回错误。说明:本次修改由 AI 辅助完成,代码和测试结果已经人工检查。
🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
目前没有精确对应的 Issue。
✅ 提交前检查项 / Checklist
responses_via_chat.go首包前、首包后错误边界以及 SSE / JSON 混流的提交。Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。📸 运行证明 / Proof of Work
运行:
结果:
另外运行:
未发现空白符或补丁格式问题。
Summary by CodeRabbit
response.failedevent (with status pluscode/message) and omitresponse.completed.sequence_numberto streamed responses events for stable event ordering.sequence_numbervalidation.