mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
perf(openai): 合并大请求体入口与转发链路的重复扫描和校验
This commit is contained in:
1 parent
6744f02164
commit
2c922cf496
15 files changed
+1348
-117
No files matched your search
@@ -116,6 +116,17 @@ func bindRequestedReasoningEffort(c *gin.Context, body []byte, model string) {
|
||||
c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort))
|
||||
}
|
||||
|
||||
func bindRequestedReasoningEffortWithFields(c *gin.Context, body []byte, model, reasoningEffort, reasoningEffortTop, outputConfigEffort string) {
|
||||
if c == nil || c.Request == nil {
|
||||
return
|
||||
}
|
||||
effort := service.CanonicalRequestedReasoningEffortWithFields(body, reasoningEffort, reasoningEffortTop, outputConfigEffort, model)
|
||||
if effort == nil {
|
||||
return
|
||||
}
|
||||
c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort))
|
||||
}
|
||||
|
||||
func stampOpenAIRequestedReasoningEffort(result *service.OpenAIForwardResult, c *gin.Context) {
|
||||
if result == nil || result.RequestedReasoningEffort != nil {
|
||||
return
|
||||
@@ -142,6 +153,20 @@ func applyOpenAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.
|
||||
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
|
||||
}
|
||||
|
||||
func applyOpenAIReasoningEffortPolicyForRequestWithFields(
|
||||
c *gin.Context,
|
||||
apiKey *service.APIKey,
|
||||
body []byte,
|
||||
model, reasoningEffort, reasoningEffortTop, outputConfigEffort string,
|
||||
) ([]byte, bool, error) {
|
||||
bindRequestedReasoningEffortWithFields(c, body, strings.TrimSpace(model), reasoningEffort, reasoningEffortTop, outputConfigEffort)
|
||||
maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
|
||||
if !ok {
|
||||
return body, false, nil
|
||||
}
|
||||
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
|
||||
}
|
||||
|
||||
func respondOpenAIReasoningEffortPolicyError(c *gin.Context, err error, write func(*gin.Context, int, string, string)) {
|
||||
if c == nil || err == nil || write == nil {
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -13,11 +14,74 @@ type inflightReservationEstimator interface {
|
||||
EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, req service.InflightEstimateRequest) (float64, bool)
|
||||
}
|
||||
|
||||
// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini)。
|
||||
// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini),
|
||||
// 单遍零拷贝遍历顶层键,保持 max_tokens → max_completion_tokens → max_output_tokens → generationConfig.maxOutputTokens → generation_config.max_output_tokens 优先级。
|
||||
func requestMaxOutputTokens(body []byte) int {
|
||||
for _, path := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens", "generationConfig.maxOutputTokens", "generation_config.max_output_tokens"} {
|
||||
if v := gjson.GetBytes(body, path); v.Exists() && v.Type == gjson.Number && v.Int() > 0 {
|
||||
return int(v.Int())
|
||||
if len(body) == 0 {
|
||||
return 0
|
||||
}
|
||||
const (
|
||||
maxTokensBit uint8 = 1 << iota
|
||||
maxCompletionTokensBit
|
||||
maxOutputTokensBit
|
||||
genConfigCamelBit
|
||||
genConfigSnakeBit
|
||||
allMaxTokenBits = maxTokensBit | maxCompletionTokensBit | maxOutputTokensBit | genConfigCamelBit | genConfigSnakeBit
|
||||
)
|
||||
var seen uint8
|
||||
var vals [5]int
|
||||
root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body)))
|
||||
if !root.IsObject() {
|
||||
return 0
|
||||
}
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "max_tokens":
|
||||
if seen&maxTokensBit == 0 {
|
||||
seen |= maxTokensBit
|
||||
if value.Type == gjson.Number && value.Int() > 0 {
|
||||
vals[0] = int(value.Int())
|
||||
return false
|
||||
}
|
||||
}
|
||||
case "max_completion_tokens":
|
||||
if seen&maxCompletionTokensBit == 0 {
|
||||
seen |= maxCompletionTokensBit
|
||||
if value.Type == gjson.Number && value.Int() > 0 {
|
||||
vals[1] = int(value.Int())
|
||||
}
|
||||
}
|
||||
case "max_output_tokens":
|
||||
if seen&maxOutputTokensBit == 0 {
|
||||
seen |= maxOutputTokensBit
|
||||
if value.Type == gjson.Number && value.Int() > 0 {
|
||||
vals[2] = int(value.Int())
|
||||
}
|
||||
}
|
||||
case "generationConfig":
|
||||
if seen&genConfigCamelBit == 0 {
|
||||
if v := value.Get("maxOutputTokens"); v.Exists() {
|
||||
seen |= genConfigCamelBit
|
||||
if v.Type == gjson.Number && v.Int() > 0 {
|
||||
vals[3] = int(v.Int())
|
||||
}
|
||||
}
|
||||
}
|
||||
case "generation_config":
|
||||
if seen&genConfigSnakeBit == 0 {
|
||||
if v := value.Get("max_output_tokens"); v.Exists() {
|
||||
seen |= genConfigSnakeBit
|
||||
if v.Type == gjson.Number && v.Int() > 0 {
|
||||
vals[4] = int(v.Int())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen != allMaxTokenBits
|
||||
})
|
||||
for _, v := range vals {
|
||||
if v > 0 {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return 0
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
@@ -471,55 +472,67 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
|
||||
return
|
||||
}
|
||||
service.MarkOpenAIRequestBodyJSONValidated(c)
|
||||
|
||||
// 使用 gjson 只读提取字段做校验,避免完整 Unmarshal
|
||||
modelResult := gjson.GetBytes(body, "model")
|
||||
if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" {
|
||||
// 单次只读扫描顶层校验与路由字段,避免对大请求体重复调用 gjson.GetBytes。
|
||||
ingressFields := parseOpenAIResponsesIngressFields(body)
|
||||
if !ingressFields.ModelValid {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
|
||||
return
|
||||
}
|
||||
reqModel := modelResult.String()
|
||||
reqModel := ingressFields.Model
|
||||
ensureCompositeTargetPlatform(c, apiKey, reqModel)
|
||||
if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
|
||||
return
|
||||
}
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
|
||||
ingressBodyChanged := false
|
||||
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequestWithFields(
|
||||
c, apiKey, body, reqModel,
|
||||
ingressFields.ReasoningEffort, ingressFields.ReasoningEffortTop, ingressFields.OutputConfigEffort,
|
||||
); err != nil {
|
||||
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
|
||||
return
|
||||
} else if changed {
|
||||
body = cappedBody
|
||||
ingressBodyChanged = true
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
|
||||
body = normalizedBody
|
||||
ingressBodyChanged = true
|
||||
reqLog.Info("openai.codex_untrusted_context_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed {
|
||||
body = normalizedBody
|
||||
ingressBodyChanged = true
|
||||
reqLog.Info("openai.codex_automation_bootstrap_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
if normalizedBody, changed := normalizeCodexDelegationBootstrap(body); changed {
|
||||
body = normalizedBody
|
||||
ingressBodyChanged = true
|
||||
reqLog.Info("openai.codex_delegation_bootstrap_normalized",
|
||||
zap.String("normalization", "call_output_to_user_message"),
|
||||
)
|
||||
}
|
||||
if ingressBodyChanged {
|
||||
ingressFields = parseOpenAIResponsesIngressFields(body)
|
||||
}
|
||||
|
||||
reqStream, ok := parseOpenAICompatibleStream(body)
|
||||
if !ok {
|
||||
if !ingressFields.StreamValid {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
|
||||
return
|
||||
}
|
||||
if _, err := service.ValidateOpenAIServiceTierField(body); err != nil {
|
||||
reqStream := ingressFields.Stream
|
||||
if _, err := service.ValidateOpenAIServiceTierResult(ingressFields.ServiceTier); err != nil {
|
||||
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error())
|
||||
return
|
||||
}
|
||||
reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream))
|
||||
previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String())
|
||||
previousResponseID := ingressFields.PreviousResponseID
|
||||
if previousResponseID != "" {
|
||||
previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID)
|
||||
reqLog = reqLog.With(
|
||||
@@ -564,10 +577,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 IsExplicitImageGenerationIntent 排除被动 image_gen namespace 声明。
|
||||
// 使用 IsExplicitImageGenerationIntentValidated 排除被动 image_gen namespace 声明。
|
||||
// Codex 在所有请求中被动声明 image_gen namespace,宽泛检测会导致禁了生图的
|
||||
// 分组中所有 Codex 请求被 403(#4447),并误占生图并发槽位。
|
||||
imageIntent := service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, body)
|
||||
imageIntent := service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body)
|
||||
if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) {
|
||||
h.errorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage())
|
||||
return
|
||||
@@ -633,7 +646,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。
|
||||
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body))
|
||||
var inflightEstimate service.InflightEstimateRequest
|
||||
if h.billingCacheService != nil && h.billingCacheService.InflightReservationEnabled() {
|
||||
inflightEstimate = tokenInflightEstimate(reqModel, body)
|
||||
}
|
||||
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, inflightEstimate)
|
||||
if err != nil {
|
||||
reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err))
|
||||
status, code, message, retryAfter := billingErrorDetails(err)
|
||||
@@ -686,6 +703,18 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
|
||||
c.Request = c.Request.WithContext(pricingCtx)
|
||||
|
||||
var (
|
||||
requestPayloadHashComputed bool
|
||||
requestPayloadHashValue string
|
||||
)
|
||||
getRequestPayloadHash := func() string {
|
||||
if !requestPayloadHashComputed {
|
||||
requestPayloadHashValue = service.HashUsageRequestPayload(body)
|
||||
requestPayloadHashComputed = true
|
||||
}
|
||||
return requestPayloadHashValue
|
||||
}
|
||||
|
||||
for {
|
||||
// Streaming Forward intentionally detaches the upstream request so usage can
|
||||
// be drained after a disconnect. Re-check the client context before every
|
||||
@@ -832,11 +861,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
if h.handleForwardRequestBodyMemoryOverload(c, err, streamStarted) {
|
||||
return
|
||||
}
|
||||
var cyberBlockBodyHTTP []byte
|
||||
if service.GetOpsCyberPolicy(c) != nil {
|
||||
cyberBlockBodyHTTP = sessionHashBody
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, sessionHashBody, clientRequestedUsageFields(c, channelMapping, reqModel, ""), getRequestPayloadHash())
|
||||
}
|
||||
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body))
|
||||
forwardDurationMs := time.Since(forwardStart).Milliseconds()
|
||||
upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
|
||||
responseLatencyMs := forwardDurationMs
|
||||
@@ -856,7 +883,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
stampOpenAIRequestedReasoningEffort(res, c)
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
clientIP := ip.GetClientIP(c)
|
||||
requestPayloadHash := service.HashUsageRequestPayload(body)
|
||||
requestPayloadHash := getRequestPayloadHash()
|
||||
inboundEndpoint := GetInboundEndpoint(c)
|
||||
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res)
|
||||
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
|
||||
@@ -1699,7 +1726,99 @@ func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, stre
|
||||
return true
|
||||
}
|
||||
|
||||
type openAIResponsesIngressFields struct {
|
||||
Model string
|
||||
ModelValid bool
|
||||
Stream bool
|
||||
StreamValid bool
|
||||
ServiceTier gjson.Result
|
||||
PreviousResponseID string
|
||||
ReasoningEffort string
|
||||
ReasoningEffortTop string
|
||||
OutputConfigEffort string
|
||||
}
|
||||
|
||||
// parseOpenAIResponsesIngressFields 单次只读扫描 /v1/responses 顶层入口字段,
|
||||
// 提取出的字符串全部 clone 断开对原始请求体的引用;ServiceTier 仅在本次同步校验期间使用。
|
||||
func parseOpenAIResponsesIngressFields(body []byte) openAIResponsesIngressFields {
|
||||
fields := openAIResponsesIngressFields{StreamValid: true}
|
||||
if len(body) == 0 {
|
||||
return fields
|
||||
}
|
||||
root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body)))
|
||||
if !root.IsObject() {
|
||||
return fields
|
||||
}
|
||||
const (
|
||||
seenModel uint8 = 1 << iota
|
||||
seenStream
|
||||
seenServiceTier
|
||||
seenPrevRespID
|
||||
seenReasoning
|
||||
seenReasoningTop
|
||||
seenOutputConfig
|
||||
seenAll = seenModel | seenStream | seenServiceTier | seenPrevRespID |
|
||||
seenReasoning | seenReasoningTop | seenOutputConfig
|
||||
)
|
||||
var seen uint8
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "model":
|
||||
if seen&seenModel == 0 {
|
||||
seen |= seenModel
|
||||
if value.Type == gjson.String && value.String() != "" {
|
||||
fields.ModelValid = true
|
||||
fields.Model = strings.Clone(value.String())
|
||||
}
|
||||
}
|
||||
case "stream":
|
||||
if seen&seenStream == 0 {
|
||||
seen |= seenStream
|
||||
if value.Type != gjson.True && value.Type != gjson.False {
|
||||
fields.StreamValid = false
|
||||
} else {
|
||||
fields.Stream = value.Bool()
|
||||
}
|
||||
}
|
||||
case "service_tier":
|
||||
if seen&seenServiceTier == 0 {
|
||||
seen |= seenServiceTier
|
||||
fields.ServiceTier = value
|
||||
}
|
||||
case "previous_response_id":
|
||||
if seen&seenPrevRespID == 0 {
|
||||
seen |= seenPrevRespID
|
||||
fields.PreviousResponseID = strings.Clone(strings.TrimSpace(value.String()))
|
||||
}
|
||||
case "reasoning":
|
||||
if seen&seenReasoning == 0 {
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
seen |= seenReasoning
|
||||
fields.ReasoningEffort = strings.Clone(strings.TrimSpace(effort.String()))
|
||||
}
|
||||
}
|
||||
case "reasoning_effort":
|
||||
if seen&seenReasoningTop == 0 {
|
||||
seen |= seenReasoningTop
|
||||
fields.ReasoningEffortTop = strings.Clone(strings.TrimSpace(value.String()))
|
||||
}
|
||||
case "output_config":
|
||||
if seen&seenOutputConfig == 0 {
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
seen |= seenOutputConfig
|
||||
fields.OutputConfigEffort = strings.Clone(strings.TrimSpace(effort.String()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen != seenAll
|
||||
})
|
||||
return fields
|
||||
}
|
||||
|
||||
func (h *OpenAIGatewayHandler) validateFunctionCallOutputRequest(c *gin.Context, body []byte, reqLog *zap.Logger) bool {
|
||||
if !bytes.Contains(body, []byte("function_call_output")) && !service.JSONMayEscapePlainASCII(body) {
|
||||
return true
|
||||
}
|
||||
if !gjson.GetBytes(body, `input.#(type=="function_call_output")`).Exists() {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseOpenAIResponsesIngressFields(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model": "gpt-6.2-astra",
|
||||
"stream": true,
|
||||
"service_tier": "fast",
|
||||
"previous_response_id": " resp_abc ",
|
||||
"reasoning": {"effort": " medium "},
|
||||
"reasoning_effort": " high ",
|
||||
"output_config": {"effort": " low "}
|
||||
}`)
|
||||
fields := parseOpenAIResponsesIngressFields(body)
|
||||
require.True(t, fields.ModelValid)
|
||||
require.Equal(t, "gpt-6.2-astra", fields.Model)
|
||||
require.True(t, fields.StreamValid)
|
||||
require.True(t, fields.Stream)
|
||||
require.Equal(t, "resp_abc", fields.PreviousResponseID)
|
||||
require.Equal(t, "medium", fields.ReasoningEffort)
|
||||
require.Equal(t, "high", fields.ReasoningEffortTop)
|
||||
require.Equal(t, "low", fields.OutputConfigEffort)
|
||||
|
||||
tier, err := service.ValidateOpenAIServiceTierResult(fields.ServiceTier)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "priority", tier)
|
||||
|
||||
// Invalid stream type.
|
||||
badStream := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","stream":"true"}`))
|
||||
require.True(t, badStream.ModelValid)
|
||||
require.False(t, badStream.StreamValid)
|
||||
|
||||
// Missing/non-string model.
|
||||
missingModel := parseOpenAIResponsesIngressFields([]byte(`{"stream":false}`))
|
||||
require.False(t, missingModel.ModelValid)
|
||||
require.True(t, missingModel.StreamValid)
|
||||
require.False(t, missingModel.Stream)
|
||||
|
||||
// Escaped keys.
|
||||
escaped := parseOpenAIResponsesIngressFields([]byte(`{"\u006dodel":"gpt-6.2-astra","\u0073tream":true,"service_tier":"invalid"}`))
|
||||
require.True(t, escaped.ModelValid)
|
||||
require.Equal(t, "gpt-6.2-astra", escaped.Model)
|
||||
require.True(t, escaped.StreamValid)
|
||||
require.True(t, escaped.Stream)
|
||||
_, err = service.ValidateOpenAIServiceTierResult(escaped.ServiceTier)
|
||||
require.Error(t, err)
|
||||
|
||||
// Non-object root.
|
||||
arr := parseOpenAIResponsesIngressFields([]byte(`[{"model":"x"}]`))
|
||||
require.False(t, arr.ModelValid)
|
||||
require.True(t, arr.StreamValid)
|
||||
|
||||
// Duplicate parent keys keep scanning until nested effort exists.
|
||||
dupParent := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","reasoning":{},"reasoning":{"effort":"xhigh"},"output_config":null,"output_config":{"effort":"low"}}`))
|
||||
require.Equal(t, "xhigh", dupParent.ReasoningEffort)
|
||||
require.Equal(t, "low", dupParent.OutputConfigEffort)
|
||||
}
|
||||
|
||||
func TestRequestMaxOutputTokensSinglePassPriority(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
{
|
||||
name: "max_tokens wins even when last",
|
||||
body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30,"max_completion_tokens":20,"max_tokens":10}`,
|
||||
want: 10,
|
||||
},
|
||||
{
|
||||
name: "max_completion_tokens wins when max_tokens absent or non-positive",
|
||||
body: `{"max_tokens":0,"max_output_tokens":30,"max_completion_tokens":20}`,
|
||||
want: 20,
|
||||
},
|
||||
{
|
||||
name: "max_output_tokens wins over generationConfig",
|
||||
body: `{"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30}`,
|
||||
want: 30,
|
||||
},
|
||||
{
|
||||
name: "generationConfig camelCase wins over snake_case",
|
||||
body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40}}`,
|
||||
want: 40,
|
||||
},
|
||||
{
|
||||
name: "generation_config snake_case fallback",
|
||||
body: `{"generation_config":{"max_output_tokens":50}}`,
|
||||
want: 50,
|
||||
},
|
||||
{
|
||||
name: "absent or non-object returns zero",
|
||||
body: `[{"max_tokens":10}]`,
|
||||
want: 0,
|
||||
},
|
||||
{
|
||||
name: "duplicate parent keys keep scanning for nested maxOutputTokens",
|
||||
body: `{"generationConfig":null,"generationConfig":{"maxOutputTokens":40},"generation_config":{"max_output_tokens":50}}`,
|
||||
want: 40,
|
||||
},
|
||||
{
|
||||
name: "duplicate snake_case parent keys keep scanning for nested max_output_tokens",
|
||||
body: `{"generation_config":{},"generation_config":{"max_output_tokens":55}}`,
|
||||
want: 55,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.want, requestMaxOutputTokens([]byte(tc.body)))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,12 @@ func IsExplicitImageGenerationIntent(endpoint string, requestedModel string, bod
|
||||
return openAIImageGenerationIntent(endpoint, requestedModel, body, true, true)
|
||||
}
|
||||
|
||||
// IsExplicitImageGenerationIntentValidated 与 IsExplicitImageGenerationIntent 语义一致,
|
||||
// 要求调用方已确认 body 是合法 JSON,跳过重复的 gjson.ValidBytes 全量校验。
|
||||
func IsExplicitImageGenerationIntentValidated(endpoint string, requestedModel string, body []byte) bool {
|
||||
return openAIImageGenerationIntent(endpoint, requestedModel, body, true, false)
|
||||
}
|
||||
|
||||
// IsImageGenerationIntentForPlatform applies platform-specific intent rules.
|
||||
//
|
||||
// Codex advertises the image_gen namespace on ordinary Responses requests so
|
||||
|
||||
@@ -26,6 +26,21 @@ func MarkOpenAINativeCompactionV2(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeCompactionTriggerInputOrderValidated 在调用方已确认 body 为合法 JSON 对象时
|
||||
// 跳过无 compaction_trigger 路径上的重复全量 gjson.ValidBytes 校验。
|
||||
func normalizeCompactionTriggerInputOrderValidated(body []byte, validated bool) ([]byte, bool, error) {
|
||||
if len(body) == 0 {
|
||||
return body, false, nil
|
||||
}
|
||||
if validated && !JSONMayEscapePlainASCII(body) && !bytes.Contains(body, compactionTriggerToken) {
|
||||
trimmed := bytes.TrimLeft(body, " \t\r\n")
|
||||
if len(trimmed) > 0 && trimmed[0] == '{' {
|
||||
return body, false, nil
|
||||
}
|
||||
}
|
||||
return NormalizeCompactionTriggerInputOrder(body)
|
||||
}
|
||||
|
||||
// NormalizeCompactionTriggerInputOrder keeps a single compaction trigger as
|
||||
// the final Responses input item, as required by the upstream v2 wire format.
|
||||
func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) {
|
||||
|
||||
@@ -44,10 +44,17 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
|
||||
restrictionResult := s.detectCodexClientRestriction(c, account, body)
|
||||
apiKeyID := getAPIKeyIDFromContext(c)
|
||||
wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account)
|
||||
// 仅允许 WS 入站请求走 WS 上游,避免出现 HTTP -> WS 协议混用。
|
||||
wsDecision = resolveOpenAIWSDecisionByClientTransport(wsDecision, GetOpenAIClientTransport(c))
|
||||
// 执行作用域必须取自客户端原始身份:后面的账号 namespace 改写与指纹收敛会改掉
|
||||
// 请求体里的 client_metadata / prompt_cache_key,用改写后的值取键会让不同会话
|
||||
// 落到同一个键,也会与 WS 接入路径按原始报文算出的键对不上。
|
||||
wsExecutionScope, _ := resolveOpenAIWSExecutionScope(c, body, apiKeyID)
|
||||
// 仅在真正走 WSv2 上游时解析作用域,避免 HTTP 路径反复扫描大请求体。
|
||||
var wsExecutionScope string
|
||||
if wsDecision.Transport == OpenAIUpstreamTransportResponsesWebsocketV2 {
|
||||
wsExecutionScope, _ = resolveOpenAIWSExecutionScope(c, body, apiKeyID)
|
||||
}
|
||||
logCodexCLIOnlyDetection(ctx, c, account, apiKeyID, restrictionResult, body)
|
||||
if restrictionResult.Enabled && !restrictionResult.Matched {
|
||||
MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied)
|
||||
@@ -67,7 +74,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
if normalized {
|
||||
body = normalizedBody
|
||||
}
|
||||
legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, body)
|
||||
bodyValidated := isOpenAIRequestBodyJSONValidated(c)
|
||||
legacyIngressBody, legacyIngressChanged, legacyIngressErr := normalizeOpenAIResponsesLegacyIngressValidated(s.cfg, body, bodyValidated)
|
||||
if legacyIngressErr != nil {
|
||||
return nil, legacyIngressErr
|
||||
}
|
||||
@@ -110,9 +118,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
body = liteBody
|
||||
}
|
||||
}
|
||||
wsDecision := s.getOpenAIWSProtocolResolver().Resolve(account)
|
||||
// 仅允许 WS 入站请求走 WS 上游,避免出现 HTTP -> WS 协议混用。
|
||||
wsDecision = resolveOpenAIWSDecisionByClientTransport(wsDecision, GetOpenAIClientTransport(c))
|
||||
passthroughEnabled := account.IsOpenAIPassthroughEnabled()
|
||||
compactPath := isOpenAIResponsesCompactPath(c)
|
||||
if shouldFlattenOpenAIResponsesNamespaces(account, wsDecision.Transport, passthroughEnabled, compactPath) {
|
||||
@@ -125,7 +130,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if shouldStripOpenAIResponsesInputNamespaces(account, wsDecision.Transport, passthroughEnabled) {
|
||||
if shouldStripOpenAIResponsesInputNamespaces(account, wsDecision.Transport, passthroughEnabled) &&
|
||||
bytes.Contains(body, openAIResponsesNamespaceFieldBytes) {
|
||||
keepToolCallNamespaces := shouldKeepOpenAIResponsesToolCallNamespaces(
|
||||
account, wsDecision.Transport, passthroughEnabled, compactPath, body,
|
||||
)
|
||||
@@ -152,8 +158,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
|
||||
originalBody := body
|
||||
rememberOpenCodeInboundBody(c, originalBody)
|
||||
requestView := newOpenAIRequestView(body)
|
||||
rememberOpenCodeInboundSessionFromView(c, requestView)
|
||||
reqModel, reqStream, promptCacheKey := requestView.Model, requestView.Stream, requestView.PromptCacheKey
|
||||
originalModel := reqModel
|
||||
|
||||
@@ -162,21 +168,30 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
|
||||
if account.IsOpenAIApiKey() {
|
||||
if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
} else if changed {
|
||||
body = normalized
|
||||
originalBody = normalized
|
||||
apiKeyBodyChanged := false
|
||||
if !responsesLite && requestView.HasParallelToolCalls {
|
||||
if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
} else if changed {
|
||||
body = normalized
|
||||
originalBody = normalized
|
||||
apiKeyBodyChanged = true
|
||||
}
|
||||
}
|
||||
if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, isOpenAIResponsesCompactPath(c)); normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
} else if changed {
|
||||
body = normalized
|
||||
originalBody = normalized
|
||||
if compactPath || requestView.StoreIsFalse {
|
||||
if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, compactPath); normalizeErr != nil {
|
||||
return nil, normalizeErr
|
||||
} else if changed {
|
||||
body = normalized
|
||||
originalBody = normalized
|
||||
apiKeyBodyChanged = true
|
||||
}
|
||||
}
|
||||
if apiKeyBodyChanged {
|
||||
requestView = newOpenAIRequestView(body)
|
||||
reqModel, reqStream, promptCacheKey = requestView.Model, requestView.Stream, requestView.PromptCacheKey
|
||||
originalModel = reqModel
|
||||
}
|
||||
requestView = newOpenAIRequestView(body)
|
||||
reqModel, reqStream, promptCacheKey = requestView.Model, requestView.Stream, requestView.PromptCacheKey
|
||||
originalModel = reqModel
|
||||
}
|
||||
|
||||
// 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。OpenAI API Key 账号只会落到
|
||||
@@ -196,7 +211,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
|
||||
if account.IsOpenAI() && (account.IsOpenAIApiKey() || account.IsOpenAIOAuthLike()) {
|
||||
normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplay(body)
|
||||
normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplayWithInput(body, requestView.Input)
|
||||
if reasoningErr != nil {
|
||||
return nil, fmt.Errorf("normalize OpenAI Responses reasoning content replay: %w", reasoningErr)
|
||||
}
|
||||
@@ -207,7 +222,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
reqModel, reqStream, promptCacheKey = requestView.Model, requestView.Stream, requestView.PromptCacheKey
|
||||
originalModel = reqModel
|
||||
}
|
||||
sanitizedBody, changed, sanitizeErr := sanitizeOpenAIResponsesInputItemIDs(body)
|
||||
sanitizedBody, changed, sanitizeErr := sanitizeOpenAIResponsesInputItemIDsWithInput(body, requestView.Input)
|
||||
if sanitizeErr != nil {
|
||||
return nil, fmt.Errorf("sanitize OpenAI Responses input item IDs: %w", sanitizeErr)
|
||||
}
|
||||
@@ -220,7 +235,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
}
|
||||
|
||||
compatMessagesBridge := isOpenAICompatMessagesBridgeBody(body)
|
||||
compatMessagesBridge := isOpenAICompatMessagesBridgePromptCacheKey(requestView.PromptCacheKey) ||
|
||||
bytes.Contains(body, []byte(openAICompatClaudeCodeTodoGuardMarker))
|
||||
setOpenAICompatMessagesBridgeContext(c, compatMessagesBridge)
|
||||
|
||||
isCodexCLI := openai.IsCodexOfficialClientByHeaders(c.GetHeader("User-Agent"), c.GetHeader("originator")) || (s.cfg != nil && s.cfg.Gateway.ForceCodexCLI)
|
||||
@@ -272,7 +288,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
// 透传分支只需要轻量提取字段,避免热路径全量 Unmarshal。
|
||||
mappedModel := account.GetMappedModel(reqModel)
|
||||
reasoningEffort := extractOpenAIReasoningEffortFromBody(body, mappedModel)
|
||||
reasoningEffort := extractOpenAIReasoningEffortFromView(requestView, mappedModel)
|
||||
// 国产模型默认 effort 补充:也要用 mappedModel 判定是否是 passback-required 上游。
|
||||
reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, mappedModel)
|
||||
return s.forwardOpenAIPassthrough(
|
||||
@@ -409,8 +425,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
upstreamModel = compactModel
|
||||
}
|
||||
}
|
||||
instructions := gjson.GetBytes(body, "instructions")
|
||||
instructionsEmpty := !instructions.Exists() || instructions.Type != gjson.String || strings.TrimSpace(instructions.String()) == ""
|
||||
instructionsEmpty := requestView.InstructionsEmpty
|
||||
if instructionsEmpty && account.UsesOpenAICodexProtocol() && !compatMessagesBridge && !nativeCNResponses {
|
||||
markPatchSet("instructions", defaultCodexSynthInstructions(upstreamModel))
|
||||
}
|
||||
@@ -428,12 +443,11 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Upstream model resolved: %s -> %s (account: %s, type: %s, isCodexCLI: %v)", billingModel, upstreamModel, account.Name, account.Type, isCodexCLI)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String()) == "minimal" {
|
||||
if requestView.ReasoningEffort == "minimal" {
|
||||
markPatchSet("reasoning.effort", "none")
|
||||
logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Normalized reasoning.effort: minimal -> none (account: %s)", account.Name)
|
||||
}
|
||||
if strings.TrimSpace(gjson.GetBytes(body, "text.format.type").String()) == "json_schema" ||
|
||||
strings.TrimSpace(gjson.GetBytes(body, "response_format.type").String()) == "json_schema" {
|
||||
if requestView.TextFormatType == "json_schema" || requestView.ResponseFormatType == "json_schema" {
|
||||
decoded, decodeErr := ensureReqBody()
|
||||
if decodeErr != nil {
|
||||
return nil, decodeErr
|
||||
@@ -527,10 +541,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
// Responses OAuth 与 Chat 兼容入口保持一致:纯文本 system 可以无损提升后删除,
|
||||
// JSON object 模式仍需在 input 中保留 JSON 指令供上游兼容校验。
|
||||
omitPromotedSystemMessages := !strings.EqualFold(
|
||||
strings.TrimSpace(gjson.GetBytes(body, "text.format.type").String()),
|
||||
"json_object",
|
||||
)
|
||||
omitPromotedSystemMessages := !strings.EqualFold(requestView.TextFormatType, "json_object")
|
||||
codexResult := codexTransformResult{}
|
||||
if compatMessagesBridge {
|
||||
codexResult = applyCodexOAuthTransformWithOptions(decoded, codexOAuthTransformOptions{
|
||||
@@ -607,12 +618,12 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
}
|
||||
|
||||
if !SupportsVerbosity(upstreamModel) && gjson.GetBytes(body, "text.verbosity").Exists() {
|
||||
if !SupportsVerbosity(upstreamModel) && requestView.HasTextVerbosity {
|
||||
markPatchDelete("text.verbosity")
|
||||
}
|
||||
|
||||
if !isCodexCLI {
|
||||
maxOutputTokens := gjson.GetBytes(body, "max_output_tokens")
|
||||
maxOutputTokens := requestView.MaxOutputTokens
|
||||
if maxOutputTokens.Exists() {
|
||||
switch account.Platform {
|
||||
case PlatformOpenAI, PlatformDeepseek:
|
||||
@@ -639,20 +650,24 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
// 仅对 OpenAI 平台归一化:Anthropic 合法使用 max_tokens,其 max_output_tokens
|
||||
// 反向转换已在上方 switch 中处理。
|
||||
if account.Platform == PlatformOpenAI {
|
||||
if maxTokens := gjson.GetBytes(body, "max_tokens"); maxTokens.Exists() {
|
||||
if !gjson.GetBytes(body, "max_output_tokens").Exists() {
|
||||
if maxTokens := requestView.MaxTokens; maxTokens.Exists() {
|
||||
if !maxOutputTokens.Exists() {
|
||||
markPatchSet("max_output_tokens", maxTokens.Value())
|
||||
}
|
||||
markPatchDelete("max_tokens")
|
||||
}
|
||||
}
|
||||
if gjson.GetBytes(body, "max_completion_tokens").Exists() && (account.Type == AccountTypeAPIKey || account.Platform != PlatformOpenAI) {
|
||||
if requestView.HasMaxCompletionTokens && (account.Type == AccountTypeAPIKey || account.Platform != PlatformOpenAI) {
|
||||
markPatchDelete("max_completion_tokens")
|
||||
}
|
||||
for _, unsupportedField := range []string{"prompt_cache_retention", "safety_identifier", "prompt_cache_options"} {
|
||||
if gjson.GetBytes(body, unsupportedField).Exists() {
|
||||
markPatchDelete(unsupportedField)
|
||||
}
|
||||
if requestView.HasPromptCacheRetention {
|
||||
markPatchDelete("prompt_cache_retention")
|
||||
}
|
||||
if requestView.HasSafetyIdentifier {
|
||||
markPatchDelete("safety_identifier")
|
||||
}
|
||||
if requestView.HasPromptCacheOptions {
|
||||
markPatchDelete("prompt_cache_options")
|
||||
}
|
||||
}
|
||||
// Ollama Cloud(实际 Responses 上游为 ollama.com)输出上限 clamp:对 Codex 与
|
||||
@@ -664,7 +679,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
markPatchSet("max_output_tokens", clampedCap)
|
||||
}
|
||||
if wsDecision.Transport != OpenAIUpstreamTransportResponsesWebsocketV2 &&
|
||||
!account.IsOpenAIApiKey() && gjson.GetBytes(body, "previous_response_id").Exists() {
|
||||
!account.IsOpenAIApiKey() && requestView.HasPreviousResponseID {
|
||||
markPatchDelete("previous_response_id")
|
||||
}
|
||||
if openAIRequestBodyMayContainEmptyBase64InputImage(body) {
|
||||
@@ -754,7 +769,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
}
|
||||
// Run after orphan-output filtering and all request-map rebuilds so a
|
||||
// compaction trigger cannot remain ahead of surviving history items.
|
||||
if normalizedBody, changed, normalizeErr := NormalizeCompactionTriggerInputOrder(body); normalizeErr != nil {
|
||||
if normalizedBody, changed, normalizeErr := normalizeCompactionTriggerInputOrderValidated(body, bodyValidated); normalizeErr != nil {
|
||||
return nil, fmt.Errorf("normalize compaction trigger order: %w", normalizeErr)
|
||||
} else if changed {
|
||||
body = normalizedBody
|
||||
@@ -1043,7 +1058,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
return nil, wsErr
|
||||
}
|
||||
|
||||
reasoningEffort := extractOpenAIReasoningEffortFromBody(body, upstreamModel, billingModel, originalModel)
|
||||
reasoningEffort := extractOpenAIReasoningEffortFromView(requestView, upstreamModel, billingModel, originalModel)
|
||||
// 国产模型默认 effort 补充:此处 reqModel 已被 mapping 重写为 billingModel。
|
||||
reasoningEffort = ApplyThinkingEnabledFallback(reasoningEffort, body, reqModel)
|
||||
reasoningEffortValue := ""
|
||||
@@ -1072,7 +1087,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
upstreamCtx, releaseUpstreamCtx, startTime.Add(firstOutputTimeout),
|
||||
)
|
||||
}
|
||||
syncOpenAIResponsesInstructionsEcho(c, body)
|
||||
syncOpenAIResponsesInstructionsEchoRaw(c, requestView.HasInstructions, requestView.InstructionsRaw)
|
||||
upstreamReq, err := s.buildUpstreamRequest(upstreamCtx, c, account, body, token, reqStream, promptCacheKey, isCodexCLI)
|
||||
if headerGuard == nil {
|
||||
releaseUpstreamCtx()
|
||||
@@ -1171,6 +1186,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serialize invalid_encrypted_content retry body: %w", err)
|
||||
}
|
||||
requestView = newOpenAIRequestView(body)
|
||||
if len(invalidDigests) > 0 {
|
||||
if lineageSessionHash == "" {
|
||||
lineageSessionHash = s.GenerateSessionHash(c, lineageEntryBody)
|
||||
@@ -1197,7 +1213,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
c, account, requestedModel, body, resp.StatusCode, upstreamMsg, respBody, compactModelFallbackRetried,
|
||||
); retry {
|
||||
s.appendOpenAICompactFallbackRetryOps(c, account, resp, respBody, upstreamMsg, false)
|
||||
fromModel := strings.TrimSpace(gjson.GetBytes(body, "model").String())
|
||||
fromModel := requestView.Model
|
||||
body = retryBody
|
||||
requestView = newOpenAIRequestView(body)
|
||||
reqBody = nil
|
||||
@@ -1256,7 +1272,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
|
||||
resp.Body = newResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize, s.cfg)
|
||||
}
|
||||
|
||||
serviceTier := extractOpenAIServiceTierFromBody(body)
|
||||
serviceTier := normalizeOpenAIServiceTier(requestView.ServiceTier)
|
||||
// 上游接受后只保留计费需要的标量,避免响应处理期间继续保活完整 input/tools map。
|
||||
reqBody = nil
|
||||
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
"unsafe"
|
||||
|
||||
"github.com/MoeForge/moego/ojson"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
@@ -82,6 +84,29 @@ func shouldPreserveOpenAIResponsesNoneReasoningEffort(account *Account) bool {
|
||||
return baseURL == "" || isOfficialOpenAIModelsBaseURL(baseURL)
|
||||
}
|
||||
|
||||
const openAIRequestBodyJSONValidatedKey = "openai_request_body_json_validated"
|
||||
|
||||
// MarkOpenAIRequestBodyJSONValidated 标记当前请求体已通过入口 JSON 语法校验,
|
||||
// 供下游只读规范化步骤跳过重复的全量 gjson.ValidBytes 扫描。
|
||||
func MarkOpenAIRequestBodyJSONValidated(c *gin.Context) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.Set(openAIRequestBodyJSONValidatedKey, true)
|
||||
}
|
||||
|
||||
func isOpenAIRequestBodyJSONValidated(c *gin.Context) bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
v, ok := c.Get(openAIRequestBodyJSONValidatedKey)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
validated, ok := v.(bool)
|
||||
return ok && validated
|
||||
}
|
||||
|
||||
// Codex 0.149.0 needs a single advertised effort to directly select a visible
|
||||
// non-reasoning model. Treat that catalog-only "none" value as omission for
|
||||
// compatible upstreams, while preserving official OpenAI request semantics.
|
||||
@@ -89,20 +114,64 @@ func filterOpenAIResponsesNoneReasoningEffortForAccount(account *Account, body [
|
||||
if len(body) == 0 || shouldPreserveOpenAIResponsesNoneReasoningEffort(account) {
|
||||
return body, nil
|
||||
}
|
||||
mayEscape := JSONMayEscapePlainASCII(body)
|
||||
seenReasoning := !bytes.Contains(body, []byte(`"reasoning"`)) && !mayEscape
|
||||
seenNestedEffort := seenReasoning
|
||||
seenReasoningEffort := !bytes.Contains(body, []byte(`"reasoning_effort"`)) && !mayEscape
|
||||
if seenReasoning && seenReasoningEffort {
|
||||
return body, nil
|
||||
}
|
||||
|
||||
root := parseRawJSONView(body)
|
||||
if !root.IsObject() {
|
||||
return body, nil
|
||||
}
|
||||
var reasoning, effortVal, reasoningEffort gjson.Result
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "reasoning":
|
||||
if !seenReasoning {
|
||||
reasoning = value
|
||||
seenReasoning = true
|
||||
}
|
||||
if !seenNestedEffort {
|
||||
if v := value.Get("effort"); v.Exists() {
|
||||
effortVal = v
|
||||
seenNestedEffort = true
|
||||
}
|
||||
}
|
||||
case "reasoning_effort":
|
||||
if !seenReasoningEffort {
|
||||
reasoningEffort = value
|
||||
seenReasoningEffort = true
|
||||
}
|
||||
}
|
||||
return !seenReasoning || !seenNestedEffort || !seenReasoningEffort
|
||||
})
|
||||
|
||||
dropNestedNone := effortVal.Type == gjson.String && strings.EqualFold(strings.TrimSpace(effortVal.String()), "none")
|
||||
dropTopNone := reasoningEffort.Type == gjson.String && strings.EqualFold(strings.TrimSpace(reasoningEffort.String()), "none")
|
||||
dropEmptyReasoning := reasoning.IsObject() && !gjsonObjectHasMembers(reasoning)
|
||||
if !dropNestedNone && !dropTopNone && !dropEmptyReasoning {
|
||||
return body, nil
|
||||
}
|
||||
|
||||
out := body
|
||||
for _, path := range []string{"reasoning.effort", "reasoning_effort"} {
|
||||
effort := gjson.GetBytes(out, path)
|
||||
if effort.Type != gjson.String || !strings.EqualFold(strings.TrimSpace(effort.String()), "none") {
|
||||
continue
|
||||
}
|
||||
next, err := sjson.DeleteBytes(out, path)
|
||||
if dropNestedNone {
|
||||
next, err := sjson.DeleteBytes(out, "reasoning.effort")
|
||||
if err != nil {
|
||||
return body, fmt.Errorf("strip %s none placeholder: %w", path, err)
|
||||
return body, fmt.Errorf("strip reasoning.effort none placeholder: %w", err)
|
||||
}
|
||||
out = next
|
||||
}
|
||||
if reasoning := gjson.GetBytes(out, "reasoning"); reasoning.IsObject() && len(reasoning.Map()) == 0 {
|
||||
if dropTopNone {
|
||||
next, err := sjson.DeleteBytes(out, "reasoning_effort")
|
||||
if err != nil {
|
||||
return body, fmt.Errorf("strip reasoning_effort none placeholder: %w", err)
|
||||
}
|
||||
out = next
|
||||
}
|
||||
if r := parseRawJSONView(out).Get("reasoning"); r.IsObject() && !gjsonObjectHasMembers(r) {
|
||||
next, err := sjson.DeleteBytes(out, "reasoning")
|
||||
if err != nil {
|
||||
return body, fmt.Errorf("strip empty reasoning object: %w", err)
|
||||
@@ -112,6 +181,18 @@ func filterOpenAIResponsesNoneReasoningEffortForAccount(account *Account, body [
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func gjsonObjectHasMembers(value gjson.Result) bool {
|
||||
if !value.IsObject() {
|
||||
return false
|
||||
}
|
||||
has := false
|
||||
value.ForEach(func(_, _ gjson.Result) bool {
|
||||
has = true
|
||||
return false
|
||||
})
|
||||
return has
|
||||
}
|
||||
|
||||
func deleteOpenAIResponsesNoneReasoningEffortFromObject(account *Account, body map[string]any) {
|
||||
if body == nil || shouldPreserveOpenAIResponsesNoneReasoningEffort(account) {
|
||||
return
|
||||
@@ -705,6 +786,17 @@ func normalizeOpenAIResponsesReasoningContentReplay(body []byte) ([]byte, bool,
|
||||
if !input.IsArray() {
|
||||
return body, false, nil
|
||||
}
|
||||
return normalizeOpenAIResponsesReasoningContentReplayWithInput(body, input)
|
||||
}
|
||||
|
||||
func normalizeOpenAIResponsesReasoningContentReplayWithInput(body []byte, input gjson.Result) ([]byte, bool, error) {
|
||||
if !input.IsArray() {
|
||||
return body, false, nil
|
||||
}
|
||||
inputBytes := unsafe.Slice(unsafe.StringData(input.Raw), len(input.Raw))
|
||||
if !bytes.Contains(inputBytes, []byte("reasoning")) && !JSONMayEscapePlainASCII(inputBytes) {
|
||||
return body, false, nil
|
||||
}
|
||||
|
||||
needsNormalization := false
|
||||
input.ForEach(func(_, item gjson.Result) bool {
|
||||
@@ -712,7 +804,7 @@ func normalizeOpenAIResponsesReasoningContentReplay(body []byte) ([]byte, bool,
|
||||
return true
|
||||
}
|
||||
content := item.Get("content")
|
||||
if content.IsArray() && len(content.Array()) > 0 {
|
||||
if content.IsArray() && gjsonArrayHasElements(content) {
|
||||
needsNormalization = true
|
||||
return false
|
||||
}
|
||||
@@ -1073,15 +1165,33 @@ func deriveOpenAIReasoningEffortFromModelCandidates(models []string) string {
|
||||
}
|
||||
|
||||
type openAIRequestView struct {
|
||||
body []byte
|
||||
Model string
|
||||
Stream bool
|
||||
PromptCacheKey string
|
||||
PreviousResponseID string
|
||||
ServiceTier string
|
||||
ReasoningEffort string
|
||||
patches []openAIRequestPatch
|
||||
patchesDisabled bool
|
||||
body []byte
|
||||
Model string
|
||||
Stream bool
|
||||
PromptCacheKey string
|
||||
PreviousResponseID string
|
||||
HasPreviousResponseID bool
|
||||
ServiceTier string
|
||||
ReasoningEffort string
|
||||
ReasoningEffortTop string
|
||||
MetadataUserID string
|
||||
HasInstructions bool
|
||||
InstructionsEmpty bool
|
||||
InstructionsRaw string
|
||||
StoreIsFalse bool
|
||||
HasParallelToolCalls bool
|
||||
HasTextVerbosity bool
|
||||
TextFormatType string
|
||||
ResponseFormatType string
|
||||
MaxOutputTokens gjson.Result
|
||||
MaxTokens gjson.Result
|
||||
HasMaxCompletionTokens bool
|
||||
HasPromptCacheRetention bool
|
||||
HasSafetyIdentifier bool
|
||||
HasPromptCacheOptions bool
|
||||
Input gjson.Result
|
||||
patches []openAIRequestPatch
|
||||
patchesDisabled bool
|
||||
}
|
||||
|
||||
type openAIRequestPatch struct {
|
||||
@@ -1092,29 +1202,53 @@ type openAIRequestPatch struct {
|
||||
|
||||
func newOpenAIRequestView(body []byte) openAIRequestView {
|
||||
if len(body) == 0 {
|
||||
return openAIRequestView{}
|
||||
return openAIRequestView{InstructionsEmpty: true}
|
||||
}
|
||||
|
||||
const (
|
||||
modelField uint8 = 1 << iota
|
||||
modelField uint32 = 1 << iota
|
||||
streamField
|
||||
promptCacheKeyField
|
||||
previousResponseIDField
|
||||
serviceTierField
|
||||
reasoningField
|
||||
reasoningEffortTopField
|
||||
metadataField
|
||||
instructionsField
|
||||
storeField
|
||||
parallelToolCallsField
|
||||
textVerbosityField
|
||||
textFormatTypeField
|
||||
responseFormatField
|
||||
maxOutputTokensField
|
||||
maxTokensField
|
||||
maxCompletionTokensField
|
||||
promptCacheRetentionField
|
||||
safetyIdentifierField
|
||||
promptCacheOptionsField
|
||||
inputField
|
||||
allRequestViewFields = modelField | streamField | promptCacheKeyField |
|
||||
previousResponseIDField | serviceTierField | reasoningField
|
||||
previousResponseIDField | serviceTierField | reasoningField | reasoningEffortTopField |
|
||||
metadataField | instructionsField | storeField | parallelToolCallsField |
|
||||
textVerbosityField | textFormatTypeField | responseFormatField |
|
||||
maxOutputTokensField | maxTokensField |
|
||||
maxCompletionTokensField | promptCacheRetentionField | safetyIdentifierField |
|
||||
promptCacheOptionsField | inputField
|
||||
)
|
||||
|
||||
view := openAIRequestView{body: body}
|
||||
var seen uint8
|
||||
view := openAIRequestView{body: body, InstructionsEmpty: true}
|
||||
root := parseRawJSONView(body)
|
||||
if !root.IsObject() {
|
||||
return view
|
||||
}
|
||||
var seen uint32
|
||||
// parseRawJSONView reads body without copying, so extracted strings alias the
|
||||
// body. They flow into usage logs and async tasks that outlive the request, so
|
||||
// clone them; otherwise a multi-MB body stays alive after its budget is freed.
|
||||
field := func(value gjson.Result) string {
|
||||
return strings.Clone(strings.TrimSpace(value.String()))
|
||||
}
|
||||
parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool {
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "model":
|
||||
if seen&modelField == 0 {
|
||||
@@ -1133,6 +1267,7 @@ func newOpenAIRequestView(body []byte) openAIRequestView {
|
||||
}
|
||||
case "previous_response_id":
|
||||
if seen&previousResponseIDField == 0 {
|
||||
view.HasPreviousResponseID = true
|
||||
view.PreviousResponseID = field(value)
|
||||
seen |= previousResponseIDField
|
||||
}
|
||||
@@ -1143,8 +1278,94 @@ func newOpenAIRequestView(body []byte) openAIRequestView {
|
||||
}
|
||||
case "reasoning":
|
||||
if seen&reasoningField == 0 {
|
||||
view.ReasoningEffort = field(value.Get("effort"))
|
||||
seen |= reasoningField
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
view.ReasoningEffort = field(effort)
|
||||
seen |= reasoningField
|
||||
}
|
||||
}
|
||||
case "reasoning_effort":
|
||||
if seen&reasoningEffortTopField == 0 {
|
||||
view.ReasoningEffortTop = field(value)
|
||||
seen |= reasoningEffortTopField
|
||||
}
|
||||
case "metadata":
|
||||
if seen&metadataField == 0 {
|
||||
if uid := value.Get("user_id"); uid.Exists() {
|
||||
view.MetadataUserID = field(uid)
|
||||
seen |= metadataField
|
||||
}
|
||||
}
|
||||
case "instructions":
|
||||
if seen&instructionsField == 0 {
|
||||
view.HasInstructions = true
|
||||
view.InstructionsRaw = value.Raw
|
||||
view.InstructionsEmpty = value.Type != gjson.String || strings.TrimSpace(value.String()) == ""
|
||||
seen |= instructionsField
|
||||
}
|
||||
case "store":
|
||||
if seen&storeField == 0 {
|
||||
view.StoreIsFalse = value.Type == gjson.False
|
||||
seen |= storeField
|
||||
}
|
||||
case "parallel_tool_calls":
|
||||
if seen¶llelToolCallsField == 0 {
|
||||
view.HasParallelToolCalls = true
|
||||
seen |= parallelToolCallsField
|
||||
}
|
||||
case "text":
|
||||
if value.IsObject() {
|
||||
if seen&textVerbosityField == 0 && value.Get("verbosity").Exists() {
|
||||
view.HasTextVerbosity = true
|
||||
seen |= textVerbosityField
|
||||
}
|
||||
if seen&textFormatTypeField == 0 {
|
||||
if ft := value.Get("format.type"); ft.Exists() {
|
||||
view.TextFormatType = field(ft)
|
||||
seen |= textFormatTypeField
|
||||
}
|
||||
}
|
||||
}
|
||||
case "response_format":
|
||||
if seen&responseFormatField == 0 && value.IsObject() {
|
||||
if rt := value.Get("type"); rt.Exists() {
|
||||
view.ResponseFormatType = field(rt)
|
||||
seen |= responseFormatField
|
||||
}
|
||||
}
|
||||
case "max_output_tokens":
|
||||
if seen&maxOutputTokensField == 0 {
|
||||
view.MaxOutputTokens = value
|
||||
seen |= maxOutputTokensField
|
||||
}
|
||||
case "max_tokens":
|
||||
if seen&maxTokensField == 0 {
|
||||
view.MaxTokens = value
|
||||
seen |= maxTokensField
|
||||
}
|
||||
case "max_completion_tokens":
|
||||
if seen&maxCompletionTokensField == 0 {
|
||||
view.HasMaxCompletionTokens = true
|
||||
seen |= maxCompletionTokensField
|
||||
}
|
||||
case "prompt_cache_retention":
|
||||
if seen&promptCacheRetentionField == 0 {
|
||||
view.HasPromptCacheRetention = true
|
||||
seen |= promptCacheRetentionField
|
||||
}
|
||||
case "safety_identifier":
|
||||
if seen&safetyIdentifierField == 0 {
|
||||
view.HasSafetyIdentifier = true
|
||||
seen |= safetyIdentifierField
|
||||
}
|
||||
case "prompt_cache_options":
|
||||
if seen&promptCacheOptionsField == 0 {
|
||||
view.HasPromptCacheOptions = true
|
||||
seen |= promptCacheOptionsField
|
||||
}
|
||||
case "input":
|
||||
if seen&inputField == 0 {
|
||||
view.Input = value
|
||||
seen |= inputField
|
||||
}
|
||||
}
|
||||
return seen != allRequestViewFields
|
||||
@@ -1912,6 +2133,26 @@ func isOpenAICodexModel(model string) bool {
|
||||
return strings.Contains(strings.ToLower(strings.TrimSpace(model)), "codex")
|
||||
}
|
||||
|
||||
func extractOpenAIReasoningEffortFromView(view openAIRequestView, modelCandidates ...string) *string {
|
||||
reasoningEffort := view.ReasoningEffort
|
||||
if reasoningEffort == "" {
|
||||
reasoningEffort = view.ReasoningEffortTop
|
||||
}
|
||||
if reasoningEffort != "" {
|
||||
normalized := normalizeOpenAIReasoningEffortForModel(reasoningEffort, firstNonEmpty(modelCandidates...))
|
||||
if normalized == "" {
|
||||
return nil
|
||||
}
|
||||
return &normalized
|
||||
}
|
||||
|
||||
value := deriveOpenAIReasoningEffortFromModelCandidates(modelCandidates)
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return &value
|
||||
}
|
||||
|
||||
// extractOpenAIReasoningEffortFromBody 按优先级传入模型候选(如 upstreamModel,
|
||||
// billingModel, originalModel):显式 effort 的模型归一化(max 保留判定)用第一个
|
||||
// 非空候选;body 未携带 effort 时的模型后缀推导依次尝试每个候选——OAuth 的
|
||||
@@ -1964,14 +2205,82 @@ func explicitRequestedReasoningEffortFromBody(body []byte) string {
|
||||
if latest := latestResponsesInputEffort(body); latest != "" {
|
||||
return latest
|
||||
}
|
||||
raw := strings.TrimSpace(gjson.GetBytes(body, "reasoning.effort").String())
|
||||
if !bytes.Contains(body, []byte("reasoning")) && !bytes.Contains(body, []byte("output_config")) && !JSONMayEscapePlainASCII(body) {
|
||||
return ""
|
||||
}
|
||||
root := parseRawJSONView(body)
|
||||
if !root.IsObject() {
|
||||
return ""
|
||||
}
|
||||
var (
|
||||
reasoningEffort string
|
||||
reasoningEffortTop string
|
||||
outputConfigEffort string
|
||||
seenReasoning bool
|
||||
seenReasoningTop bool
|
||||
seenOutputConfig bool
|
||||
)
|
||||
root.ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "reasoning":
|
||||
if !seenReasoning {
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
seenReasoning = true
|
||||
reasoningEffort = strings.TrimSpace(effort.String())
|
||||
if reasoningEffort != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
case "reasoning_effort":
|
||||
if !seenReasoningTop {
|
||||
seenReasoningTop = true
|
||||
reasoningEffortTop = strings.TrimSpace(value.String())
|
||||
}
|
||||
case "output_config":
|
||||
if !seenOutputConfig {
|
||||
if effort := value.Get("effort"); effort.Exists() {
|
||||
seenOutputConfig = true
|
||||
outputConfigEffort = strings.TrimSpace(effort.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
return !seenReasoning || !seenReasoningTop || !seenOutputConfig
|
||||
})
|
||||
if reasoningEffort != "" {
|
||||
return strings.Clone(reasoningEffort)
|
||||
}
|
||||
if reasoningEffortTop != "" {
|
||||
return strings.Clone(reasoningEffortTop)
|
||||
}
|
||||
if outputConfigEffort != "" {
|
||||
return strings.Clone(outputConfigEffort)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// CanonicalRequestedReasoningEffortWithFields 与 CanonicalRequestedReasoningEffort 语义一致,
|
||||
// 直接消费入口单次扫描已提取的顶层 effort 字段与模型名,避免对大请求体重复扫描。
|
||||
func CanonicalRequestedReasoningEffortWithFields(body []byte, reasoningEffort, reasoningEffortTop, outputConfigEffort string, modelCandidates ...string) *string {
|
||||
raw := latestResponsesInputEffort(body)
|
||||
if raw == "" {
|
||||
raw = strings.TrimSpace(gjson.GetBytes(body, "reasoning_effort").String())
|
||||
raw = strings.TrimSpace(reasoningEffort)
|
||||
}
|
||||
if raw == "" {
|
||||
raw = strings.TrimSpace(gjson.GetBytes(body, "output_config.effort").String())
|
||||
raw = strings.TrimSpace(reasoningEffortTop)
|
||||
}
|
||||
return raw
|
||||
if raw == "" {
|
||||
raw = strings.TrimSpace(outputConfigEffort)
|
||||
}
|
||||
if raw != "" {
|
||||
return optionalTrimmedStringPtr(normalizeReasoningEffortMappingSource(raw))
|
||||
}
|
||||
for _, model := range modelCandidates {
|
||||
if value := canonicalReasoningEffortFromModelSuffix(model); value != "" {
|
||||
return &value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CanonicalRequestedReasoningEffort extracts the client-requested effort before
|
||||
@@ -2089,7 +2398,14 @@ func boundInvalidOpenAIServiceTierValue(raw string) string {
|
||||
// unknown value → *ErrInvalidOpenAIServiceTier (handler maps to HTTP 400),
|
||||
// matching OpenAI's enum validation semantics
|
||||
func ValidateOpenAIServiceTierField(body []byte) (string, error) {
|
||||
tierResult := gjson.GetBytes(body, "service_tier")
|
||||
if !bytes.Contains(body, []byte(`"service_tier"`)) && !JSONMayEscapePlainASCII(body) {
|
||||
return "", nil
|
||||
}
|
||||
return ValidateOpenAIServiceTierResult(parseRawJSONView(body).Get("service_tier"))
|
||||
}
|
||||
|
||||
// ValidateOpenAIServiceTierResult 对已提取的 service_tier 字段值执行枚举校验。
|
||||
func ValidateOpenAIServiceTierResult(tierResult gjson.Result) (string, error) {
|
||||
if !tierResult.Exists() || tierResult.Type == gjson.Null {
|
||||
return "", nil
|
||||
}
|
||||
@@ -2102,7 +2418,7 @@ func ValidateOpenAIServiceTierField(body []byte) (string, error) {
|
||||
}
|
||||
norm := normalizedOpenAIServiceTierValue(raw)
|
||||
if norm == "" {
|
||||
return "", &ErrInvalidOpenAIServiceTier{Value: boundInvalidOpenAIServiceTierValue(raw)}
|
||||
return "", &ErrInvalidOpenAIServiceTier{Value: strings.Clone(boundInvalidOpenAIServiceTierValue(raw))}
|
||||
}
|
||||
return norm, nil
|
||||
}
|
||||
@@ -2605,8 +2921,10 @@ func openAIJSONValueMayContainImageInput(value gjson.Result) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var openAIBase64PrefixBytes = []byte("base64,")
|
||||
|
||||
func openAIRequestBodyMayContainEmptyBase64InputImage(body []byte) bool {
|
||||
if len(body) == 0 || !openAIRequestBodyMayContainInputImageToken(body) {
|
||||
if len(body) == 0 || !openAIRequestBodyMayContainEmptyBase64DataURI(body) || !openAIRequestBodyMayContainInputImageToken(body) {
|
||||
return false
|
||||
}
|
||||
input := parseRawJSONView(body).Get("input")
|
||||
@@ -2616,6 +2934,58 @@ func openAIRequestBodyMayContainEmptyBase64InputImage(body []byte) bool {
|
||||
return openAIJSONValueMayContainEmptyBase64InputImage(input)
|
||||
}
|
||||
|
||||
// openAIRequestBodyMayContainEmptyBase64DataURI 检查请求体是否存在可能解码为空 base64 data URI 的候选片段。
|
||||
// 非空 base64 图片在 "base64," 后紧跟 ASCII base64 字符,单字节即可跳过;
|
||||
// 仅当存在 \u 平面 ASCII 转义、或某个 "base64," 后紧跟纯空白/转义并以引号结束时返回 true。
|
||||
func openAIRequestBodyMayContainEmptyBase64DataURI(body []byte) bool {
|
||||
if JSONMayEscapePlainASCII(body) {
|
||||
return true
|
||||
}
|
||||
rest := body
|
||||
for {
|
||||
idx := bytes.Index(rest, openAIBase64PrefixBytes)
|
||||
if idx < 0 {
|
||||
return false
|
||||
}
|
||||
i := idx + len(openAIBase64PrefixBytes)
|
||||
for i < len(rest) {
|
||||
b := rest[i]
|
||||
switch b {
|
||||
case '"':
|
||||
return true
|
||||
case ' ', '\t', '\n', '\r':
|
||||
i++
|
||||
case '\\':
|
||||
if i+1 >= len(rest) {
|
||||
return true
|
||||
}
|
||||
switch rest[i+1] {
|
||||
case 't', 'n', 'r', 'f', 'u':
|
||||
// 可能是转义空白(如 \n/\t/\u0020/\u3000),继续或保守放行
|
||||
if rest[i+1] == 'u' {
|
||||
return true
|
||||
}
|
||||
i += 2
|
||||
default:
|
||||
// 非空白转义(如 \/),不为空
|
||||
goto nextMatch
|
||||
}
|
||||
default:
|
||||
if b >= 0x80 {
|
||||
// 可能是多字节 Unicode 空白,保守交由结构扫描判定
|
||||
return true
|
||||
}
|
||||
goto nextMatch
|
||||
}
|
||||
}
|
||||
if i >= len(rest) {
|
||||
return true
|
||||
}
|
||||
nextMatch:
|
||||
rest = rest[idx+len(openAIBase64PrefixBytes):]
|
||||
}
|
||||
}
|
||||
|
||||
func openAIRequestBodyMayContainInputImageToken(body []byte) bool {
|
||||
if bytes.Contains(body, []byte("input_image")) {
|
||||
return true
|
||||
@@ -2641,10 +3011,41 @@ func openAIJSONValueMayContainEmptyBase64InputImage(value gjson.Result) bool {
|
||||
return found
|
||||
}
|
||||
if value.IsObject() {
|
||||
if strings.TrimSpace(value.Get("type").String()) == "input_image" && isEmptyBase64DataURI(value.Get("image_url").String()) {
|
||||
var (
|
||||
itemType string
|
||||
imageURL string
|
||||
content gjson.Result
|
||||
seenType bool
|
||||
seenImageURL bool
|
||||
seenContent bool
|
||||
)
|
||||
value.ForEach(func(key, v gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "type":
|
||||
if !seenType {
|
||||
seenType = true
|
||||
itemType = strings.TrimSpace(v.String())
|
||||
}
|
||||
case "image_url":
|
||||
if !seenImageURL {
|
||||
seenImageURL = true
|
||||
imageURL = v.String()
|
||||
}
|
||||
case "content":
|
||||
if !seenContent {
|
||||
seenContent = true
|
||||
content = v
|
||||
}
|
||||
}
|
||||
return !seenType || !seenImageURL || !seenContent
|
||||
})
|
||||
if itemType == "input_image" && isEmptyBase64DataURI(imageURL) {
|
||||
return true
|
||||
}
|
||||
return openAIJSONValueMayContainEmptyBase64InputImage(value.Get("content"))
|
||||
if seenContent {
|
||||
return openAIJSONValueMayContainEmptyBase64InputImage(content)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -2763,7 +3164,22 @@ func isEmptyBase64DataURI(raw string) bool {
|
||||
if !strings.HasPrefix(rest, "base64,") {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(strings.TrimPrefix(rest, "base64,")) == ""
|
||||
payload := strings.TrimPrefix(rest, "base64,")
|
||||
for i := 0; i < len(payload); {
|
||||
if b := payload[i]; b < 0x80 {
|
||||
if b != ' ' && b != '\t' && b != '\n' && b != '\r' && b != '\v' && b != '\f' {
|
||||
return false
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
r, size := utf8.DecodeRuneInString(payload[i:])
|
||||
if !unicode.IsSpace(r) {
|
||||
return false
|
||||
}
|
||||
i += size
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getOpenAIRequestBodyMap(_ *gin.Context, body []byte) (map[string]any, error) {
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOpenAIRequestBodyMayContainEmptyBase64DataURI(t *testing.T) {
|
||||
largeB64 := strings.Repeat("AAAA", 16*1024)
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
prefilter bool
|
||||
emptyImg bool
|
||||
}{
|
||||
{
|
||||
name: "non-empty valid base64 images",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"message","role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,` + largeB64 + `"}]}]}`,
|
||||
prefilter: false,
|
||||
emptyImg: false,
|
||||
},
|
||||
{
|
||||
name: "non-empty escaped slash base64",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/jpeg;base64,\/9j\/4AAQ"}]}`,
|
||||
prefilter: false,
|
||||
emptyImg: false,
|
||||
},
|
||||
{
|
||||
name: "empty base64 data uri",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,"}]}`,
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
{
|
||||
name: "ascii whitespace only base64",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64, \t\n\r "}]}`,
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
{
|
||||
name: "unicode whitespace escape base64",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,\u00a0\u3000"}]}`,
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
{
|
||||
name: "raw utf8 nbsp whitespace base64",
|
||||
body: "{\"model\":\"gpt-6.2-astra\",\"input\":[{\"type\":\"input_image\",\"image_url\":\"data:image/png;base64,\u00a0\"}]}",
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
{
|
||||
name: "unicode escaped base64 keyword",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;\u0062ase64,"}]}`,
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
{
|
||||
name: "fourth image empty after three valid images",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,QUFB"},{"type":"input_image","image_url":"data:image/png;base64,QkJC"},{"type":"input_image","image_url":"data:image/png;base64,Q0ND"},{"type":"input_image","image_url":"data:image/png;base64, "}]}`,
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
{
|
||||
name: "input_image with valid image_url but nested empty content",
|
||||
body: `{"model":"gpt-6.2-astra","input":[{"type":"input_image","image_url":"data:image/png;base64,QUFB","content":[{"type":"input_image","image_url":"data:image/png;base64,"}]}]}`,
|
||||
prefilter: true,
|
||||
emptyImg: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
raw := []byte(tc.body)
|
||||
require.Equal(t, tc.prefilter, openAIRequestBodyMayContainEmptyBase64DataURI(raw))
|
||||
require.Equal(t, tc.emptyImg, openAIRequestBodyMayContainEmptyBase64InputImage(raw))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIRequestViewExpandedFields(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"model": " gpt-6.2-astra ",
|
||||
"stream": true,
|
||||
"prompt_cache_key": " pck-1 ",
|
||||
"previous_response_id": " resp_123 ",
|
||||
"service_tier": " priority ",
|
||||
"reasoning": {"effort": " minimal "},
|
||||
"reasoning_effort": " high ",
|
||||
"metadata": {"user_id": " user_99 "},
|
||||
"instructions": " follow rules ",
|
||||
"store": false,
|
||||
"parallel_tool_calls": true,
|
||||
"text": {"verbosity": "low", "format": {"type": "json_schema"}},
|
||||
"response_format": {"type": "json_object"},
|
||||
"max_output_tokens": 4096,
|
||||
"max_tokens": 2048,
|
||||
"max_completion_tokens": 1024,
|
||||
"prompt_cache_retention": "24h",
|
||||
"safety_identifier": "safe-1",
|
||||
"prompt_cache_options": {"enabled": true},
|
||||
"input": [{"type": "message", "role": "user", "content": "hi"}]
|
||||
}`)
|
||||
|
||||
view := newOpenAIRequestView(body)
|
||||
require.Equal(t, "gpt-6.2-astra", view.Model)
|
||||
require.True(t, view.Stream)
|
||||
require.Equal(t, "pck-1", view.PromptCacheKey)
|
||||
require.True(t, view.HasPreviousResponseID)
|
||||
require.Equal(t, "resp_123", view.PreviousResponseID)
|
||||
require.Equal(t, "priority", view.ServiceTier)
|
||||
require.Equal(t, "minimal", view.ReasoningEffort)
|
||||
require.Equal(t, "high", view.ReasoningEffortTop)
|
||||
require.Equal(t, "user_99", view.MetadataUserID)
|
||||
require.True(t, view.HasInstructions)
|
||||
require.False(t, view.InstructionsEmpty)
|
||||
require.Equal(t, `" follow rules "`, view.InstructionsRaw)
|
||||
require.True(t, view.StoreIsFalse)
|
||||
require.True(t, view.HasParallelToolCalls)
|
||||
require.True(t, view.HasTextVerbosity)
|
||||
require.Equal(t, "json_schema", view.TextFormatType)
|
||||
require.Equal(t, "json_object", view.ResponseFormatType)
|
||||
require.True(t, view.MaxOutputTokens.Exists())
|
||||
require.Equal(t, float64(4096), view.MaxOutputTokens.Value())
|
||||
require.True(t, view.MaxTokens.Exists())
|
||||
require.Equal(t, float64(2048), view.MaxTokens.Value())
|
||||
require.True(t, view.HasMaxCompletionTokens)
|
||||
require.True(t, view.HasPromptCacheRetention)
|
||||
require.True(t, view.HasSafetyIdentifier)
|
||||
require.True(t, view.HasPromptCacheOptions)
|
||||
require.True(t, view.Input.IsArray())
|
||||
|
||||
// Escaped keys and first-key precedence match gjson.GetBytes.
|
||||
escaped := []byte(`{"\u006dodel":"first","model":"second","\u0073tore":false,"instructions":" "}`)
|
||||
ev := newOpenAIRequestView(escaped)
|
||||
require.Equal(t, "first", ev.Model)
|
||||
require.True(t, ev.StoreIsFalse)
|
||||
require.True(t, ev.HasInstructions)
|
||||
require.True(t, ev.InstructionsEmpty)
|
||||
|
||||
// Non-object root and empty body return safe zero views with InstructionsEmpty=true.
|
||||
arrView := newOpenAIRequestView([]byte(`[{"model":"x"}]`))
|
||||
require.Empty(t, arrView.Model)
|
||||
require.True(t, arrView.InstructionsEmpty)
|
||||
emptyView := newOpenAIRequestView(nil)
|
||||
require.True(t, emptyView.InstructionsEmpty)
|
||||
|
||||
// Duplicate parent keys: nested lookups follow gjson.GetBytes and continue until child exists.
|
||||
dupParent := []byte(`{
|
||||
"model": "gpt-6.2-astra",
|
||||
"reasoning": {},
|
||||
"reasoning": {"effort": "high"},
|
||||
"metadata": {},
|
||||
"metadata": {"user_id": "sess-1"},
|
||||
"text": {},
|
||||
"text": {"verbosity": "low"},
|
||||
"text": {"format": {"type": "json_schema"}},
|
||||
"response_format": {},
|
||||
"response_format": {"type": "json_schema"}
|
||||
}`)
|
||||
dv := newOpenAIRequestView(dupParent)
|
||||
require.Equal(t, "high", dv.ReasoningEffort)
|
||||
require.Equal(t, "sess-1", dv.MetadataUserID)
|
||||
require.True(t, dv.HasTextVerbosity)
|
||||
require.Equal(t, "json_schema", dv.TextFormatType)
|
||||
require.Equal(t, "json_schema", dv.ResponseFormatType)
|
||||
}
|
||||
|
||||
func TestFilterOpenAIResponsesNoneReasoningEffortForAccountFastPath(t *testing.T) {
|
||||
acct := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{
|
||||
"base_url": "https://compat.example.com/v1",
|
||||
},
|
||||
}
|
||||
|
||||
unchanged := []byte(`{"model":"gpt-6.2-astra","reasoning":{"effort":"medium"},"input":[{"type":"message","role":"user","content":"hello"}]}`)
|
||||
out, err := filterOpenAIResponsesNoneReasoningEffortForAccount(acct, unchanged)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(unchanged), string(out))
|
||||
|
||||
noneNested := []byte(`{"model":"gpt-6.2-astra","reasoning":{"effort":"none"}}`)
|
||||
out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, noneNested)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(out), "reasoning")
|
||||
|
||||
noneTop := []byte(`{"model":"gpt-6.2-astra","reasoning_effort":"NONE"}`)
|
||||
out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, noneTop)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(out), "reasoning_effort")
|
||||
|
||||
escapedKey := []byte(`{"model":"gpt-6.2-astra","\u0072easoning":{"effort":"none"}}`)
|
||||
out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, escapedKey)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(out), "none")
|
||||
|
||||
dupParentEmpty := []byte(`{"model":"gpt-6.2-astra","reasoning":{},"reasoning":{"effort":"none"}}`)
|
||||
out, err = filterOpenAIResponsesNoneReasoningEffortForAccount(acct, dupParentEmpty)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, `{"model":"gpt-6.2-astra","reasoning":{"effort":"none"}}`, string(out))
|
||||
}
|
||||
|
||||
func TestOpenAIResponsesRejectedFieldRetryStateLazyHash(t *testing.T) {
|
||||
initial := []byte(`{"model":"gpt-6.2-astra","max_output_tokens":100}`)
|
||||
state := newOpenAIResponsesRejectedFieldRetryState(initial)
|
||||
require.Nil(t, state.seenBodyHashes)
|
||||
require.NotNil(t, state.initialBody)
|
||||
|
||||
// Re-submitting initial body hashes lazily and is rejected.
|
||||
require.False(t, state.Allow(initial))
|
||||
require.Nil(t, state.initialBody)
|
||||
require.Len(t, state.seenBodyHashes, 1)
|
||||
|
||||
retry1 := []byte(`{"model":"gpt-6.2-astra"}`)
|
||||
require.True(t, state.Allow(retry1))
|
||||
require.False(t, state.Allow(retry1))
|
||||
|
||||
retry2 := []byte(`{"model":"gpt-6.2-astra","stream":true}`)
|
||||
require.True(t, state.Allow(retry2))
|
||||
|
||||
// remember() also initializes initialBody hash lazily.
|
||||
state2 := newOpenAIResponsesRejectedFieldRetryState(initial)
|
||||
state2.remember(retry1)
|
||||
require.Nil(t, state2.initialBody)
|
||||
require.False(t, state2.Allow(initial))
|
||||
require.False(t, state2.Allow(retry1))
|
||||
require.True(t, state2.Allow(retry2))
|
||||
}
|
||||
|
||||
func TestSetOpenAICodexRoutingHintFromBodyNonOAuthStripsHeader(t *testing.T) {
|
||||
acct := &Account{
|
||||
Platform: PlatformOpenAI,
|
||||
Type: AccountTypeAPIKey,
|
||||
}
|
||||
headers := http.Header{}
|
||||
headers.Set("X-Codex-Routing-Hint", "stale-hint")
|
||||
|
||||
setOpenAICodexRoutingHintFromBody(headers, acct, []byte(`{"model":"gpt-6.2-astra","service_tier":"priority"}`))
|
||||
require.Empty(t, headers.Get("X-Codex-Routing-Hint"))
|
||||
}
|
||||
|
||||
func TestRememberOpenCodeInboundSessionFromView(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{name: "prompt_cache_key", body: `{"model":"m","prompt_cache_key":"sess-pck"}`},
|
||||
{name: "plain_metadata_user_id", body: `{"model":"m","metadata":{"user_id":"user-plain"}}`},
|
||||
{name: "json_metadata_user_id", body: `{"model":"m","metadata":{"user_id":"{\"session_id\":\"sess-json\"}"}}`},
|
||||
{name: "empty_body", body: ``},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c1, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c2, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
raw := []byte(tc.body)
|
||||
|
||||
rememberOpenCodeInboundBody(c1, raw)
|
||||
rememberOpenCodeInboundSessionFromView(c2, newOpenAIRequestView(raw))
|
||||
|
||||
require.Equal(t, openCodeInboundBodies(c1), openCodeInboundBodies(c2))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalRequestedReasoningEffortWithFields(t *testing.T) {
|
||||
body := []byte(`{"model":"gpt-6.2-astra-high","reasoning":{"effort":"medium"},"reasoning_effort":"low","output_config":{"effort":"xhigh"}}`)
|
||||
got := CanonicalRequestedReasoningEffortWithFields(body, "medium", "low", "xhigh", "gpt-6.2-astra-high")
|
||||
require.NotNil(t, got)
|
||||
require.Equal(t, "medium", *got)
|
||||
|
||||
got2 := CanonicalRequestedReasoningEffortWithFields(body, "", "low", "xhigh", "gpt-6.2-astra-high")
|
||||
require.NotNil(t, got2)
|
||||
require.Equal(t, "low", *got2)
|
||||
|
||||
got3 := CanonicalRequestedReasoningEffortWithFields(body, "", "", "xhigh", "gpt-6.2-astra-high")
|
||||
require.NotNil(t, got3)
|
||||
require.Equal(t, "xhigh", *got3)
|
||||
|
||||
got4 := CanonicalRequestedReasoningEffortWithFields([]byte(`{"model":"gpt-6.2-astra-high"}`), "", "", "", "gpt-6.2-astra-high")
|
||||
require.NotNil(t, got4)
|
||||
require.Equal(t, "high", *got4)
|
||||
|
||||
cfgUpdate := []byte(`{"model":"gpt-6.2-astra","reasoning":{"effort":"low"},"input":[{"type":"configuration_update","reasoning":{"effort":"max"}}]}`)
|
||||
got5 := CanonicalRequestedReasoningEffortWithFields(cfgUpdate, "low", "", "", "gpt-6.2-astra")
|
||||
require.NotNil(t, got5)
|
||||
require.Equal(t, "max", *got5)
|
||||
|
||||
// Duplicate parent keys in explicitRequestedReasoningEffortFromBody match gjson.GetBytes.
|
||||
require.Equal(t, "high", explicitRequestedReasoningEffortFromBody([]byte(`{"reasoning":{},"reasoning":{"effort":"high"}}`)))
|
||||
require.Equal(t, "xhigh", explicitRequestedReasoningEffortFromBody([]byte(`{"output_config":{},"output_config":{"effort":"xhigh"}}`)))
|
||||
}
|
||||
|
||||
func TestNormalizeOpenAIResponsesLegacyIngressValidatedNonObjectRoot(t *testing.T) {
|
||||
_, _, err := normalizeOpenAIResponsesLegacyIngressValidated(nil, []byte(`[]`), true)
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -71,6 +71,18 @@ func rememberOpenCodeInboundBody(c *gin.Context, body []byte) {
|
||||
c.Set(openCodeInboundBodyContextKey, openCodeSessionHintBody(sessionID))
|
||||
}
|
||||
|
||||
func rememberOpenCodeInboundSessionFromView(c *gin.Context, view openAIRequestView) {
|
||||
if c == nil || len(view.body) == 0 {
|
||||
return
|
||||
}
|
||||
raw := view.PromptCacheKey
|
||||
if raw == "" {
|
||||
raw = openCodeSessionIDFromMetadataUserID(view.MetadataUserID)
|
||||
}
|
||||
sessionID := sanitizeSessionID(raw)
|
||||
c.Set(openCodeInboundBodyContextKey, openCodeSessionHintBody(sessionID))
|
||||
}
|
||||
|
||||
func openCodeInboundBodies(c *gin.Context) [][]byte {
|
||||
if c == nil {
|
||||
return nil
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -10,6 +11,12 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
var (
|
||||
openAILegacyMessagesFieldBytes = []byte(`"messages"`)
|
||||
openAILegacyPromptFieldBytes = []byte(`"prompt"`)
|
||||
openAILegacyCommandsFieldBytes = []byte(`"commands"`)
|
||||
)
|
||||
|
||||
// normalizeOpenAIResponsesLegacyIngress accepts the Chat Completions-shaped
|
||||
// payloads that a few Responses clients still emit. Native Responses input is
|
||||
// always authoritative because this path has no separate full-replay attempt.
|
||||
@@ -17,6 +24,37 @@ func normalizeOpenAIResponsesLegacyIngress(body []byte) ([]byte, bool, error) {
|
||||
return normalizeOpenAIResponsesLegacyIngressWithConfig(nil, body)
|
||||
}
|
||||
|
||||
func normalizeOpenAIResponsesLegacyIngressValidated(cfg *config.Config, body []byte, validated bool) ([]byte, bool, error) {
|
||||
if len(body) == 0 {
|
||||
return body, false, nil
|
||||
}
|
||||
if validated {
|
||||
trimmed := bytes.TrimLeft(body, " \t\r\n")
|
||||
if len(trimmed) > 0 && trimmed[0] == '{' &&
|
||||
!bytes.Contains(body, openAILegacyMessagesFieldBytes) &&
|
||||
!bytes.Contains(body, openAILegacyPromptFieldBytes) &&
|
||||
!bytes.Contains(body, openAILegacyCommandsFieldBytes) &&
|
||||
!JSONMayEscapePlainASCII(body) {
|
||||
return body, false, nil
|
||||
}
|
||||
view := parseRawJSONView(body)
|
||||
if view.IsObject() {
|
||||
hasLegacyField := false
|
||||
view.ForEach(func(key, _ gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "messages", "prompt", "commands":
|
||||
hasLegacyField = true
|
||||
}
|
||||
return !hasLegacyField
|
||||
})
|
||||
if !hasLegacyField {
|
||||
return body, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return normalizeOpenAIResponsesLegacyIngressWithConfig(cfg, body)
|
||||
}
|
||||
|
||||
func normalizeOpenAIResponsesLegacyIngressWithConfig(cfg *config.Config, body []byte) ([]byte, bool, error) {
|
||||
if len(body) == 0 {
|
||||
return body, false, nil
|
||||
|
||||
@@ -26,6 +26,33 @@ type openAIResponsesClientInstructions struct {
|
||||
raw string
|
||||
}
|
||||
|
||||
// syncOpenAIResponsesInstructionsEchoRaw 按已提取的上游 instructions 原始 JSON 对比并登记还原值。
|
||||
func syncOpenAIResponsesInstructionsEchoRaw(c *gin.Context, hasInstructions bool, rawValue string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
stored, ok := c.Get(openAIResponsesClientInstructionsKey)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
client, ok := stored.(openAIResponsesClientInstructions)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
upstreamRaw := ""
|
||||
if hasInstructions {
|
||||
upstreamRaw = rawValue
|
||||
}
|
||||
restore := ""
|
||||
if !openAIResponsesInstructionsRawEqual(client.raw, upstreamRaw) {
|
||||
restore = client.raw
|
||||
if restore == "" {
|
||||
restore = "null"
|
||||
}
|
||||
}
|
||||
c.Set(openAIResponsesInstructionsEchoRestoreKey, restore)
|
||||
}
|
||||
|
||||
// rememberOpenAIResponsesClientInstructions 记录本次转发尝试的客户端原始
|
||||
// instructions,并清空还原值,使未登记上游请求体的转发分支不做还原。
|
||||
func rememberOpenAIResponsesClientInstructions(c *gin.Context, body []byte) {
|
||||
@@ -33,8 +60,10 @@ func rememberOpenAIResponsesClientInstructions(c *gin.Context, body []byte) {
|
||||
return
|
||||
}
|
||||
raw := ""
|
||||
if value := gjson.GetBytes(body, "instructions"); value.Exists() {
|
||||
raw = compactOpenAIResponsesInstructionsRaw(value.Raw)
|
||||
if bytes.Contains(body, openAIResponsesInstructionsFieldMarker) || JSONMayEscapePlainASCII(body) {
|
||||
if value := gjson.GetBytes(body, "instructions"); value.Exists() {
|
||||
raw = compactOpenAIResponsesInstructionsRaw(value.Raw)
|
||||
}
|
||||
}
|
||||
c.Set(openAIResponsesClientInstructionsKey, openAIResponsesClientInstructions{raw: raw})
|
||||
c.Set(openAIResponsesInstructionsEchoRestoreKey, "")
|
||||
@@ -55,8 +84,10 @@ func syncOpenAIResponsesInstructionsEcho(c *gin.Context, upstreamBody []byte) {
|
||||
return
|
||||
}
|
||||
upstreamRaw := ""
|
||||
if value := gjson.GetBytes(upstreamBody, "instructions"); value.Exists() {
|
||||
upstreamRaw = value.Raw
|
||||
if bytes.Contains(upstreamBody, openAIResponsesInstructionsFieldMarker) || JSONMayEscapePlainASCII(upstreamBody) {
|
||||
if value := gjson.GetBytes(upstreamBody, "instructions"); value.Exists() {
|
||||
upstreamRaw = value.Raw
|
||||
}
|
||||
}
|
||||
restore := ""
|
||||
if !openAIResponsesInstructionsRawEqual(client.raw, upstreamRaw) {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
@@ -62,11 +64,30 @@ func shouldStripOpenAIResponsesNonPairCallID(itemType string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
openAIResponsesIDFieldBytes = []byte(`"id"`)
|
||||
openAIResponsesCallIDFieldBytes = []byte(`"call_id"`)
|
||||
)
|
||||
|
||||
func sanitizeOpenAIResponsesInputItemIDs(body []byte) ([]byte, bool, error) {
|
||||
if !bytes.Contains(body, openAIResponsesIDFieldBytes) && !bytes.Contains(body, openAIResponsesCallIDFieldBytes) && !JSONMayEscapePlainASCII(body) {
|
||||
return body, false, nil
|
||||
}
|
||||
input := parseRawJSONView(body).Get("input")
|
||||
if !input.IsArray() {
|
||||
return body, false, nil
|
||||
}
|
||||
return sanitizeOpenAIResponsesInputItemIDsWithInput(body, input)
|
||||
}
|
||||
|
||||
func sanitizeOpenAIResponsesInputItemIDsWithInput(body []byte, input gjson.Result) ([]byte, bool, error) {
|
||||
if !input.IsArray() {
|
||||
return body, false, nil
|
||||
}
|
||||
inputBytes := unsafe.Slice(unsafe.StringData(input.Raw), len(input.Raw))
|
||||
if !bytes.Contains(inputBytes, openAIResponsesIDFieldBytes) && !bytes.Contains(inputBytes, openAIResponsesCallIDFieldBytes) && !JSONMayEscapePlainASCII(inputBytes) {
|
||||
return body, false, nil
|
||||
}
|
||||
|
||||
type inputItem struct {
|
||||
raw string
|
||||
@@ -78,11 +99,30 @@ func sanitizeOpenAIResponsesInputItemIDs(body []byte) ([]byte, bool, error) {
|
||||
input.ForEach(func(_, item gjson.Result) bool {
|
||||
parsed := inputItem{raw: item.Raw}
|
||||
if item.IsObject() {
|
||||
itemType := item.Get("type")
|
||||
id := item.Get("id")
|
||||
var itemType, id gjson.Result
|
||||
var seenType, seenID, seenCallID bool
|
||||
item.ForEach(func(k, v gjson.Result) bool {
|
||||
switch k.Str {
|
||||
case "type":
|
||||
if !seenType {
|
||||
itemType = v
|
||||
seenType = true
|
||||
}
|
||||
case "id":
|
||||
if !seenID {
|
||||
id = v
|
||||
seenID = true
|
||||
}
|
||||
case "call_id":
|
||||
if !seenCallID {
|
||||
seenCallID = true
|
||||
}
|
||||
}
|
||||
return !seenType || !seenID || !seenCallID
|
||||
})
|
||||
trimmedItemType := strings.TrimSpace(itemType.String())
|
||||
parsed.stripCallID = item.Get("call_id").Exists() && shouldStripOpenAIResponsesNonPairCallID(trimmedItemType)
|
||||
if id.Type == gjson.String {
|
||||
parsed.stripCallID = seenCallID && shouldStripOpenAIResponsesNonPairCallID(trimmedItemType)
|
||||
if seenID && id.Type == gjson.String {
|
||||
parsed.stripID = shouldStripOpenAIResponsesInputItemID(trimmedItemType, id.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ var (
|
||||
type openAIResponsesRejectedFieldRetryState struct {
|
||||
mu sync.Mutex
|
||||
budget *openAIResponsesRejectedFieldRetryBudget
|
||||
initialBody []byte
|
||||
seenBodyHashes map[[sha256.Size]byte]struct{}
|
||||
}
|
||||
|
||||
@@ -67,12 +68,18 @@ func newOpenAIResponsesRejectedFieldRetryState(initialBody []byte) *openAIRespon
|
||||
}
|
||||
|
||||
func newOpenAIResponsesRejectedFieldRetryStateWithBudget(initialBody []byte, budget *openAIResponsesRejectedFieldRetryBudget) *openAIResponsesRejectedFieldRetryState {
|
||||
state := &openAIResponsesRejectedFieldRetryState{
|
||||
budget: budget,
|
||||
seenBodyHashes: make(map[[sha256.Size]byte]struct{}, maxOpenAIResponsesRejectedFieldRetries+1),
|
||||
return &openAIResponsesRejectedFieldRetryState{
|
||||
budget: budget,
|
||||
initialBody: initialBody,
|
||||
}
|
||||
state.remember(initialBody)
|
||||
return state
|
||||
}
|
||||
|
||||
func (s *openAIResponsesRejectedFieldRetryState) ensureInitialHashLocked() {
|
||||
if len(s.initialBody) == 0 {
|
||||
return
|
||||
}
|
||||
s.rememberLocked(s.initialBody)
|
||||
s.initialBody = nil
|
||||
}
|
||||
|
||||
func (s *openAIResponsesRejectedFieldRetryState) Allow(nextBody []byte) bool {
|
||||
@@ -81,6 +88,7 @@ func (s *openAIResponsesRejectedFieldRetryState) Allow(nextBody []byte) bool {
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.ensureInitialHashLocked()
|
||||
bodyHash := sha256.Sum256(nextBody)
|
||||
if _, seen := s.seenBodyHashes[bodyHash]; seen {
|
||||
return false
|
||||
@@ -90,6 +98,9 @@ func (s *openAIResponsesRejectedFieldRetryState) Allow(nextBody []byte) bool {
|
||||
if s.budget.attempts >= maxOpenAIResponsesRejectedFieldRetries {
|
||||
return false
|
||||
}
|
||||
if s.seenBodyHashes == nil {
|
||||
s.seenBodyHashes = make(map[[sha256.Size]byte]struct{}, maxOpenAIResponsesRejectedFieldRetries+1)
|
||||
}
|
||||
s.seenBodyHashes[bodyHash] = struct{}{}
|
||||
s.budget.attempts++
|
||||
return true
|
||||
@@ -101,6 +112,7 @@ func (s *openAIResponsesRejectedFieldRetryState) remember(body []byte) {
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.ensureInitialHashLocked()
|
||||
s.rememberLocked(body)
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,13 @@ func deleteOpenAIHeaderEqualFold(headers http.Header, name string) {
|
||||
}
|
||||
|
||||
func setOpenAICodexRoutingHintFromBody(headers http.Header, account *Account, body []byte) {
|
||||
if headers == nil {
|
||||
return
|
||||
}
|
||||
if account == nil || !account.IsOpenAIOAuthLike() {
|
||||
deleteOpenAIHeaderEqualFold(headers, openAICodexRoutingHintHeader)
|
||||
return
|
||||
}
|
||||
fields := gjson.GetManyBytes(body, "model", "service_tier")
|
||||
setOpenAICodexRoutingHint(headers, account, fields[0].String(), fields[1].String())
|
||||
}
|
||||
@@ -115,6 +122,12 @@ func logOpenAIRoutingDiagnosticsFromBody(
|
||||
body []byte,
|
||||
wsAffinityDecision string,
|
||||
) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if !logger.FromContext(ctx).Core().Enabled(zap.DebugLevel) {
|
||||
return
|
||||
}
|
||||
fields := gjson.GetManyBytes(body, "model", "service_tier")
|
||||
logOpenAIRoutingDiagnostics(
|
||||
ctx,
|
||||
|
||||
Reference in new issue
Block a user