mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
xAI rejects an oversized prompt with 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)"}.
The shared extractor cannot read this flat body, so Responses clients got the
generic "Upstream rejected the request" and could not tell an oversized
prompt from any other rejected request.
For Grok accounts, a 400 that carries the explicit [input_too_large] tag is now
returned as 400 {"error":{"type":"invalid_request_error",
"code":"context_length_exceeded","message":...}}. Token counts are copied only
when the upstream message states them. X-Grok-Context-Window is forwarded from
the upstream when it is a positive integer, otherwise taken from the stated
limit, otherwise omitted. Other 400s keep their existing shape, and the error
still does not fail over or cool down the account.
408 lines
13 KiB
Go
408 lines
13 KiB
Go
package service
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"net/http"
|
||
"regexp"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/tidwall/gjson"
|
||
)
|
||
|
||
// isGrokContentPolicyRejection identifies request-scoped safety refusals from
|
||
// xAI. These failures are caused by the prompt or media, so retrying another
|
||
// OAuth account cannot change the outcome and would incorrectly drain a pool.
|
||
// Keep this matcher deliberately narrow: account entitlement and suspension
|
||
// messages may mention policy but must retain the normal account failover path.
|
||
func isGrokContentPolicyRejection(statusCode int, responseBody []byte) bool {
|
||
if statusCode != http.StatusForbidden || len(responseBody) == 0 {
|
||
return false
|
||
}
|
||
if grokAccountAccessMessage(string(responseBody)) {
|
||
return false
|
||
}
|
||
|
||
var payload any
|
||
if json.Unmarshal(responseBody, &payload) == nil {
|
||
if grokStructuredAccountAccessMarker(payload) {
|
||
return false
|
||
}
|
||
if grokStructuredContentPolicyMarker(payload) {
|
||
return true
|
||
}
|
||
}
|
||
|
||
return grokContentPolicyMessage(string(responseBody))
|
||
}
|
||
|
||
func grokStructuredAccountAccessMarker(value any) bool {
|
||
switch node := value.(type) {
|
||
case map[string]any:
|
||
for key, child := range node {
|
||
normalizedKey := normalizeGrokErrorMarker(key)
|
||
switch normalizedKey {
|
||
case "code", "error_code", "type", "category", "reason":
|
||
if marker, ok := child.(string); ok && isGrokAccountAccessCode(marker) {
|
||
return true
|
||
}
|
||
}
|
||
if grokStructuredAccountAccessMarker(child) {
|
||
return true
|
||
}
|
||
}
|
||
case []any:
|
||
for _, child := range node {
|
||
if grokStructuredAccountAccessMarker(child) {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func grokStructuredContentPolicyMarker(value any) bool {
|
||
switch node := value.(type) {
|
||
case map[string]any:
|
||
for key, child := range node {
|
||
normalizedKey := normalizeGrokErrorMarker(key)
|
||
switch normalizedKey {
|
||
case "code", "error_code", "type", "category", "reason":
|
||
if marker, ok := child.(string); ok && isGrokContentPolicyCode(marker) {
|
||
return true
|
||
}
|
||
}
|
||
if grokStructuredContentPolicyMarker(child) {
|
||
return true
|
||
}
|
||
}
|
||
case []any:
|
||
for _, child := range node {
|
||
if grokStructuredContentPolicyMarker(child) {
|
||
return true
|
||
}
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func normalizeGrokErrorMarker(value string) string {
|
||
value = strings.ToLower(strings.TrimSpace(value))
|
||
value = strings.ReplaceAll(value, "-", "_")
|
||
value = strings.ReplaceAll(value, " ", "_")
|
||
return value
|
||
}
|
||
|
||
func isGrokContentPolicyCode(value string) bool {
|
||
switch normalizeGrokErrorMarker(value) {
|
||
case "content_filter",
|
||
"content_policy",
|
||
"content_policy_violation",
|
||
"content_moderation",
|
||
"cyber_policy",
|
||
"new_sensitive":
|
||
return true
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
|
||
func isGrokAccountAccessCode(value string) bool {
|
||
switch normalizeGrokErrorMarker(value) {
|
||
case "account_suspended",
|
||
"account_disabled",
|
||
"user_suspended",
|
||
"user_disabled",
|
||
"subscription_required",
|
||
"entitlement_required",
|
||
"not_entitled",
|
||
"plan_required":
|
||
// permission-denied is omitted: xAI reuses it for both entitlement
|
||
// refusals and request-scoped safety blocks, so the message decides.
|
||
return true
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
|
||
func grokAccountAccessMessage(value string) bool {
|
||
lower := strings.ToLower(strings.TrimSpace(value))
|
||
for _, phrase := range []string{
|
||
"account suspended",
|
||
"account has been suspended",
|
||
"account disabled",
|
||
"account has been disabled",
|
||
"user suspended",
|
||
"user has been suspended",
|
||
"subscription required",
|
||
"entitlement required",
|
||
"not entitled",
|
||
} {
|
||
if strings.Contains(lower, phrase) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func grokContentPolicyMessage(value string) bool {
|
||
lower := strings.ToLower(strings.TrimSpace(value))
|
||
if lower == "" {
|
||
return false
|
||
}
|
||
|
||
// xAI's media safety responses use these exact phrases. They are specific
|
||
// enough not to classify a generic account-policy or entitlement message.
|
||
for _, phrase := range []string{
|
||
"the moderation feature is not available",
|
||
"image is sensitive",
|
||
"text is sensitive",
|
||
"prohibited content",
|
||
"forbidden content",
|
||
"content policy violation",
|
||
"content policy rejection",
|
||
"content policy rejected",
|
||
"content moderation rejection",
|
||
"content moderation rejected",
|
||
"content moderation blocked",
|
||
"request blocked by content moderation",
|
||
"request rejected by content moderation",
|
||
"request blocked by policy",
|
||
"request rejected by policy",
|
||
"request violates policy",
|
||
"prompt violates content policy",
|
||
"prompt violates policy",
|
||
"input violates content policy",
|
||
"input violates policy",
|
||
"violates usage guidelines",
|
||
} {
|
||
if strings.Contains(lower, phrase) {
|
||
return true
|
||
}
|
||
}
|
||
|
||
return false
|
||
}
|
||
|
||
func grokContentPolicyClientMessage(responseBody []byte) string {
|
||
message := sanitizeUpstreamErrorMessage(strings.TrimSpace(grokUpstreamErrorMessage(responseBody)))
|
||
if message == "" {
|
||
return "Request blocked by upstream content policy"
|
||
}
|
||
return message
|
||
}
|
||
|
||
// grokUpstreamErrorMessage extends the shared extractor with xAI's flat error
|
||
// body {"code":"...","error":"..."}. It is Grok-only on purpose: the shared
|
||
// extractUpstreamErrorMessage feeds failover, model-not-found and account
|
||
// disable decisions on every platform and must not drift with xAI's format.
|
||
// Non-string error values are never surfaced so unknown objects cannot leak.
|
||
func grokUpstreamErrorMessage(body []byte) string {
|
||
if message := extractUpstreamErrorMessage(body); strings.TrimSpace(message) != "" {
|
||
return message
|
||
}
|
||
if errValue := gjson.GetBytes(body, "error"); errValue.Type == gjson.String {
|
||
return errValue.String()
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// grokUpstreamErrorCode extends the shared extractor with xAI's top-level code.
|
||
// Nested error.code keeps priority. Like grokUpstreamErrorMessage it stays
|
||
// Grok-only: a top-level code would otherwise short-circuit the OpenAI-
|
||
// compatible model-not-found failover for bodies such as
|
||
// {"object":"error","message":"model not found","code":400}.
|
||
func grokUpstreamErrorCode(body []byte) string {
|
||
if code := strings.TrimSpace(extractUpstreamErrorCode(body)); code != "" {
|
||
return code
|
||
}
|
||
if code := gjson.GetBytes(body, "code"); code.Type == gjson.String || code.Type == gjson.Number {
|
||
return strings.TrimSpace(code.String())
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// shouldFailoverGrokUpstreamError is the body-aware counterpart of the
|
||
// status-only failover helper. Grok content refusals must stay on the current
|
||
// account and be returned to the caller instead of consuming the account pool.
|
||
// Free-usage / empty-output / billing bodies also failover even when the HTTP
|
||
// status alone would not (e.g. 400 with free-usage-exhausted).
|
||
func (s *OpenAIGatewayService) shouldFailoverGrokUpstreamError(statusCode int, responseBody []byte) bool {
|
||
if isGrokContentPolicyRejection(statusCode, responseBody) {
|
||
return false
|
||
}
|
||
// A 422 emitted by xAI's ModelInput decoder is account/runtime compatibility,
|
||
// not quota exhaustion. Another account may run a different upstream build,
|
||
// so fail over without applying an account cooldown.
|
||
if isGrokDecoderCompatibilityError(statusCode, responseBody) {
|
||
return true
|
||
}
|
||
decision := classifyGrokUpstreamFailure(statusCode, responseBody, "")
|
||
switch decision.Class {
|
||
case GrokFailureFreeUsage, GrokFailureEmptyUpstream, GrokFailureBilling, GrokFailureModelCapacity, GrokFailureCompatibility:
|
||
return decision.ShouldFailover
|
||
}
|
||
return s.shouldFailoverUpstreamError(statusCode)
|
||
}
|
||
|
||
func isGrokDecoderCompatibilityError(statusCode int, responseBody []byte) bool {
|
||
if statusCode != http.StatusUnprocessableEntity || len(responseBody) == 0 {
|
||
return false
|
||
}
|
||
for _, candidate := range grokStructuredErrorMessageCandidates(responseBody) {
|
||
message := strings.ToLower(candidate)
|
||
decoderSignal := strings.Contains(message, "untagged enum") ||
|
||
strings.Contains(message, "decode") ||
|
||
strings.Contains(message, "deserialize") ||
|
||
strings.Contains(message, "deserializ") ||
|
||
strings.Contains(message, "decoder")
|
||
inputSignal := strings.Contains(message, "modelinput") ||
|
||
strings.Contains(message, "model input") ||
|
||
strings.Contains(message, "input[") ||
|
||
strings.Contains(message, "input.")
|
||
messageContentSignal := (strings.Contains(message, "messages[") ||
|
||
strings.Contains(message, "messages.")) &&
|
||
strings.Contains(message, "content") &&
|
||
strings.Contains(message, "did not match any variant")
|
||
if decoderSignal && (inputSignal || messageContentSignal) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func grokStructuredErrorMessageCandidates(body []byte) []string {
|
||
candidates := make([]string, 0, 6)
|
||
appendCandidate := func(result gjson.Result) {
|
||
if !result.Exists() {
|
||
return
|
||
}
|
||
value := strings.TrimSpace(result.String())
|
||
if value != "" {
|
||
candidates = append(candidates, value)
|
||
}
|
||
}
|
||
appendCandidate(gjson.GetBytes(body, "error.message"))
|
||
appendCandidate(gjson.GetBytes(body, "error.error"))
|
||
errorNode := gjson.GetBytes(body, "error")
|
||
if errorNode.Type == gjson.String {
|
||
appendCandidate(errorNode)
|
||
}
|
||
appendCandidate(gjson.GetBytes(body, "message"))
|
||
appendCandidate(gjson.GetBytes(body, "detail"))
|
||
if !json.Valid(body) {
|
||
if plaintext := strings.TrimSpace(string(body)); plaintext != "" {
|
||
candidates = append(candidates, plaintext)
|
||
}
|
||
}
|
||
return candidates
|
||
}
|
||
|
||
// applyGrokForbiddenPolicy applies an administrator's existing temporary
|
||
// unschedulable rules to a non-content 403. It reports true only when a rule
|
||
// matched; unmatched responses retain the legacy entitlement cooldown.
|
||
func (s *OpenAIGatewayService) applyGrokForbiddenPolicy(ctx context.Context, account *Account, responseBody []byte) bool {
|
||
if account == nil || !account.IsTempUnschedulableEnabled() {
|
||
return false
|
||
}
|
||
|
||
matches := matchTempUnschedulableRules(account, http.StatusForbidden, responseBody)
|
||
if len(matches) == 0 {
|
||
return false
|
||
}
|
||
|
||
match := matches[0]
|
||
// Reuse the central policy implementation when it has a repository. This
|
||
// preserves the existing reason/cache format and avoids duplicating writes.
|
||
if s != nil && s.rateLimitService != nil && s.rateLimitService.accountRepo != nil {
|
||
stateCtx, cancel := openAIAccountStateContext(ctx)
|
||
handled := s.rateLimitService.tryTempUnschedulable(
|
||
stateCtx,
|
||
account,
|
||
http.StatusForbidden,
|
||
responseBody,
|
||
)
|
||
cancel()
|
||
if handled {
|
||
return true
|
||
}
|
||
}
|
||
|
||
// A partially constructed service (for example a unit-test gateway) still
|
||
// honors the configured duration instead of silently falling back to 30m.
|
||
cooldown := time.Duration(match.rule.DurationMinutes) * time.Minute
|
||
if cooldown > 0 {
|
||
s.tempUnscheduleGrok(ctx, account, cooldown, "grok configured forbidden rule")
|
||
}
|
||
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
|
||
}
|