mirror of
https://github.com/Wei-Shaw/sub2api
synced 2026-12-06 01:12:31 +00:00
Merge pull request #9224 from debug-zhang/fix/8966-reasoning-only-completed
fix(openai): treat reasoning-only responses.completed as empty
This commit is contained in:
3 files changed
+278
-19
No files matched your search
@@ -748,10 +748,11 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
|
||||
if startsClientOutput && !openAIStreamEventTypeIsTerminal(eventType) {
|
||||
responsesSemanticOutputSeen = true
|
||||
}
|
||||
// OpenAI Responses streams that terminate with an empty
|
||||
// response.completed (no output, no usage, no error, nothing sent
|
||||
// to the client) are silent upstream refusals: fail over instead of
|
||||
// recording a successful 0/0 usage turn (issue #5009). Grok
|
||||
// OpenAI Responses streams that terminate with a
|
||||
// response.completed carrying no visible output (no message text,
|
||||
// no tool call, possibly reasoning items only) are silent upstream
|
||||
// refusals: fail over instead of recording a successful empty
|
||||
// turn (issues #5009, #8966). Grok
|
||||
// subscriptions behind vendor gateways show the same silent-refusal
|
||||
// shape on /v1/responses (forwardGrokResponses reaches this same
|
||||
// handler), so cover PlatformGrok too — the passthrough-path guard
|
||||
@@ -1468,14 +1469,24 @@ func extractOpenAIUsageFromJSONBytes(body []byte) (OpenAIUsage, bool) {
|
||||
}
|
||||
|
||||
// openAIResponsesCompletedEventIsEmpty reports whether a response.completed /
|
||||
// response.done SSE payload carries no usage, no error and no output items.
|
||||
// The accumulated usage is consulted too, because OpenAI may deliver usage on
|
||||
// an earlier event. An empty terminal event after a stream with no semantic
|
||||
// output is treated as a silent upstream refusal (issue #5009).
|
||||
// response.done SSE payload carries no visible output and no error. Emptiness is
|
||||
// classified by the terminal output items, not by usage: reasoning tokens are
|
||||
// billing-only, so a completion whose output holds nothing but reasoning items
|
||||
// is a silent empty turn (issue #8966). Usage is only a fallback for payloads
|
||||
// that carry no output items (missing, null or empty array), because OpenAI may
|
||||
// deliver usage on an earlier event and such partial terminal events must not
|
||||
// be failed over as empty. An empty terminal event after a stream with no
|
||||
// semantic output is treated as a silent upstream refusal (issues #5009, #7774).
|
||||
func openAIResponsesCompletedEventIsEmpty(data []byte, usage *OpenAIUsage) bool {
|
||||
if len(data) == 0 || !gjson.ValidBytes(data) {
|
||||
return false
|
||||
}
|
||||
if openAIResponsesCompletedHasError(data) {
|
||||
return false
|
||||
}
|
||||
if output, ok := openAIResponsesCompletedOutput(data); ok && len(output.Array()) > 0 {
|
||||
return !openAIResponsesOutputHasVisibleProduct(output)
|
||||
}
|
||||
if usage != nil && (usage.InputTokens > 0 || usage.OutputTokens > 0 ||
|
||||
usage.ImageInputTokens > 0 || usage.ImageOutputTokens > 0 ||
|
||||
usage.CacheCreationInputTokens > 0 || usage.CacheReadInputTokens > 0) {
|
||||
@@ -1484,15 +1495,107 @@ func openAIResponsesCompletedEventIsEmpty(data []byte, usage *OpenAIUsage) bool
|
||||
if gjson.GetBytes(data, "usage").Exists() || gjson.GetBytes(data, "response.usage").Exists() {
|
||||
return false
|
||||
}
|
||||
if gjson.GetBytes(data, "error").Exists() || gjson.GetBytes(data, "response.error").Exists() {
|
||||
return false
|
||||
}
|
||||
if output := gjson.GetBytes(data, "response.output"); output.Exists() && output.IsArray() && len(output.Array()) > 0 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// openAIResponsesCompletedHasError reports whether the terminal event carries a
|
||||
// real error. The documented completed event can include "error": null; a JSON
|
||||
// null (or an empty object/string) is not an error and must not hide an empty
|
||||
// turn from the caller.
|
||||
func openAIResponsesCompletedHasError(data []byte) bool {
|
||||
for _, path := range []string{"error", "response.error"} {
|
||||
errValue := gjson.GetBytes(data, path)
|
||||
if !errValue.Exists() {
|
||||
continue
|
||||
}
|
||||
switch errValue.Type {
|
||||
case gjson.Null:
|
||||
continue
|
||||
case gjson.JSON:
|
||||
if errValue.IsObject() && len(errValue.Map()) == 0 {
|
||||
continue
|
||||
}
|
||||
return true
|
||||
case gjson.String:
|
||||
if strings.TrimSpace(errValue.String()) == "" {
|
||||
continue
|
||||
}
|
||||
return true
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// openAIResponsesCompletedOutput locates the terminal output array. OpenAI
|
||||
// nests it under response.output; some compatible upstreams emit it at the top
|
||||
// level, mirroring the usage lookup in openAIResponsesCompletedEventIsEmpty.
|
||||
func openAIResponsesCompletedOutput(data []byte) (gjson.Result, bool) {
|
||||
for _, path := range []string{"response.output", "output"} {
|
||||
if output := gjson.GetBytes(data, path); output.IsArray() {
|
||||
return output, true
|
||||
}
|
||||
}
|
||||
return gjson.Result{}, false
|
||||
}
|
||||
|
||||
// openAIResponsesOutputHasVisibleProduct reports whether the terminal output
|
||||
// contains an item the downstream client can consume. Reasoning items never
|
||||
// count, even with encrypted content or a non-empty summary: only a message
|
||||
// body, a tool call, an image and similar products make a response complete.
|
||||
// Unknown item types count as visible so payloads this gateway does not model
|
||||
// are never failed over as empty.
|
||||
func openAIResponsesOutputHasVisibleProduct(output gjson.Result) bool {
|
||||
for _, item := range output.Array() {
|
||||
if !item.IsObject() {
|
||||
return true
|
||||
}
|
||||
switch strings.TrimSpace(item.Get("type").String()) {
|
||||
case "reasoning":
|
||||
continue
|
||||
case "message":
|
||||
if openAIResponsesMessageItemHasVisibleText(item) {
|
||||
return true
|
||||
}
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// openAIResponsesMessageItemHasVisibleText reports whether an assistant message
|
||||
// item carries text or a refusal the client can render. A message with empty
|
||||
// content is still an empty turn.
|
||||
func openAIResponsesMessageItemHasVisibleText(item gjson.Result) bool {
|
||||
if text := item.Get("text"); text.Exists() && strings.TrimSpace(text.String()) != "" {
|
||||
return true
|
||||
}
|
||||
content := item.Get("content")
|
||||
if !content.Exists() || content.Type == gjson.Null {
|
||||
return false
|
||||
}
|
||||
if content.Type == gjson.String {
|
||||
return strings.TrimSpace(content.String()) != ""
|
||||
}
|
||||
for _, part := range content.Array() {
|
||||
switch strings.TrimSpace(part.Get("type").String()) {
|
||||
case "output_text", "text":
|
||||
if strings.TrimSpace(part.Get("text").String()) != "" {
|
||||
return true
|
||||
}
|
||||
case "refusal":
|
||||
if strings.TrimSpace(part.Get("refusal").String()) != "" {
|
||||
return true
|
||||
}
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func mergeHostedImageGenToolUsage(imageGen gjson.Result, usage *OpenAIUsage) {
|
||||
if !imageGen.Exists() || !imageGen.IsObject() {
|
||||
return
|
||||
|
||||
@@ -141,8 +141,96 @@ func TestOpenAIResponsesCompletedEventIsEmpty(t *testing.T) {
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with output item",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","id":"msg_1"}]}}`,
|
||||
name: "reasoning only with explicit null error",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","error":null,"output":[{"type":"reasoning","id":"rs_1","summary":[]}]}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "reasoning only with empty error object",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","error":{},"output":[{"type":"reasoning","id":"rs_1","summary":[]}]}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "top-level explicit null error",
|
||||
data: `{"type":"response.completed","error":null,"response":{"id":"r1","status":"completed","output":[{"type":"reasoning","id":"rs_1","summary":[]}]}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "completed with message text",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"hello"}]}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with message refusal",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","id":"msg_1","content":[{"type":"refusal","refusal":"no"}]}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with message empty content",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","id":"msg_1","content":[{"type":"output_text","text":""}]}]}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "completed with reasoning and message text",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"reasoning","id":"rs_1","summary":[]},{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"hello"}]}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with function call",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with custom tool call",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"shell","input":"ls"}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with tool search call",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"tool_search_call","id":"ts_1","call_id":"call_1"}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "completed with image generation call",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"image_generation_call","id":"img_1","status":"completed"}]}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "reasoning only with reasoning usage",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"reasoning","id":"rs_1","encrypted_content":"enc"}],"usage":{"input_tokens":40,"output_tokens":9,"output_tokens_details":{"reasoning_tokens":9}}}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "reasoning only with accumulated usage",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"reasoning","id":"rs_1","summary":[]}]}}`,
|
||||
usage: &OpenAIUsage{
|
||||
InputTokens: 40,
|
||||
OutputTokens: 9,
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "reasoning only with non-empty summary",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"thinking"}]}]}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "empty output array with usage falls back to usage",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "top level output array",
|
||||
data: `{"type":"response.completed","output":[{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"hello"}]}]}`,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "output not an array falls back to usage",
|
||||
data: `{"type":"response.completed","response":{"id":"r1","output":{"type":"message"}}}`,
|
||||
usage: &OpenAIUsage{
|
||||
InputTokens: 3,
|
||||
OutputTokens: 1,
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
@@ -167,6 +255,74 @@ func TestOpenAIResponsesCompletedEventIsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIResponsesReasoningOnlyCompletedFailsOver verifies that a Responses
|
||||
// stream whose terminal output only holds reasoning items is treated as an
|
||||
// empty turn and failed over, even though usage reports reasoning tokens
|
||||
// (issue #8966).
|
||||
func TestOpenAIResponsesReasoningOnlyCompletedFailsOver(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_reasoning\",\"object\":\"response\",\"status\":\"in_progress\"}}\n\n" +
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_reasoning\",\"object\":\"response\",\"status\":\"completed\",\"output\":[{\"type\":\"reasoning\",\"id\":\"rs_1\",\"encrypted_content\":\"enc\"}],\"usage\":{\"input_tokens\":40,\"output_tokens\":9,\"total_tokens\":49,\"output_tokens_details\":{\"reasoning_tokens\":9}}}}\n\n",
|
||||
)),
|
||||
}}
|
||||
svc := newOpenAIImageGenerationControlTestService(upstream)
|
||||
c, recorder := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1")
|
||||
account := newOpenAIImageGenerationControlTestAccount()
|
||||
account.Extra = map[string]any{"openai_passthrough": true}
|
||||
|
||||
body := []byte(`{
|
||||
"model":"gpt-5.6-sol",
|
||||
"stream":true,
|
||||
"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]
|
||||
}`)
|
||||
|
||||
_, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.Error(t, err)
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.True(t, errors.As(err, &failoverErr), "reasoning-only completed must produce UpstreamFailoverError, got: %v", err)
|
||||
require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode)
|
||||
require.Empty(t, recorder.Body.String(), "no empty success stream may reach the client")
|
||||
}
|
||||
|
||||
// TestOpenAIResponsesReasoningWithMessageCompletedSucceeds ensures reasoning
|
||||
// items followed by a message with text are a normal completion, not an empty
|
||||
// turn (issue #8966 regression guard).
|
||||
func TestOpenAIResponsesReasoningWithMessageCompletedSucceeds(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_answer\",\"object\":\"response\",\"status\":\"in_progress\"}}\n\n" +
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_answer\",\"object\":\"response\",\"status\":\"completed\",\"output\":[{\"type\":\"reasoning\",\"id\":\"rs_1\",\"summary\":[]},{\"type\":\"message\",\"id\":\"msg_1\",\"content\":[{\"type\":\"output_text\",\"text\":\"done\"}]}],\"usage\":{\"input_tokens\":40,\"output_tokens\":9,\"total_tokens\":49}}}\n\n",
|
||||
)),
|
||||
}}
|
||||
svc := newOpenAIImageGenerationControlTestService(upstream)
|
||||
c, recorder := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1")
|
||||
account := newOpenAIImageGenerationControlTestAccount()
|
||||
account.Extra = map[string]any{"openai_passthrough": true}
|
||||
|
||||
body := []byte(`{
|
||||
"model":"gpt-5.6-sol",
|
||||
"stream":true,
|
||||
"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]
|
||||
}`)
|
||||
|
||||
result, err := svc.Forward(context.Background(), c, account, body)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Contains(t, recorder.Body.String(), "done")
|
||||
require.NotNil(t, result.Usage)
|
||||
require.Equal(t, 40, result.Usage.InputTokens)
|
||||
require.Equal(t, 9, result.Usage.OutputTokens)
|
||||
}
|
||||
|
||||
// TestOpenAIResponsesEmptyCompletedFailsOverGrok verifies that Grok platform
|
||||
// accounts — which reach the stream relay through forwardGrokResponses instead
|
||||
// of the passthrough path — get the same #5009 silent-refusal failover for an
|
||||
|
||||
@@ -16,7 +16,7 @@ const (
|
||||
openAISilentRefusalErrorCode = "openai_silent_refusal"
|
||||
openAISilentRefusalUpstreamMessage = "OpenAI upstream returned an empty completion stream with finish_reason=stop and no usage"
|
||||
openAISilentRefusalClientMessage = "Upstream returned an empty completion without usage; no fallback account was available"
|
||||
openAIResponsesEmptyCompletedMessage = "OpenAI upstream returned an empty response.completed stream with no output and no usage"
|
||||
openAIResponsesEmptyCompletedMessage = "OpenAI upstream returned an empty response.completed stream with no visible output"
|
||||
)
|
||||
|
||||
type openAIChatSilentRefusalDetector struct {
|
||||
@@ -272,8 +272,8 @@ func newOpenAISilentRefusalFailoverError(c *gin.Context, account *Account, upstr
|
||||
// newOpenAIResponsesEmptyCompletedFailoverError marks an empty
|
||||
// response.completed terminal event as a retryable upstream anomaly. OpenAI
|
||||
// Responses streams that deliver only response.created + response.completed
|
||||
// with no output, no usage and no error are treated as silent upstream
|
||||
// refusals rather than successful empty replies (issue #5009).
|
||||
// with no visible output and no error are treated as silent upstream refusals
|
||||
// rather than successful empty replies (issues #5009, #8966).
|
||||
func newOpenAIResponsesEmptyCompletedFailoverError(c *gin.Context, account *Account, upstreamRequestID string) *UpstreamFailoverError {
|
||||
accountID := int64(0)
|
||||
accountName := ""
|
||||
|
||||
Reference in new issue
Block a user