fix(relay): Claude 流开始输出后不再换渠道重试,上游 error 转给客户端 (#8550)

上游在流中途发来 error 事件(如 overloaded_error)时,HandleStreamResponseData
返回 500。重试判断不知道这次尝试已经给客户端写过事件,换渠道重来,新流接在
半截旧流后面,客户端看到两个 message_start;全部失败时还会再补一个 error。

- 还没有事件写给客户端:照旧可以重试。
- 已写出事件但没有输出:不重试,由 relay 在同一条流里发 error 并退款。
- 已有输出:不重试,error 事件转给客户端(保留上游 type 和 message),
  已送达的输出按上游报告的 usage 计费,没报告则按估算。
- Claude 转 Responses:发出 response.failed 后同样只为已送达的输出计费,
  没有输出不收费,流状态记为失败。

controller 的 writeRelayStreamError 移到 helper.StreamErrorData,供 Claude
处理器复用。
This commit is contained in:
Calcium-Ion authored and GitHub committed 2026-12-03 18:34:34 +08:00
1 parent 5911c8cca8
commit 080997bf23
7 files changed
+162 -50

No files matched your search

+1 -19
View File
@@ -24,7 +24,6 @@ import (
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/relay/requestplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/operation_setting"
@@ -108,7 +107,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
upstreamURLs := common.UpstreamAddresses(c)
if relayFormat != types.RelayFormatOpenAIRealtime && c.Writer.Written() &&
strings.HasPrefix(c.Writer.Header().Get("Content-Type"), "text/event-stream") {
writeRelayStreamError(c, relayFormat, newAPIError)
helper.StreamErrorData(c, relayFormat, newAPIError)
return
}
if relayFormat != types.RelayFormatOpenAIRealtime {
@@ -269,23 +268,6 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
}
}
func writeRelayStreamError(c *gin.Context, format types.RelayFormat, apiError *types.NewAPIError) {
// 心跳提交响应头后,最终错误继续通过同一个流返回。
status, _ := common.GetContextKeyType[*relaycommon.StreamStatus](c, constant.ContextKeyResponseStreamStatus)
if status == nil {
status = relaycommon.NewStreamStatus()
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, status)
}
status.MarkFailed(string(apiError.GetErrorCode()), string(apiError.GetErrorType()), apiError.StatusCode)
upstreamURLs := common.UpstreamAddresses(c)
if format == types.RelayFormatClaude {
_ = helper.ClaudeData(c, dto.ClaudeResponse{Type: "error", Error: apiError.ToClaudeError(upstreamURLs...)})
return
}
_ = helper.ObjectData(c, gin.H{"error": apiError.ToOpenAIError(upstreamURLs...)})
helper.Done(c)
}
// CountClaudeTokens implements Anthropic's token-counting utility endpoint.
// It deliberately skips upstream generation and billing; callers use this
// endpoint to size prompts before creating a Message.
+1 -1
View File
@@ -283,7 +283,7 @@ func TestRelayStreamErrorAfterKeepAlive(t *testing.T) {
common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, "https://provider.example")
common.SetContextKey(c, constant.ContextKeyUpstreamRequestOrigin, "https://provider.example")
apiError := types.NewErrorWithStatusCode(errors.New("upstream rejected input at https://provider.example/v1/messages"), types.ErrorCodeBadResponseStatusCode, http.StatusBadRequest)
writeRelayStreamError(c, format, apiError)
helper.StreamErrorData(c, format, apiError)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, "text/event-stream", recorder.Header().Get("Content-Type"))
require.Contains(t, recorder.Body.String(), "upstream rejected input")
+4 -1
View File
@@ -284,6 +284,7 @@ func awsStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, a *Adaptor) (
}
events := stream.Events()
started := false
streamLoop:
for {
select {
@@ -302,8 +303,10 @@ streamLoop:
info.SetFirstResponseTime()
respErr := claude.HandleStreamResponseData(c, info, claudeInfo, string(v.Value.Bytes))
if respErr != nil {
return respErr, nil
usage, err := claude.HandleStartedStreamError(c, info, claudeInfo, started, respErr)
return err, usage
}
started = true
case *bedrockruntimeTypes.UnknownUnionMember:
fmt.Println(common.LogText("unknown tag: %v", v.Tag))
return types.NewError(errors.New("unknown response type"), types.ErrorCodeInvalidRequest), nil
+57 -29
View File
@@ -273,34 +273,7 @@ func recordClaudeServerToolUse(info *relaycommon.RelayInfo, serverToolUse *dto.C
}
func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
// Claude input_tokens excludes cache reads and writes, so a fully cached
// prompt reports zero input; the prompt is uncounted only when the total
// with cache is zero as well. Zero output is uncounted only when content
// was streamed, so a refusal before any output keeps its zeros.
missingInputUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage).PromptTokens == 0
missingOutputUsage := claudeInfo.Usage.CompletionTokens == 0 && claudeInfo.ResponseText.Len() > 0
if missingInputUsage || missingOutputUsage || !claudeInfo.Done {
if common.DebugEnabled {
common.SysLog(common.LogText("claude response usage is not complete, maybe upstream error"))
}
// 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
// Each tool_use block costs about 40 output tokens beyond its name and JSON
// input (measured on Claude Haiku 4.5 and Sonnet 5 agent turns).
fallback.CompletionTokens += claudeInfo.ToolUseCount * 40
if missingOutputUsage ||
(!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
}
if missingInputUsage {
claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
}
if claudeInfo.Usage != nil {
claudeInfo.Usage.UsageSemantic = "anthropic"
}
relayconvert.FinalizeClaudeStreamBillingUsage(claudeInfo)
completeClaudeStreamUsage(c, info, claudeInfo)
if info.RelayFormat == types.RelayFormatClaude {
//
@@ -331,6 +304,58 @@ func HandleStreamFinalResponse(c *gin.Context, info *relaycommon.RelayInfo, clau
}
}
// HandleStartedStreamError settles a stream that fails after events have
// reached the client. A retry would splice a second message into the same
// response, so the failure ends this stream without one: with output
// delivered, the client gets the error event here and the output is billed;
// with none, the error goes back to the relay, which sends it and refunds.
func HandleStartedStreamError(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo, started bool, streamErr *types.NewAPIError) (*dto.Usage, *types.NewAPIError) {
if !started {
return nil, streamErr
}
if claudeInfo.ResponseText.Len() == 0 {
types.ErrOptionWithSkipRetry()(streamErr)
return nil, streamErr
}
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
helper.StreamErrorData(c, info.RelayFormat, streamErr)
completeClaudeStreamUsage(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
// completeClaudeStreamUsage fills the usage a stream left unreported from the
// streamed content and finalizes its billing usage.
func completeClaudeStreamUsage(c *gin.Context, info *relaycommon.RelayInfo, claudeInfo *ClaudeResponseInfo) {
// Claude input_tokens excludes cache reads and writes, so a fully cached
// prompt reports zero input; the prompt is uncounted only when the total
// with cache is zero as well. Zero output is uncounted only when content
// was streamed, so a refusal before any output keeps its zeros.
missingInputUsage := buildOpenAIStyleUsageFromClaudeUsage(claudeInfo.Usage).PromptTokens == 0
missingOutputUsage := claudeInfo.Usage.CompletionTokens == 0 && claudeInfo.ResponseText.Len() > 0
if missingInputUsage || missingOutputUsage || !claudeInfo.Done {
if common.DebugEnabled {
common.SysLog(common.LogText("claude response usage is not complete, maybe upstream error"))
}
// 只补缺失字段,不整份覆盖——保留 message_start 已拿到的 cache 字段
fallback := service.ResponseText2Usage(c, claudeInfo.ResponseText.String(), info.UpstreamModelName, info.GetEstimatePromptTokens())
// Each tool_use block costs about 40 output tokens beyond its name and JSON
// input (measured on Claude Haiku 4.5 and Sonnet 5 agent turns).
fallback.CompletionTokens += claudeInfo.ToolUseCount * 40
if missingOutputUsage ||
(!claudeInfo.Done && fallback.CompletionTokens > claudeInfo.Usage.CompletionTokens) {
claudeInfo.Usage.CompletionTokens = fallback.CompletionTokens
}
if missingInputUsage {
claudeInfo.Usage.PromptTokens = fallback.PromptTokens
}
claudeInfo.Usage.TotalTokens = claudeInfo.Usage.PromptTokens + claudeInfo.Usage.CompletionTokens
}
if claudeInfo.Usage != nil {
claudeInfo.Usage.UsageSemantic = "anthropic"
}
relayconvert.FinalizeClaudeStreamBillingUsage(claudeInfo)
}
func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (*dto.Usage, *types.NewAPIError) {
claudeInfo := &ClaudeResponseInfo{
ResponseId: helper.GetResponseID(c),
@@ -340,15 +365,18 @@ func ClaudeStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.
Usage: &dto.Usage{},
}
var err *types.NewAPIError
started := false
helper.StreamScannerHandler(c, resp, info, func(data string, sr *helper.StreamResult) {
err = HandleStreamResponseData(c, info, claudeInfo, data)
if err != nil {
sr.Stop(err)
return
}
started = true
})
info.StreamStatus.RequireTerminal()
if err != nil {
return nil, err
return HandleStartedStreamError(c, info, claudeInfo, started, err)
}
HandleStreamFinalResponse(c, info, claudeInfo)
+69
View File
@@ -2,6 +2,7 @@ package claude
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
@@ -65,6 +66,74 @@ func TestClaudeStreamFinalUsageEstimatesOnlyUncountedUsage(t *testing.T) {
}
}
func TestClaudeStreamErrorRetriesOnlyBeforeTheClientGotEvents(t *testing.T) {
gin.SetMode(gin.TestMode)
previousTimeout := constant.StreamingTimeout
constant.StreamingTimeout = 30
t.Cleanup(func() { constant.StreamingTimeout = previousTimeout })
start := `{"type":"message_start","message":{"id":"msg_1","model":"claude-opus-4-8","usage":{"input_tokens":1000,"output_tokens":1}}}`
thinking := `{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hello"}}`
overloaded := `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`
for _, tc := range []struct {
name string
format types.RelayFormat
events []string
wantErr bool
wantRetry bool
wantInput int
wantOutput int
wantBody []string
}{
{name: "error before any event may retry", format: types.RelayFormatClaude, events: []string{overloaded}, wantErr: true, wantRetry: true},
{name: "error after message_start ends the stream unbilled", format: types.RelayFormatClaude, events: []string{start, overloaded}, wantErr: true},
{name: "error after output reaches the client and bills it", format: types.RelayFormatClaude, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{"event: error\n", `"type":"overloaded_error"`}},
{name: "converted chat stream gets the error and bills the output", format: types.RelayFormatOpenAI, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{`"error":`, `"overloaded_error"`, "data: [DONE]"}},
{name: "converted responses stream bills the output before response.failed", format: types.RelayFormatOpenAIResponses, events: []string{start, thinking, overloaded}, wantInput: 1000, wantOutput: 2, wantBody: []string{"event: response.failed\n"}},
{name: "converted responses stream failing before output is free", format: types.RelayFormatOpenAIResponses, events: []string{start, overloaded}, wantBody: []string{"event: response.failed\n"}},
} {
t.Run(tc.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
info := &relaycommon.RelayInfo{RelayFormat: tc.format, IsStream: true, ChannelMeta: &relaycommon.ChannelMeta{UpstreamModelName: "claude-opus-4-8"}}
info.SetEstimatePromptTokens(1200)
var body strings.Builder
for _, event := range tc.events {
body.WriteString("data: " + event + "\n\n")
}
resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body.String()))}
handler := ClaudeStreamHandler
if tc.format == types.RelayFormatOpenAIResponses {
handler = ClaudeResponsesStreamHandler
}
usage, apiErr := handler(c, resp, info)
if tc.wantErr {
require.NotNil(t, apiErr)
assert.Nil(t, usage, "a failure without output is refunded")
assert.Equal(t, tc.wantRetry, !types.IsSkipRetryError(apiErr))
assert.NotContains(t, recorder.Body.String(), "Overloaded", "the relay sends the error once")
return
}
require.Nil(t, apiErr)
for _, want := range tc.wantBody {
assert.Contains(t, recorder.Body.String(), want)
}
assert.Equal(t, 1, strings.Count(recorder.Body.String(), tc.wantBody[0]), "the failure is sent once")
assert.True(t, info.StreamStatus.ResponseFailed())
assert.Equal(t, tc.wantInput, usage.PromptTokens)
assert.Equal(t, tc.wantOutput, usage.CompletionTokens)
if tc.wantOutput == 0 {
return
}
canonical, ok := usage.BillingUsage.CanonicalUsage()
require.True(t, ok)
assert.Equal(t, tc.wantOutput, canonical.CompletionTokens, "settlement must bill the delivered output")
})
}
}
func TestResponseOpenAI2ClaudeToolUseInputIsObject(t *testing.T) {
tests := []struct {
name string
+9
View File
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper"
@@ -78,6 +79,8 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
return true
}
}
info.StreamStatus.MarkFailed("server_error", "", 0)
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, info.StreamStatus)
streamFailed = true
return true
}
@@ -162,6 +165,12 @@ func ClaudeResponsesStreamHandler(c *gin.Context, resp *http.Response, info *rel
return nil, streamErr
}
if streamFailed {
// The client received response.failed: output it got before the failure
// is billed, and a failure before any output is free.
if claudeInfo.ResponseText.Len() == 0 {
return &dto.Usage{}, nil
}
completeClaudeStreamUsage(c, info, claudeInfo)
return claudeInfo.Usage, nil
}
+21
View File
@@ -9,7 +9,9 @@ import (
"time"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
@@ -296,6 +298,25 @@ func Done(c *gin.Context) {
_ = StringData(c, "[DONE]")
}
// StreamErrorData ends a stream whose response has already started with an
// error event in the client's protocol, and records the failure on the
// response stream status.
func StreamErrorData(c *gin.Context, format types.RelayFormat, apiError *types.NewAPIError) {
status, _ := common.GetContextKeyType[*relaycommon.StreamStatus](c, constant.ContextKeyResponseStreamStatus)
if status == nil {
status = relaycommon.NewStreamStatus()
common.SetContextKey(c, constant.ContextKeyResponseStreamStatus, status)
}
status.MarkFailed(string(apiError.GetErrorCode()), string(apiError.GetErrorType()), apiError.StatusCode)
upstreamURLs := common.UpstreamAddresses(c)
if format == types.RelayFormatClaude {
_ = ClaudeData(c, dto.ClaudeResponse{Type: "error", Error: apiError.ToClaudeError(upstreamURLs...)})
return
}
_ = ObjectData(c, gin.H{"error": apiError.ToOpenAIError(upstreamURLs...)})
Done(c)
}
func WssString(c *gin.Context, ws *websocket.Conn, str string) error {
if ws == nil {
logger.LogError(c, common.LogText("websocket connection is nil"))