mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
Merge pull request #9255 from zanyatta/fix/xai-input-too-large
fix(grok): keep xAI context-window refusals as context_length_exceeded
This commit is contained in:
4 files changed
+256
No files matched your search
@@ -0,0 +1,160 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// xAI 对超出上下文窗口的请求回 400,原因只写在顶层 error 字符串里。
|
||||
const grokInputTooLargeBody = `{"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window (612345 tokens > 500000 tokens)"}`
|
||||
|
||||
const grokInputTooLargeNoCountsBody = `{"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window"}`
|
||||
|
||||
const grokGenericInvalidArgumentBody = `{"code":"invalid-argument","error":"Failed to start sampling: invalid tool schema"}`
|
||||
|
||||
func TestDetectGrokContextLengthExceeded(t *testing.T) {
|
||||
got, ok := detectGrokContextLengthExceeded(http.StatusBadRequest, []byte(grokInputTooLargeBody))
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)", got.Message)
|
||||
require.Equal(t, int64(500000), got.Window)
|
||||
|
||||
got, ok = detectGrokContextLengthExceeded(http.StatusBadRequest, []byte(grokInputTooLargeNoCountsBody))
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "The prompt is too long for this model's context window", got.Message)
|
||||
require.Zero(t, got.Window)
|
||||
|
||||
nested := `{"error":{"code":"invalid_argument","message":"[input_too_large] prompt exceeds window (12 tokens > 10 tokens)"}}`
|
||||
got, ok = detectGrokContextLengthExceeded(http.StatusBadRequest, []byte(nested))
|
||||
require.True(t, ok)
|
||||
require.Equal(t, int64(10), got.Window)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{name: "generic invalid argument", status: http.StatusBadRequest, body: grokGenericInvalidArgumentBody},
|
||||
{name: "context words without the explicit tag", status: http.StatusBadRequest, body: `{"code":"invalid-argument","error":"The prompt is too long for this model’s context window"}`},
|
||||
{name: "tag on a non-400", status: http.StatusInternalServerError, body: grokInputTooLargeBody},
|
||||
{name: "empty body", status: http.StatusBadRequest, body: ``},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, ok := detectGrokContextLengthExceeded(tc.status, []byte(tc.body))
|
||||
require.False(t, ok)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokInputTooLargeDoesNotFailoverOrCoolDown(t *testing.T) {
|
||||
repo := &grokQuotaAccountRepo{}
|
||||
svc := &OpenAIGatewayService{accountRepo: repo}
|
||||
account := &Account{ID: 8241, Platform: PlatformGrok, Type: AccountTypeOAuth}
|
||||
|
||||
require.False(t, svc.shouldFailoverGrokUpstreamError(http.StatusBadRequest, []byte(grokInputTooLargeBody)))
|
||||
svc.handleGrokAccountUpstreamError(context.Background(), account, http.StatusBadRequest, nil, []byte(grokInputTooLargeBody))
|
||||
require.Zero(t, repo.tempUnschedCalls)
|
||||
require.Zero(t, repo.rateLimitedCalls)
|
||||
require.Zero(t, repo.updateCalls)
|
||||
}
|
||||
|
||||
func TestGrokResponsesInputTooLargeKeepsContextLengthExceeded(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
upstreamWindow string
|
||||
wantMessage string
|
||||
wantWindow string
|
||||
}{
|
||||
{
|
||||
name: "upstream window header wins",
|
||||
body: grokInputTooLargeBody,
|
||||
upstreamWindow: "2000000",
|
||||
wantMessage: "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)",
|
||||
wantWindow: "2000000",
|
||||
},
|
||||
{
|
||||
name: "window from the stated limit",
|
||||
body: grokInputTooLargeBody,
|
||||
wantMessage: "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)",
|
||||
wantWindow: "500000",
|
||||
},
|
||||
{
|
||||
name: "invalid upstream header falls back to the stated limit",
|
||||
body: grokInputTooLargeBody,
|
||||
upstreamWindow: "0",
|
||||
wantMessage: "The prompt is too long for this model's context window (612345 tokens > 500000 tokens)",
|
||||
wantWindow: "500000",
|
||||
},
|
||||
{
|
||||
name: "no window anywhere keeps only the code",
|
||||
body: grokInputTooLargeNoCountsBody,
|
||||
wantMessage: "The prompt is too long for this model's context window",
|
||||
wantWindow: "",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := &grokQuotaAccountRepo{}
|
||||
svc := &OpenAIGatewayService{accountRepo: repo}
|
||||
account := &Account{ID: 8242, Platform: PlatformGrok, Type: AccountTypeOAuth}
|
||||
c, rec := newOpenAIUpstreamErrorTestContext(t)
|
||||
resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, tc.body)
|
||||
if tc.upstreamWindow != "" {
|
||||
resp.Header.Set("x-grok-context-window", tc.upstreamWindow)
|
||||
}
|
||||
|
||||
_, err := svc.handleErrorResponse(context.Background(), resp, c, account, nil, "grok-4.6")
|
||||
|
||||
require.Error(t, err)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
require.Contains(t, rec.Header().Get("Content-Type"), "application/json")
|
||||
body := rec.Body.Bytes()
|
||||
require.Equal(t, "invalid_request_error", gjson.GetBytes(body, "error.type").String())
|
||||
require.Equal(t, "context_length_exceeded", gjson.GetBytes(body, "error.code").String())
|
||||
require.Equal(t, tc.wantMessage, gjson.GetBytes(body, "error.message").String())
|
||||
require.Equal(t, tc.wantWindow, rec.Header().Get("x-grok-context-window"))
|
||||
require.Zero(t, repo.tempUnschedCalls)
|
||||
require.Zero(t, repo.rateLimitedCalls)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokResponsesGenericInvalidArgumentKeepsShape(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := &OpenAIGatewayService{accountRepo: &grokQuotaAccountRepo{}}
|
||||
account := &Account{ID: 8243, Platform: PlatformGrok, Type: AccountTypeOAuth}
|
||||
c, rec := newOpenAIUpstreamErrorTestContext(t)
|
||||
resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, grokGenericInvalidArgumentBody)
|
||||
resp.Header.Set("x-grok-context-window", "500000")
|
||||
|
||||
_, err := svc.handleErrorResponse(context.Background(), resp, c, account, nil, "grok-4.6")
|
||||
require.Error(t, err)
|
||||
|
||||
// 与没有这条识别时一样:通用写法、不补上下文窗口头。
|
||||
want := httptest.NewRecorder()
|
||||
wantCtx, _ := gin.CreateTestContext(want)
|
||||
writeOpenAIUpstreamClientError(wantCtx, http.StatusBadRequest, []byte(grokGenericInvalidArgumentBody), "")
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
require.JSONEq(t, want.Body.String(), rec.Body.String())
|
||||
require.NotEqual(t, "context_length_exceeded", gjson.Get(rec.Body.String(), "error.code").String())
|
||||
require.Empty(t, rec.Header().Get("x-grok-context-window"))
|
||||
}
|
||||
|
||||
func TestOpenAIAccountInputTooLargeTagIsNotRemapped(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{}
|
||||
c, rec := newOpenAIUpstreamErrorTestContext(t)
|
||||
resp := newOpenAIUpstreamErrorResponse(http.StatusBadRequest, grokInputTooLargeBody)
|
||||
|
||||
_, err := svc.handleErrorResponse(context.Background(), resp, c, newOpenAIUpstreamErrorTestAccount(), nil, "gpt-5")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
require.NotEqual(t, "context_length_exceeded", gjson.Get(rec.Body.String(), "error.code").String())
|
||||
require.Empty(t, rec.Header().Get("x-grok-context-window"))
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -336,3 +338,70 @@ func (s *OpenAIGatewayService) applyGrokForbiddenPolicy(ctx context.Context, acc
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// grokContextLengthExceededMarker is the reason tag xAI puts in front of its
|
||||
// context-window refusal, e.g. HTTP 400
|
||||
// {"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window (612345 tokens > 500000 tokens)"}.
|
||||
// invalid-argument alone is shared by every malformed request, so only this
|
||||
// explicit tag is trusted.
|
||||
const grokContextLengthExceededMarker = "[input_too_large]"
|
||||
|
||||
const grokContextLengthExceededMessage = "The prompt is too long for this model's context window"
|
||||
|
||||
// grokContextWindowHeader carries the model's context window in tokens. Grok
|
||||
// Build compacts and resends an oversized turn only when this header comes
|
||||
// with the context_length_exceeded error.
|
||||
const grokContextWindowHeader = "X-Grok-Context-Window"
|
||||
|
||||
var reGrokContextWindowTokens = regexp.MustCompile(`\((\d+)\s+tokens\s*>\s*(\d+)\s+tokens\)`)
|
||||
|
||||
// grokContextLengthExceeded describes an explicit xAI context-window refusal.
|
||||
// Window is the limit stated in the upstream message, or 0 when the message
|
||||
// does not state it.
|
||||
type grokContextLengthExceeded struct {
|
||||
Message string
|
||||
Window int64
|
||||
}
|
||||
|
||||
// detectGrokContextLengthExceeded reports whether an xAI 400 is the explicit
|
||||
// context-window refusal. Token counts are copied only when the same upstream
|
||||
// message states them; otherwise the refusal is still reported with a message
|
||||
// that carries no numbers.
|
||||
func detectGrokContextLengthExceeded(statusCode int, body []byte) (grokContextLengthExceeded, bool) {
|
||||
if statusCode != http.StatusBadRequest || len(body) == 0 {
|
||||
return grokContextLengthExceeded{}, false
|
||||
}
|
||||
for _, candidate := range grokStructuredErrorMessageCandidates(body) {
|
||||
if !strings.Contains(strings.ToLower(candidate), grokContextLengthExceededMarker) {
|
||||
continue
|
||||
}
|
||||
result := grokContextLengthExceeded{Message: grokContextLengthExceededMessage}
|
||||
if m := reGrokContextWindowTokens.FindStringSubmatch(candidate); len(m) == 3 {
|
||||
actual, errA := strconv.ParseInt(m[1], 10, 64)
|
||||
limit, errB := strconv.ParseInt(m[2], 10, 64)
|
||||
if errA == nil && errB == nil && limit > 0 {
|
||||
result.Message += " (" + strconv.FormatInt(actual, 10) + " tokens > " + strconv.FormatInt(limit, 10) + " tokens)"
|
||||
result.Window = limit
|
||||
}
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
return grokContextLengthExceeded{}, false
|
||||
}
|
||||
|
||||
// grokContextWindowForClient prefers the upstream's own context-window header
|
||||
// and falls back to the limit stated in the error. It returns 0 when neither
|
||||
// is a positive integer, in which case no header is sent.
|
||||
func grokContextWindowForClient(upstreamHeaders http.Header, statedWindow int64) int64 {
|
||||
if upstreamHeaders != nil {
|
||||
if raw := strings.TrimSpace(upstreamHeaders.Get(grokContextWindowHeader)); raw != "" {
|
||||
if window, err := strconv.ParseInt(raw, 10, 64); err == nil && window > 0 {
|
||||
return window
|
||||
}
|
||||
}
|
||||
}
|
||||
if statedWindow > 0 {
|
||||
return statedWindow
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -745,6 +746,19 @@ func (s *OpenAIGatewayService) handleErrorResponse(
|
||||
// 回真实状态码 + invalid_request_error + 真实 message;/v1/images 还额外透传
|
||||
// code/param。原生 Responses 是唯一漏掉的一条。
|
||||
if isOpenAIDeterministicClientError(resp.StatusCode) {
|
||||
// xAI reports an oversized prompt as a flat invalid-argument body that the
|
||||
// shared extractor cannot read; keep the explicit reason as the OpenAI code
|
||||
// and the context window Grok Build needs to compact and resend.
|
||||
if account != nil && account.Platform == PlatformGrok {
|
||||
if exceeded, ok := detectGrokContextLengthExceeded(resp.StatusCode, body); ok {
|
||||
setOpsUpstreamError(c, resp.StatusCode, exceeded.Message, upstreamDetail)
|
||||
if window := grokContextWindowForClient(resp.Header, exceeded.Window); window > 0 {
|
||||
c.Header(grokContextWindowHeader, strconv.FormatInt(window, 10))
|
||||
}
|
||||
writeOpenAIContextLengthExceededError(c, resp.StatusCode, exceeded.Message)
|
||||
return nil, fmt.Errorf("upstream error: %d context_length_exceeded message=%s", resp.StatusCode, exceeded.Message)
|
||||
}
|
||||
}
|
||||
writeOpenAIUpstreamClientError(c, resp.StatusCode, body, upstreamMsg)
|
||||
if upstreamMsg == "" {
|
||||
return nil, fmt.Errorf("upstream error: %d", resp.StatusCode)
|
||||
|
||||
@@ -36,6 +36,19 @@ func isOpenAIDeterministicClientError(statusCode int) bool {
|
||||
// upstreamMsg 由调用方传入,调用方已做过 sanitizeUpstreamErrorMessage 与
|
||||
// redactAgentIdentitySensitiveBody;这里不重复清洗,也不回落读取原始 body 的
|
||||
// message,避免绕开那两道脱敏。
|
||||
// writeOpenAIContextLengthExceededError writes the OpenAI Responses shape for a
|
||||
// prompt that does not fit the model's context window, so clients can tell it
|
||||
// apart from other rejected requests (for example to compact and resend).
|
||||
func writeOpenAIContextLengthExceededError(c *gin.Context, statusCode int, message string) {
|
||||
c.JSON(statusCode, gin.H{
|
||||
"error": gin.H{
|
||||
"type": "invalid_request_error",
|
||||
"code": "context_length_exceeded",
|
||||
"message": message,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func writeOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte, upstreamMsg string) {
|
||||
errorPayload := gin.H{"type": openAIUpstreamClientErrorFallbackType}
|
||||
if errType := strings.TrimSpace(gjson.GetBytes(body, "error.type").String()); errType != "" {
|
||||
|
||||
Reference in new issue
Block a user