mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
Merge remote-tracking branch 'origin/main' into pr-9255-fix
This commit is contained in:
commit
bfceebe029
19 files changed
+677
-151
No files matched your search
@@ -55,6 +55,13 @@ const (
|
||||
// 语义上等同于「无可用账号」:候选账号都不满足分组的利润约束。
|
||||
const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control"
|
||||
|
||||
func appendUpstreamRetryAfterField(fields []zap.Field, failoverErr *service.UpstreamFailoverError) []zap.Field {
|
||||
if failoverErr != nil && failoverErr.UpstreamRetryAfter > 0 {
|
||||
return append(fields, zap.Duration("upstream_retry_after", failoverErr.UpstreamRetryAfter))
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryCount int) time.Duration {
|
||||
if failoverErr == nil {
|
||||
return sameAccountRetryDelay
|
||||
@@ -220,13 +227,14 @@ func (s *FailoverState) HandleFailoverError(
|
||||
if sameAccountRetry {
|
||||
s.SameAccountRetryCount[accountID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, s.SameAccountRetryCount[accountID])
|
||||
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("same_account_retry_count", s.SameAccountRetryCount[accountID]),
|
||||
zap.Int("same_account_retry_max", retryLimit),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", retryFields...)
|
||||
if !sleepWithContext(ctx, retryDelay) {
|
||||
return FailoverCanceled
|
||||
}
|
||||
@@ -248,12 +256,13 @@ func (s *FailoverState) HandleFailoverError(
|
||||
|
||||
// 递增切换计数
|
||||
s.SwitchCount++
|
||||
logger.FromContext(ctx).Warn("gateway.failover_switch_account",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", accountID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", s.SwitchCount),
|
||||
zap.Int("max_switches", s.MaxSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
logger.FromContext(ctx).Warn("gateway.failover_switch_account", switchFields...)
|
||||
|
||||
// Antigravity 平台换号线性递增延时
|
||||
if platform == service.PlatformAntigravity {
|
||||
|
||||
@@ -242,13 +242,14 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_alpha_search.same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_alpha_search.same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -269,11 +270,12 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, false)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_alpha_search.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_alpha_search.upstream_failover_switching", switchFields...)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//go:build unit
|
||||
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func capacityShedSSEOverloadResponse(retryAfterSec string) *http.Response {
|
||||
stream := fmt.Sprintf(
|
||||
"event: response.created\n"+
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_shed\"}}\n\n"+
|
||||
"event: error\n"+
|
||||
"data: {\"type\":\"error\",\"error\":{\"type\":\"service_unavailable_error\",\"code\":\"server_is_overloaded\",\"message\":\"Our servers are currently overloaded. Please try again later.\",\"headers\":{\"retry-after\":%q}}}\n\n",
|
||||
retryAfterSec,
|
||||
)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(bytes.NewBufferString(stream)),
|
||||
}
|
||||
}
|
||||
|
||||
func capacityShedHTTPOverloadResponse(retryAfterMs string) *http.Response {
|
||||
h := http.Header{"Content-Type": []string{"application/json"}}
|
||||
if retryAfterMs != "" {
|
||||
h.Set("Retry-After-Ms", retryAfterMs)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusServiceUnavailable,
|
||||
Header: h,
|
||||
Body: io.NopCloser(bytes.NewBufferString(
|
||||
`{"error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_LongOverloadRetryAfterSwitchesImmediately(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(capacityShedSSEOverloadResponse("315"), astra200())
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 2}, accountIDs)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
require.Equal(t, "completed", gjson.GetBytes(rec.Body.Bytes(), "status").String())
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_ShortOverloadRetryAfterRetriesSameAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(capacityShedHTTPOverloadResponse("10"), astra200())
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 1}, accountIDs)
|
||||
require.Equal(t, http.StatusOK, rec.Code)
|
||||
}
|
||||
|
||||
func TestOpenAIGatewayHandlerResponses_AllAccountsLongOverloadFailsFast503(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
upstream := newAstraProCapturedUpstream(
|
||||
capacityShedSSEOverloadResponse("315"),
|
||||
capacityShedSSEOverloadResponse("335"),
|
||||
)
|
||||
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
|
||||
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
|
||||
|
||||
handler.Responses(c)
|
||||
|
||||
_, accountIDs, _ := upstream.snapshot()
|
||||
require.Equal(t, []int64{1, 2}, accountIDs)
|
||||
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
|
||||
require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "servers are currently overloaded")
|
||||
}
|
||||
@@ -359,13 +359,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -386,12 +387,13 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_chat_completions.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_chat_completions.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, nil), false, nil, err)
|
||||
|
||||
@@ -247,12 +247,13 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
switchCount++
|
||||
reqLog.Warn("openai_embeddings.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_embeddings.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), false, nil, err)
|
||||
|
||||
@@ -981,13 +981,14 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -1024,6 +1025,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
|
||||
} else if account.ProxyID != nil {
|
||||
failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID))
|
||||
}
|
||||
failoverSwitchFields = appendUpstreamRetryAfterField(failoverSwitchFields, failoverErr)
|
||||
reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...)
|
||||
continue
|
||||
}
|
||||
@@ -1561,13 +1563,14 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai_messages.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_messages.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
return
|
||||
@@ -1588,12 +1591,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
|
||||
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai_messages.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai_messages.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
if result != nil && result.ClientDisconnect {
|
||||
@@ -3077,12 +3081,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
|
||||
closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr)
|
||||
return false
|
||||
}
|
||||
reqLog.Warn("openai.websocket_upstream_failover_switching",
|
||||
wsSwitchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.websocket_upstream_failover_switching", wsSwitchFields...)
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -333,13 +333,14 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
|
||||
sameAccountRetryCount[account.ID]++
|
||||
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
|
||||
reqLog.Warn("openai.images.pool_mode_same_account_retry",
|
||||
retryFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("retry_limit", retryLimit),
|
||||
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
|
||||
zap.Duration("retry_delay", retryDelay),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.images.pool_mode_same_account_retry", retryFields...)
|
||||
select {
|
||||
case <-requestCtx.Done():
|
||||
return
|
||||
@@ -360,12 +361,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
|
||||
h.handleFailoverExhausted(c, failoverErr, streamStarted)
|
||||
return
|
||||
}
|
||||
reqLog.Warn("openai.images.upstream_failover_switching",
|
||||
switchFields := appendUpstreamRetryAfterField([]zap.Field{
|
||||
zap.Int64("account_id", account.ID),
|
||||
zap.Int("upstream_status", failoverErr.StatusCode),
|
||||
zap.Int("switch_count", switchCount),
|
||||
zap.Int("max_switches", maxAccountSwitches),
|
||||
)
|
||||
}, failoverErr)
|
||||
reqLog.Warn("openai.images.upstream_failover_switching", switchFields...)
|
||||
continue
|
||||
}
|
||||
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err)
|
||||
|
||||
@@ -1152,7 +1152,7 @@ func (s *BillingService) initFallbackPricing() {
|
||||
// getFallbackPricing 根据模型系列获取回退价格
|
||||
func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
|
||||
modelLower := normalizeAntigravityClaudeTierAlias(strings.ToLower(model))
|
||||
if modelLower == "gpt-image-2.6-flare" || modelLower == "gpt-image-2.6-sunburst" {
|
||||
if isGPTImage26Model(modelLower) {
|
||||
p := openAIGPTImage25FallbackPricing
|
||||
return &ModelPricing{
|
||||
InputPricePerToken: p.InputCostPerToken, CacheReadPricePerToken: p.CacheReadInputTokenCost,
|
||||
|
||||
@@ -794,6 +794,7 @@ type UpstreamFailoverError struct {
|
||||
ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true
|
||||
RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换
|
||||
SameAccountRetryDelay time.Duration // 同账号重试的最小间隔;零值使用 handler 默认值
|
||||
UpstreamRetryAfter time.Duration // 上游原始 Retry-After 建议时长(未截断),用于决策与可观测日志
|
||||
SameAccountRetryDeadline time.Time // 同账号重试截止时间;零值表示仅受 retryLimit 限制
|
||||
SameAccountRetryMax int // 可选的错误级同账号重试上限,低于 handler 默认预算时优先采用
|
||||
RequestScopedTransient bool // 故障因素与账号无关(如上游按客户端身份/模型容量降载):可同账号重试,但不得据此对账号做临时封禁
|
||||
|
||||
@@ -112,16 +112,78 @@ func TestOpenAIHTTPCapacityShedIsRequestScopedForOAuthAccounts(t *testing.T) {
|
||||
|
||||
func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
headers http.Header
|
||||
body string
|
||||
want time.Duration
|
||||
name string
|
||||
headers http.Header
|
||||
body string
|
||||
callerSameAccount bool
|
||||
wantDelay time.Duration
|
||||
wantUpstreamHint time.Duration
|
||||
wantSameAccountTry bool
|
||||
}{
|
||||
{name: "http seconds", headers: http.Header{"Retry-After": []string{"6"}}, want: 6 * time.Second},
|
||||
{name: "http milliseconds", headers: http.Header{"Retry-After-Ms": []string{"6000"}}, want: 6 * time.Second},
|
||||
{name: "body seconds", body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`, want: 7 * time.Second},
|
||||
{name: "body milliseconds", body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`, want: 7 * time.Second},
|
||||
{name: "bounded", headers: http.Header{"Retry-After": []string{"60"}}, want: openAIRequestScopedRetryMaxDelay},
|
||||
{
|
||||
name: "missing retry-after keeps same-account retry",
|
||||
body: `{"error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
wantDelay: 0,
|
||||
wantUpstreamHint: 0,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "http seconds within budget",
|
||||
headers: http.Header{"Retry-After": []string{"6"}},
|
||||
wantDelay: 6 * time.Second,
|
||||
wantUpstreamHint: 6 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "http milliseconds within budget",
|
||||
headers: http.Header{"Retry-After-Ms": []string{"6000"}},
|
||||
wantDelay: 6 * time.Second,
|
||||
wantUpstreamHint: 6 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "body seconds within budget",
|
||||
body: `{"error":{"headers":{"retry-after":"7"},"message":"Our servers are currently overloaded. Please try again later."}}`,
|
||||
wantDelay: 7 * time.Second,
|
||||
wantUpstreamHint: 7 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "body milliseconds within budget",
|
||||
body: `{"response":{"error":{"headers":{"retry-after-ms":"7000"},"message":"Our servers are currently overloaded. Please try again later."}}}`,
|
||||
wantDelay: 7 * time.Second,
|
||||
wantUpstreamHint: 7 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "exact max delay boundary still retries same account",
|
||||
headers: http.Header{"Retry-After": []string{"8"}},
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: openAIRequestScopedRetryMaxDelay,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
{
|
||||
name: "long http retry-after skips non-pool same-account retry",
|
||||
headers: http.Header{"Retry-After": []string{"60"}},
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: 60 * time.Second,
|
||||
wantSameAccountTry: false,
|
||||
},
|
||||
{
|
||||
name: "long event retry-after skips non-pool same-account retry",
|
||||
body: `{"type":"error","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`,
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: 315 * time.Second,
|
||||
wantSameAccountTry: false,
|
||||
},
|
||||
{
|
||||
name: "pool-mode caller retains bounded same-account retry on long hint",
|
||||
body: `{"type":"error","error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`,
|
||||
callerSameAccount: true,
|
||||
wantDelay: openAIRequestScopedRetryMaxDelay,
|
||||
wantUpstreamHint: 315 * time.Second,
|
||||
wantSameAccountTry: true,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
failoverErr := newOpenAIUpstreamFailoverError(
|
||||
@@ -129,14 +191,81 @@ func TestOpenAICapacityShedHonorsRetryAfter(t *testing.T) {
|
||||
test.headers,
|
||||
[]byte(test.body),
|
||||
"Our servers are currently overloaded. Please try again later.",
|
||||
false,
|
||||
test.callerSameAccount,
|
||||
)
|
||||
require.True(t, failoverErr.RequestScopedTransient)
|
||||
require.Equal(t, test.want, failoverErr.SameAccountRetryDelay)
|
||||
require.Equal(t, test.wantDelay, failoverErr.SameAccountRetryDelay)
|
||||
require.Equal(t, test.wantUpstreamHint, failoverErr.UpstreamRetryAfter)
|
||||
require.Equal(t, test.wantSameAccountTry, failoverErr.RetryableOnSameAccount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIStreamCapacityShedLongRetryAfterSkipsSameAccountReplay(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, passthrough := range []bool{false, true} {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
retryAfter string
|
||||
poolMode bool
|
||||
wantSameAccount bool
|
||||
wantHint time.Duration
|
||||
}{
|
||||
{name: "short_7s_oauth", retryAfter: "7", wantSameAccount: true, wantHint: 7 * time.Second},
|
||||
{name: "long_315s_oauth_switches", retryAfter: "315", wantSameAccount: false, wantHint: 315 * time.Second},
|
||||
{name: "long_315s_pool_keeps_retry", retryAfter: "315", poolMode: true, wantSameAccount: true, wantHint: 315 * time.Second},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("passthrough=%t/%s", passthrough, tc.name), func(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}}}
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
|
||||
stream := strings.Join([]string{
|
||||
"event: response.created",
|
||||
`data: {"type":"response.created","response":{"id":"resp_1"}}`,
|
||||
"",
|
||||
"event: error",
|
||||
fmt.Sprintf(`data: {"type":"error","error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":%q}}}`, tc.retryAfter),
|
||||
"",
|
||||
}, "\n")
|
||||
resp := &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{},
|
||||
Body: io.NopCloser(strings.NewReader(stream)),
|
||||
}
|
||||
account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Name: "acc"}
|
||||
if tc.poolMode {
|
||||
account.Type = AccountTypeAPIKey
|
||||
account.Credentials = map[string]any{"pool_mode": true}
|
||||
}
|
||||
var err error
|
||||
if passthrough {
|
||||
_, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "model", "model")
|
||||
} else {
|
||||
_, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "model", "model")
|
||||
}
|
||||
var failoverErr *UpstreamFailoverError
|
||||
require.ErrorAs(t, err, &failoverErr)
|
||||
require.True(t, failoverErr.RequestScopedTransient)
|
||||
require.Equal(t, tc.wantSameAccount, failoverErr.RetryableOnSameAccount)
|
||||
require.Equal(t, tc.wantHint, failoverErr.UpstreamRetryAfter)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIOAuth429WrappedCapacityShedLongRetryAfterSkipsDeadlineWindow(t *testing.T) {
|
||||
svc := &OpenAIGatewayService{}
|
||||
account := &Account{ID: 921, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
|
||||
payload := []byte(`{"type":"error","error":{"type":"rate_limit_error","code":"slow_down","message":"Our servers are currently overloaded. Please try again later.","headers":{"retry-after":"315"}}}`)
|
||||
err := svc.newOpenAIAccountFailoverError(account, http.StatusTooManyRequests, nil, payload, "Our servers are currently overloaded. Please try again later.", false, false)
|
||||
|
||||
require.True(t, err.RequestScopedTransient)
|
||||
require.False(t, err.RetryableOnSameAccount)
|
||||
require.True(t, err.SameAccountRetryDeadline.IsZero())
|
||||
require.Equal(t, 315*time.Second, err.UpstreamRetryAfter)
|
||||
}
|
||||
|
||||
// 上游降载的真实序列是「event: error → event: response.failed」。error 帧不算
|
||||
// 客户端输出:若把它当首输出 flush,clientOutputStarted 被固化,随后的 failed
|
||||
// 事件就进不了 pre-output failover 分支,只能把致命错误原样转发给客户端。
|
||||
|
||||
@@ -1922,15 +1922,20 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects(
|
||||
}
|
||||
|
||||
func openAIStreamFailedEventRetryableOnSameAccount(account *Account, payload []byte, message string) bool {
|
||||
return openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account, nil, payload, message)
|
||||
}
|
||||
|
||||
func openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account *Account, headers http.Header, payload []byte, message string) bool {
|
||||
if account == nil {
|
||||
return false
|
||||
}
|
||||
// 容量降载是请求级信号,不是账号级故障:上游只是让本次请求稍后再试。
|
||||
// 换账号并不改变被降载的因素(客户端身份、模型容量都与账号无关),
|
||||
// 只会让单个请求把整池账号逐个消耗掉,最终仍以同一个错误告终。
|
||||
// 因此先在同一账号上做有界重试,用尽后才按常规流程切号。
|
||||
// 容量降载是请求级信号,不是账号级故障:短时过载先在同一账号上做有界重试;
|
||||
// 若上游明确建议等待时长超过单次同号重试预算上限,非池模式单凭据账号不再盲目原地重放,直接优先尝试其他可用账号。
|
||||
if isOpenAIUpstreamCapacityShedEvent(payload) {
|
||||
return true
|
||||
upstreamRetryAfter, _ := parseUpstreamRetryAfterDelay(headers, payload)
|
||||
if openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if !account.IsPoolMode() {
|
||||
return false
|
||||
@@ -2035,7 +2040,7 @@ func (s *OpenAIGatewayService) newOpenAIStreamFailoverErrorWithModel(
|
||||
"message": message,
|
||||
},
|
||||
})
|
||||
retryableOnSameAccount := openAIStreamFailedEventRetryableOnSameAccount(account, payload, message)
|
||||
retryableOnSameAccount := openAIStreamFailedEventRetryableOnSameAccountWithHeaders(account, headers, payload, message)
|
||||
// 流终止事件承载在 HTTP 200 内,外层响应头描述的是成功流状态,而不是语义上的
|
||||
// 429 事件。仅在配额分类时忽略这些头;故障转移错误仍保留它们,使 Retry-After
|
||||
// 和请求 ID 能继续传递给后续处理。
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -197,59 +196,19 @@ func isOpenAIRequestScopedCapacityShed(upstreamMsg string, upstreamBody []byte)
|
||||
|
||||
const openAIRequestScopedRetryMaxDelay = 8 * time.Second
|
||||
|
||||
func openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter time.Duration) bool {
|
||||
return upstreamRetryAfter <= 0 || upstreamRetryAfter <= openAIRequestScopedRetryMaxDelay
|
||||
}
|
||||
|
||||
func openAIRequestScopedRetryDelay(responseHeaders http.Header, responseBody []byte) time.Duration {
|
||||
type retryAfterValue struct {
|
||||
raw string
|
||||
milliseconds bool
|
||||
delay, ok := parseUpstreamRetryAfterDelay(responseHeaders, responseBody)
|
||||
if !ok || delay <= 0 {
|
||||
return 0
|
||||
}
|
||||
for _, value := range []retryAfterValue{
|
||||
{raw: responseHeaders.Get("Retry-After")},
|
||||
{raw: responseHeaders.Get("Retry-After-Ms"), milliseconds: true},
|
||||
{raw: gjson.GetBytes(responseBody, "error.headers.retry-after").String()},
|
||||
{raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after").String()},
|
||||
{raw: gjson.GetBytes(responseBody, "error.headers.retry-after-ms").String(), milliseconds: true},
|
||||
{raw: gjson.GetBytes(responseBody, "response.error.headers.retry-after-ms").String(), milliseconds: true},
|
||||
} {
|
||||
raw := strings.TrimSpace(value.raw)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
var delay time.Duration
|
||||
var ok bool
|
||||
if value.milliseconds {
|
||||
delay, ok = parseOpenAIRequestScopedRetryDelayMilliseconds(raw)
|
||||
} else {
|
||||
delay, ok = parseOpenAIRequestScopedRetryDelay(raw)
|
||||
}
|
||||
if !ok || delay <= 0 {
|
||||
continue
|
||||
}
|
||||
if delay > openAIRequestScopedRetryMaxDelay {
|
||||
return openAIRequestScopedRetryMaxDelay
|
||||
}
|
||||
return delay
|
||||
if delay > openAIRequestScopedRetryMaxDelay {
|
||||
return openAIRequestScopedRetryMaxDelay
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseOpenAIRequestScopedRetryDelay(raw string) (time.Duration, bool) {
|
||||
if seconds, err := strconv.ParseFloat(raw, 64); err == nil && seconds > 0 {
|
||||
return time.Duration(seconds * float64(time.Second)), true
|
||||
}
|
||||
if resetAt, err := http.ParseTime(raw); err == nil {
|
||||
delay := time.Until(resetAt)
|
||||
if delay > 0 {
|
||||
return delay, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func parseOpenAIRequestScopedRetryDelayMilliseconds(raw string) (time.Duration, bool) {
|
||||
if millis, err := strconv.ParseFloat(raw, 64); err == nil && millis > 0 {
|
||||
return time.Duration(millis * float64(time.Millisecond)), true
|
||||
}
|
||||
return 0, false
|
||||
return delay
|
||||
}
|
||||
|
||||
func isOpenAIContextWindowError(upstreamMsg string, upstreamBody []byte) bool {
|
||||
@@ -388,12 +347,18 @@ func newOpenAIUpstreamFailoverError(
|
||||
retryableOnSameAccount bool,
|
||||
) *UpstreamFailoverError {
|
||||
requestScopedCapacity := isOpenAIRequestScopedCapacityShed(upstreamMsg, responseBody)
|
||||
var upstreamRetryAfter time.Duration
|
||||
if requestScopedCapacity {
|
||||
upstreamRetryAfter, _ = parseUpstreamRetryAfterDelay(responseHeaders, responseBody)
|
||||
}
|
||||
capacitySameAccountRetry := requestScopedCapacity && openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter)
|
||||
failoverErr := &UpstreamFailoverError{
|
||||
StatusCode: statusCode,
|
||||
ResponseBody: responseBody,
|
||||
ResponseHeaders: responseHeaders.Clone(),
|
||||
RetryableOnSameAccount: retryableOnSameAccount || requestScopedCapacity,
|
||||
RetryableOnSameAccount: retryableOnSameAccount || capacitySameAccountRetry,
|
||||
RequestScopedTransient: requestScopedCapacity,
|
||||
UpstreamRetryAfter: upstreamRetryAfter,
|
||||
}
|
||||
if requestScopedCapacity {
|
||||
failoverErr.SameAccountRetryDelay = openAIRequestScopedRetryDelay(responseHeaders, responseBody)
|
||||
@@ -448,6 +413,11 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverErrorWithClassificationHe
|
||||
retryableOnSameAccount bool,
|
||||
) *UpstreamFailoverError {
|
||||
oauth429Retry := s.shouldRetryOpenAIOAuth429OnSameAccountWithResponse(account, statusCode, shouldDisable, classificationHeaders, responseBody)
|
||||
if oauth429Retry && isOpenAIRequestScopedCapacityShed(upstreamMsg, responseBody) {
|
||||
if upstreamRetryAfter, ok := parseUpstreamRetryAfterDelay(responseHeaders, responseBody); ok && !openAICapacityShedAllowsSameAccountRetry(upstreamRetryAfter) {
|
||||
oauth429Retry = false
|
||||
}
|
||||
}
|
||||
failoverErr := newOpenAIUpstreamFailoverError(
|
||||
statusCode,
|
||||
responseHeaders,
|
||||
|
||||
@@ -193,6 +193,15 @@ func (r *OpenAIImagesRequest) IsEdits() bool {
|
||||
return r != nil && r.Endpoint == openAIImagesEditsEndpoint
|
||||
}
|
||||
|
||||
func (r *OpenAIImagesRequest) HasImageInputs() bool {
|
||||
return r != nil && (len(r.InputImageURLs) > 0 ||
|
||||
len(r.Uploads) > 0 ||
|
||||
strings.TrimSpace(r.MaskImageURL) != "" ||
|
||||
r.MaskUpload != nil ||
|
||||
strings.TrimSpace(r.MarkupImageURL) != "" ||
|
||||
r.MarkupUpload != nil)
|
||||
}
|
||||
|
||||
func (r *OpenAIImagesRequest) StickySessionSeed() string {
|
||||
if r == nil {
|
||||
return ""
|
||||
@@ -302,7 +311,6 @@ func parseOpenAIImagesJSONRequest(body []byte, req *OpenAIImagesRequest) error {
|
||||
req.Moderation = strings.TrimSpace(gjson.GetBytes(body, "moderation").String())
|
||||
req.InputFidelity = strings.TrimSpace(gjson.GetBytes(body, "input_fidelity").String())
|
||||
req.Style = strings.TrimSpace(gjson.GetBytes(body, "style").String())
|
||||
req.HasMask = gjson.GetBytes(body, "mask").Exists()
|
||||
if outputCompression := gjson.GetBytes(body, "output_compression"); outputCompression.Exists() {
|
||||
if outputCompression.Type != gjson.Number {
|
||||
return fmt.Errorf("invalid output_compression field type")
|
||||
@@ -331,51 +339,106 @@ func parseOpenAIImagesJSONRequest(body []byte, req *OpenAIImagesRequest) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if req.IsEdits() {
|
||||
images := gjson.GetBytes(body, "images")
|
||||
if images.Exists() {
|
||||
if !images.IsArray() {
|
||||
return fmt.Errorf("invalid images field type")
|
||||
hasExplicitImagesField := false
|
||||
if images := gjson.GetBytes(body, "images"); images.Exists() && images.Type != gjson.Null {
|
||||
hasExplicitImagesField = true
|
||||
if !images.IsArray() {
|
||||
return fmt.Errorf("invalid images field type")
|
||||
}
|
||||
for _, item := range images.Array() {
|
||||
imageURL, err := extractOpenAIImagesJSONInputURL(item, "images[]")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range images.Array() {
|
||||
if imageURL := strings.TrimSpace(item.Get("image_url").String()); imageURL != "" {
|
||||
req.InputImageURLs = append(req.InputImageURLs, imageURL)
|
||||
continue
|
||||
}
|
||||
if item.Get("file_id").Exists() {
|
||||
return fmt.Errorf("images[].file_id is not supported (use images[].image_url instead)")
|
||||
}
|
||||
if imageURL != "" {
|
||||
req.InputImageURLs = append(req.InputImageURLs, imageURL)
|
||||
}
|
||||
}
|
||||
if maskImageURL := strings.TrimSpace(gjson.GetBytes(body, "mask.image_url").String()); maskImageURL != "" {
|
||||
}
|
||||
if singleImage := gjson.GetBytes(body, "image"); singleImage.Exists() && singleImage.Type != gjson.Null {
|
||||
hasExplicitImagesField = true
|
||||
switch {
|
||||
case singleImage.IsArray():
|
||||
for _, item := range singleImage.Array() {
|
||||
imageURL, err := extractOpenAIImagesJSONInputURL(item, "image[]")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if imageURL != "" {
|
||||
req.InputImageURLs = append(req.InputImageURLs, imageURL)
|
||||
}
|
||||
}
|
||||
default:
|
||||
imageURL, err := extractOpenAIImagesJSONInputURL(singleImage, "image")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if imageURL != "" {
|
||||
req.InputImageURLs = append(req.InputImageURLs, imageURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
if mask := gjson.GetBytes(body, "mask"); mask.Exists() && mask.Type != gjson.Null {
|
||||
maskImageURL, err := extractOpenAIImagesJSONInputURL(mask, "mask")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if maskImageURL != "" {
|
||||
req.MaskImageURL = maskImageURL
|
||||
req.HasMask = true
|
||||
}
|
||||
if gjson.GetBytes(body, "mask.file_id").Exists() {
|
||||
return fmt.Errorf("mask.file_id is not supported (use mask.image_url instead)")
|
||||
}
|
||||
if markup := gjson.GetBytes(body, "markup"); markup.Exists() && markup.Type != gjson.Null {
|
||||
if !markup.IsObject() {
|
||||
return fmt.Errorf("invalid markup field type")
|
||||
}
|
||||
if markup := gjson.GetBytes(body, "markup"); markup.Exists() && markup.Type != gjson.Null {
|
||||
if !markup.IsObject() {
|
||||
return fmt.Errorf("invalid markup field type")
|
||||
}
|
||||
if markup.Get("file_id").Exists() {
|
||||
return fmt.Errorf("markup.file_id is not supported (use markup.image_url instead)")
|
||||
}
|
||||
req.MarkupImageURL = strings.TrimSpace(markup.Get("image_url").String())
|
||||
if req.MarkupImageURL == "" {
|
||||
return fmt.Errorf("markup.image_url is required")
|
||||
}
|
||||
if markup.Get("file_id").Exists() {
|
||||
return fmt.Errorf("markup.file_id is not supported (use markup.image_url instead)")
|
||||
}
|
||||
if len(req.InputImageURLs) == 0 {
|
||||
return fmt.Errorf("images[].image_url is required")
|
||||
req.MarkupImageURL = strings.TrimSpace(markup.Get("image_url").String())
|
||||
if req.MarkupImageURL == "" {
|
||||
req.MarkupImageURL = strings.TrimSpace(markup.Get("url").String())
|
||||
}
|
||||
if req.MarkupImageURL == "" {
|
||||
return fmt.Errorf("markup.image_url is required")
|
||||
}
|
||||
}
|
||||
if (req.IsEdits() || hasExplicitImagesField || req.MaskImageURL != "" || req.MarkupImageURL != "") && len(req.InputImageURLs) == 0 {
|
||||
return fmt.Errorf("images[].image_url is required")
|
||||
}
|
||||
req.HasNativeOptions = hasOpenAINativeImageOptions(func(path string) bool {
|
||||
return gjson.GetBytes(body, path).Exists()
|
||||
v := gjson.GetBytes(body, path)
|
||||
return v.Exists() && v.Type != gjson.Null
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func extractOpenAIImagesJSONInputURL(value gjson.Result, field string) (string, error) {
|
||||
if !value.Exists() || value.Type == gjson.Null {
|
||||
return "", nil
|
||||
}
|
||||
if value.Type == gjson.String {
|
||||
trimmed := strings.TrimSpace(value.String())
|
||||
if trimmed == "" {
|
||||
return "", fmt.Errorf("%s.image_url is required", field)
|
||||
}
|
||||
return trimmed, nil
|
||||
}
|
||||
if !value.IsObject() {
|
||||
return "", fmt.Errorf("invalid %s field type", field)
|
||||
}
|
||||
if value.Get("file_id").Exists() {
|
||||
return "", fmt.Errorf("%s.file_id is not supported (use %s.image_url instead)", field, field)
|
||||
}
|
||||
if imageURL := strings.TrimSpace(value.Get("image_url").String()); imageURL != "" {
|
||||
return imageURL, nil
|
||||
}
|
||||
if imageURL := strings.TrimSpace(value.Get("url").String()); imageURL != "" {
|
||||
return imageURL, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s.image_url is required", field)
|
||||
}
|
||||
|
||||
func parseOpenAIImagesMultipartRequest(body []byte, contentType string, req *OpenAIImagesRequest) error {
|
||||
_, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
@@ -529,7 +592,7 @@ func parseOpenAIImagesMultipartRequest(body []byte, contentType string, req *Ope
|
||||
}
|
||||
}
|
||||
|
||||
if len(req.Uploads) == 0 && req.IsEdits() {
|
||||
if len(req.Uploads) == 0 && (req.IsEdits() || req.MaskUpload != nil || req.MarkupUpload != nil) {
|
||||
return fmt.Errorf("image file is required")
|
||||
}
|
||||
return nil
|
||||
@@ -634,7 +697,7 @@ func classifyOpenAIImagesCapability(req *OpenAIImagesRequest) OpenAIImagesCapabi
|
||||
if req.Stream || req.N != 1 || req.HasMask || req.HasNativeOptions {
|
||||
return OpenAIImagesCapabilityNative
|
||||
}
|
||||
if req.IsEdits() && !req.Multipart {
|
||||
if (req.IsEdits() && !req.Multipart) || (!req.IsEdits() && req.HasImageInputs()) {
|
||||
return OpenAIImagesCapabilityNative
|
||||
}
|
||||
if req.ResponseFormat != "" && req.ResponseFormat != "b64_json" {
|
||||
|
||||
@@ -290,7 +290,7 @@ func TestGPTImage26InvalidNativeOptions(t *testing.T) {
|
||||
|
||||
func TestGPTImage26BillingWithoutDynamicPricing(t *testing.T) {
|
||||
svc := &BillingService{}
|
||||
for _, model := range []string{"gpt-image-2.6-flare", "gpt-image-2.6-sunburst"} {
|
||||
for _, model := range []string{"gpt-image-2.6", "gpt-image-2.6-flare", "gpt-image-2.6-sunburst", "gpt-image-2.6-flare-2026-11-06"} {
|
||||
p, err := svc.GetModelPricing(model)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 5e-6, p.InputPricePerToken)
|
||||
@@ -301,3 +301,137 @@ func TestGPTImage26BillingWithoutDynamicPricing(t *testing.T) {
|
||||
require.Zero(t, p.OutputPricePerToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGPTImage26UnifiedGenerationsWithImageInputs(t *testing.T) {
|
||||
for _, model := range []string{"gpt-image-2.6", "gpt-image-2.6-flare", "gpt-image-2.6-sunburst", "gpt-image-2.6-flare-2026-11-06"} {
|
||||
for _, multipartInput := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/multipart=%t", model, multipartInput), func(t *testing.T) {
|
||||
body := []byte(fmt.Sprintf(`{"model":%q,"prompt":"combine and edit","complexity":"high","quality":"high","size":"1024x1024","images":[{"image_url":"data:image/png;base64,aW1nMQ=="},{"url":"https://example.com/ref2.png"}],"mask":{"image_url":"data:image/png;base64,bWFzaw=="},"markup":{"image_url":"data:image/png;base64,bWFya3Vw"}}`, model))
|
||||
contentType := "application/json"
|
||||
if multipartInput {
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
for key, value := range map[string]string{
|
||||
"model": model, "prompt": "combine and edit", "complexity": "high", "quality": "high", "size": "1024x1024",
|
||||
} {
|
||||
require.NoError(t, writer.WriteField(key, value))
|
||||
}
|
||||
for _, partSpec := range []struct{ field, content string }{
|
||||
{"image[]", "img1"},
|
||||
{"image[]", "img2"},
|
||||
{"mask", "mask"},
|
||||
{"markup", "markup"},
|
||||
} {
|
||||
header := textproto.MIMEHeader{}
|
||||
header.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename="in.png"`, partSpec.field))
|
||||
header.Set("Content-Type", "image/png")
|
||||
part, err := writer.CreatePart(header)
|
||||
require.NoError(t, err)
|
||||
_, err = part.Write([]byte(partSpec.content))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.NoError(t, writer.Close())
|
||||
body, contentType = buf.Bytes(), writer.FormDataContentType()
|
||||
}
|
||||
|
||||
c, _ := newOpenAIImagesTestContext(t, body)
|
||||
c.Request.Header.Set("Content-Type", contentType)
|
||||
upstream := &httpUpstreamRecorder{resp: openAIImagesJSONResponse()}
|
||||
svc := newOpenAIImagesTestService(upstream)
|
||||
|
||||
parsed, err := svc.ParseOpenAIImagesRequest(c, body)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, OpenAIImagesCapabilityNative, parsed.RequiredCapability)
|
||||
require.Len(t, gjson.GetBytes(parsed.ModerationBody(), "images").Array(), 4)
|
||||
|
||||
result, err := svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "/backend-api/codex/images/generations", result.UpstreamEndpoint)
|
||||
require.Len(t, gjson.GetBytes(upstream.lastBody, "images").Array(), 2)
|
||||
require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "mask.image_url").String())
|
||||
require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "markup.image_url").String())
|
||||
require.Equal(t, "high", gjson.GetBytes(upstream.lastBody, "complexity").String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for _, invalidBody := range []string{
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[]}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":"bad"}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"file_id":"file-1"}]}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="},{}]}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":["data:image/png;base64,AA==",""]}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="}],"mask":{}}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="}],"mask":""}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","mask":{"image_url":"data:image/png;base64,AA=="}}`,
|
||||
`{"model":"gpt-image-2.6-flare","prompt":"edit","markup":{"image_url":"data:image/png;base64,AA=="}}`,
|
||||
} {
|
||||
t.Run(invalidBody, func(t *testing.T) {
|
||||
c, _ := newOpenAIImagesTestContext(t, []byte(invalidBody))
|
||||
_, err := newOpenAIImagesTestService(nil).ParseOpenAIImagesRequest(c, []byte(invalidBody))
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
nullOptionalBody := []byte(`{"prompt":"draw a cat","images":null,"mask":null,"markup":null}`)
|
||||
cNull, _ := newOpenAIImagesTestContext(t, nullOptionalBody)
|
||||
parsedNull, err := newOpenAIImagesTestService(nil).ParseOpenAIImagesRequest(cNull, nullOptionalBody)
|
||||
require.NoError(t, err)
|
||||
require.False(t, parsedNull.HasMask)
|
||||
require.False(t, parsedNull.HasImageInputs())
|
||||
require.Equal(t, OpenAIImagesCapabilityBasic, parsedNull.RequiredCapability)
|
||||
}
|
||||
|
||||
func TestGPTImage26EditsFallsForwardToUnifiedGenerationsWhenEditsUnavailable(t *testing.T) {
|
||||
for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} {
|
||||
t.Run(fmt.Sprint(status), func(t *testing.T) {
|
||||
var paths []string
|
||||
var lastPayload []byte
|
||||
upstream := &codexModelsHTTPUpstreamStub{do: func(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
paths = append(paths, req.URL.Path)
|
||||
lastPayload, _ = io.ReadAll(req.Body)
|
||||
if len(paths) == 1 {
|
||||
return &http.Response{
|
||||
StatusCode: status,
|
||||
Header: http.Header{},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"edits endpoint retired"}}`)),
|
||||
}, nil
|
||||
}
|
||||
return openAIImagesJSONResponse(), nil
|
||||
}}
|
||||
body := []byte(`{"model":"gpt-image-2.6-flare","prompt":"edit","complexity":"low","images":[{"image_url":"data:image/png;base64,AA=="}],"markup":{"image_url":"data:image/png;base64,bWFya3Vw"}}`)
|
||||
c, _ := newOpenAIImagesTestContext(t, body)
|
||||
c.Request.URL.Path = openAIImagesEditsEndpoint
|
||||
svc := newOpenAIImagesTestService(upstream)
|
||||
parsed, err := svc.ParseOpenAIImagesRequest(c, body)
|
||||
require.NoError(t, err)
|
||||
result, err := svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, []string{"/backend-api/codex/images/edits", "/backend-api/codex/images/generations"}, paths)
|
||||
require.Len(t, gjson.GetBytes(lastPayload, "images").Array(), 1)
|
||||
require.Equal(t, "data:image/png;base64,bWFya3Vw", gjson.GetBytes(lastPayload, "markup.image_url").String())
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("model_not_found_404_does_not_retry_generations_on_same_account", func(t *testing.T) {
|
||||
var paths []string
|
||||
upstream := &codexModelsHTTPUpstreamStub{do: func(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
|
||||
paths = append(paths, req.URL.Path)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusNotFound,
|
||||
Header: http.Header{},
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"model_not_found","message":"The model 'gpt-image-2.6-flare' does not exist"}}`)),
|
||||
}, nil
|
||||
}}
|
||||
body := []byte(`{"model":"gpt-image-2.6-flare","prompt":"edit","images":[{"image_url":"data:image/png;base64,AA=="}]}`)
|
||||
c, _ := newOpenAIImagesTestContext(t, body)
|
||||
c.Request.URL.Path = openAIImagesEditsEndpoint
|
||||
svc := newOpenAIImagesTestService(upstream)
|
||||
parsed, err := svc.ParseOpenAIImagesRequest(c, body)
|
||||
require.NoError(t, err)
|
||||
_, err = svc.ForwardImages(context.Background(), c, directImagesTestAccount(), body, parsed, "")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, []string{"/backend-api/codex/images/edits"}, paths)
|
||||
})
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
)
|
||||
|
||||
type openAIImagesForceResponsesContextKey struct{}
|
||||
type openAIImagesForceUnifiedGenerationsContextKey struct{}
|
||||
|
||||
func withOpenAIImagesForceResponses(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, openAIImagesForceResponsesContextKey{}, true)
|
||||
@@ -27,11 +28,30 @@ func isOpenAIImagesForceResponses(ctx context.Context) bool {
|
||||
return forced
|
||||
}
|
||||
|
||||
func withOpenAIImagesForceUnifiedGenerations(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, openAIImagesForceUnifiedGenerationsContextKey{}, true)
|
||||
}
|
||||
|
||||
func isOpenAIImagesForceUnifiedGenerations(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
return false
|
||||
}
|
||||
forced, _ := ctx.Value(openAIImagesForceUnifiedGenerationsContextKey{}).(bool)
|
||||
return forced
|
||||
}
|
||||
|
||||
func isGPTImage26Model(model string) bool {
|
||||
normalized := strings.ToLower(strings.TrimSpace(model))
|
||||
return normalized == "gpt-image-2.6" || strings.HasPrefix(normalized, "gpt-image-2.6-")
|
||||
}
|
||||
|
||||
// 显式列出已接入的模型,不把未来模型或未知快照自动送到直调端点。
|
||||
func usesCodexDirectImages(model string) bool {
|
||||
if isGPTImage26Model(model) {
|
||||
return true
|
||||
}
|
||||
switch strings.TrimSpace(model) {
|
||||
case "gpt-image-1.5", "gpt-image-2",
|
||||
"gpt-image-2.6-flare", "gpt-image-2.6-sunburst",
|
||||
"gpt-image-2.5-flare", "gpt-image-2.5-sunburst",
|
||||
"gpt-image-2.5-flare-2026-09-08", "gpt-image-2.5-sunburst-2026-09-08":
|
||||
return true
|
||||
@@ -43,16 +63,15 @@ func usesCodexDirectImages(model string) bool {
|
||||
// Codex Responses binds image_generation to an internal model and cannot
|
||||
// preserve the requested 2.6 model. Do not fall back to that bridge for 2.6.
|
||||
func requiresCodexDirectImages(model string) bool {
|
||||
switch strings.TrimSpace(model) {
|
||||
case "gpt-image-2.6-flare", "gpt-image-2.6-sunburst":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return isGPTImage26Model(model)
|
||||
}
|
||||
|
||||
// 正式转发与后台测试共用同一份端点选择和请求构造。
|
||||
func buildOpenAIImagesOAuthPayload(parsed *OpenAIImagesRequest, model string) ([]byte, string, error) {
|
||||
return buildOpenAIImagesOAuthPayloadForContext(context.Background(), parsed, model)
|
||||
}
|
||||
|
||||
func buildOpenAIImagesOAuthPayloadForContext(ctx context.Context, parsed *OpenAIImagesRequest, model string) ([]byte, string, error) {
|
||||
if parsed == nil {
|
||||
return nil, "", fmt.Errorf("parsed images request is required")
|
||||
}
|
||||
@@ -109,8 +128,10 @@ func buildOpenAIImagesOAuthPayload(parsed *OpenAIImagesRequest, model string) ([
|
||||
}
|
||||
|
||||
endpoint := "/images/generations"
|
||||
if parsed.IsEdits() {
|
||||
if parsed.IsEdits() && !isOpenAIImagesForceUnifiedGenerations(ctx) {
|
||||
endpoint = "/images/edits"
|
||||
}
|
||||
if parsed.IsEdits() || parsed.HasImageInputs() {
|
||||
images := make([]map[string]string, 0, len(parsed.InputImageURLs)+len(parsed.Uploads))
|
||||
for _, imageURL := range parsed.InputImageURLs {
|
||||
if imageURL = strings.TrimSpace(imageURL); imageURL != "" {
|
||||
|
||||
@@ -408,7 +408,7 @@ func buildOpenAIImagesResponsesRequest(parsed *OpenAIImagesRequest, toolModel st
|
||||
req, _ = sjson.SetRawBytes(req, "input", input)
|
||||
|
||||
action := "generate"
|
||||
if parsed.IsEdits() {
|
||||
if parsed.IsEdits() || len(inputImages) > 0 {
|
||||
action = "edit"
|
||||
}
|
||||
tool := []byte(`{"type":"image_generation","action":"","model":""}`)
|
||||
@@ -1872,7 +1872,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth(
|
||||
var responsesBody []byte
|
||||
var targetURL string
|
||||
if direct {
|
||||
responsesBody, targetURL, err = buildOpenAIImagesOAuthPayload(parsed, upstreamModel)
|
||||
responsesBody, targetURL, err = buildOpenAIImagesOAuthPayloadForContext(ctx, parsed, upstreamModel)
|
||||
} else {
|
||||
responsesBody, err = buildOpenAIImagesResponsesRequest(parsed, upstreamModel)
|
||||
targetURL = chatgptCodexURL
|
||||
@@ -1928,7 +1928,12 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth(
|
||||
respBody := s.readUpstreamErrorBody(resp)
|
||||
_ = resp.Body.Close()
|
||||
respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody)
|
||||
if direct && !requiresCodexDirectImages(upstreamModel) && (resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusMethodNotAllowed) {
|
||||
endpointUnavailable := resp.StatusCode == http.StatusMethodNotAllowed ||
|
||||
(resp.StatusCode == http.StatusNotFound && !isOpenAICompatibleModelNotFoundBody(respBody))
|
||||
if direct && parsed.IsEdits() && !isOpenAIImagesForceUnifiedGenerations(ctx) && endpointUnavailable {
|
||||
return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceUnifiedGenerations(ctx), c, account, parsed, channelMappedModel)
|
||||
}
|
||||
if direct && !requiresCodexDirectImages(upstreamModel) && endpointUnavailable {
|
||||
return s.forwardOpenAIImagesOAuth(withOpenAIImagesForceResponses(ctx), c, account, parsed, channelMappedModel)
|
||||
}
|
||||
if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) {
|
||||
|
||||
@@ -607,15 +607,6 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
return err
|
||||
}
|
||||
}
|
||||
// HTTP cannot resolve an opaque parent; only this connection's replay can.
|
||||
if parent := currentBridgePayload.previousResponseID; parent != "" &&
|
||||
(parent != bridgeLastResponseID || !bridgeReplayInputExists || len(bridgeReplayInput) == 0) {
|
||||
return NewOpenAIWSClientCloseError(
|
||||
coderws.StatusPolicyViolation,
|
||||
"previous_response_id cannot be resolved on this connection; resend full input without previous_response_id",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
if hooks != nil && hooks.BeforeTurn != nil {
|
||||
if err := hooks.BeforeTurn(turn); err != nil {
|
||||
return err
|
||||
@@ -652,6 +643,28 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
|
||||
if needsBridgeReplay && historyLost {
|
||||
return NewResponsesWSBridgeHistoryCloseError()
|
||||
}
|
||||
// HTTP cannot resolve an opaque parent unless this connection holds its
|
||||
// replay chain, the platform handles continuations natively on HTTP bridge,
|
||||
// or turn 1 sticky-routed to the API-key account bound to that response ID.
|
||||
if parent := currentBridgePayload.previousResponseID; parent != "" {
|
||||
resolvedInConnection := parent == bridgeLastResponseID && bridgeReplayInputExists && len(bridgeReplayInput) > 0
|
||||
resolvedBoundAPIKey := turn == 1 &&
|
||||
account != nil &&
|
||||
account.IsOpenAIApiKey() &&
|
||||
!s.isOpenAIWSStoreDisabledInRequestRaw(currentBridgePayload.payloadRaw, account) &&
|
||||
stateStore != nil &&
|
||||
func() bool {
|
||||
boundAccountID, getErr := stateStore.GetResponseAccount(ctx, groupID, parent)
|
||||
return getErr == nil && boundAccountID == account.ID
|
||||
}()
|
||||
if !resolvedInConnection && !resolvedBoundAPIKey && (account == nil || account.Platform != PlatformGrok) {
|
||||
return NewOpenAIWSClientCloseError(
|
||||
coderws.StatusPolicyViolation,
|
||||
"previous_response_id cannot be resolved on this connection; resend full input without previous_response_id",
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
if !needsBridgeReplay {
|
||||
// A self-contained request replaces the previous replay chain.
|
||||
bridgeReplayInput, bridgeAccountFailoverInput = nil, nil
|
||||
|
||||
@@ -114,4 +114,77 @@ func TestOpenAIWSHTTPBridgeRejectsUnresolvedPreviousResponseID(t *testing.T) {
|
||||
require.Len(t, upstream.bodies, priorTurns, "never POST a delta whose parent cannot be reconstructed")
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("bound_apikey_cross_connection_turn1_allowed_but_store_false_rejected", func(t *testing.T) {
|
||||
upstream := &httpUpstreamRecorder{
|
||||
responses: []*http.Response{
|
||||
{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
|
||||
Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_next\",\"output\":[]}}\n\n")),
|
||||
},
|
||||
},
|
||||
}
|
||||
cfg := &config.Config{}
|
||||
cfg.Gateway.OpenAIWS.Enabled = true
|
||||
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
|
||||
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
|
||||
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
|
||||
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
|
||||
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
|
||||
svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg)}
|
||||
account := &Account{
|
||||
ID: 9006, Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge},
|
||||
Status: StatusActive, Schedulable: true, Concurrency: 1,
|
||||
}
|
||||
require.NoError(t, svc.getOpenAIWSStateStore().BindResponseAccount(context.Background(), 0, "resp_bound", account.ID, time.Hour))
|
||||
|
||||
runTurn1 := func(frame string) (int, coderws.StatusCode) {
|
||||
wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := coderws.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer func() { _ = conn.CloseNow() }()
|
||||
readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
_, firstMessage, err := conn.Read(readCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = r.Clone(r.Context())
|
||||
proxyErr := svc.ProxyResponsesWebSocketFromClient(r.Context(), c, conn, account, "sk-test", firstMessage, nil)
|
||||
var closeErr *OpenAIWSClientCloseError
|
||||
if errors.As(proxyErr, &closeErr) {
|
||||
_ = conn.Close(closeErr.StatusCode(), closeErr.Reason())
|
||||
}
|
||||
}))
|
||||
defer wsServer.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = client.CloseNow() }()
|
||||
require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(frame)))
|
||||
_, event, readErr := client.Read(ctx)
|
||||
if readErr != nil {
|
||||
return len(upstream.bodies), coderws.CloseStatus(readErr)
|
||||
}
|
||||
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
|
||||
_ = client.Close(coderws.StatusNormalClosure, "done")
|
||||
return len(upstream.bodies), coderws.StatusNormalClosure
|
||||
}
|
||||
|
||||
posts, status := runTurn1(`{"type":"response.create","model":"gpt-6.1-sol","store":false,"previous_response_id":"resp_bound","input":[{"role":"user","content":"delta"}]}`)
|
||||
require.Equal(t, coderws.StatusPolicyViolation, status)
|
||||
require.Zero(t, posts)
|
||||
|
||||
posts, status = runTurn1(`{"type":"response.create","model":"gpt-6.1-sol","previous_response_id":"resp_bound","input":[{"role":"user","content":"delta"}]}`)
|
||||
require.Equal(t, coderws.StatusNormalClosure, status)
|
||||
require.Equal(t, 1, posts)
|
||||
})
|
||||
}
|
||||
@@ -1773,7 +1773,7 @@ func (s *PricingService) matchOpenAIModel(model string) *LiteLLMModelPricing {
|
||||
|
||||
// Remote price mirrors can lag new releases. Never bill GPT Image 2.5 / 2.6
|
||||
// using the older image model's rates when its entry is absent.
|
||||
if model == "gpt-image-2.6-flare" || model == "gpt-image-2.6-sunburst" {
|
||||
if isGPTImage26Model(model) {
|
||||
return openAIGPTImage25FallbackPricing
|
||||
}
|
||||
for _, imageModel := range []string{"gpt-image-2.5-flare", "gpt-image-2.5-sunburst"} {
|
||||
|
||||
Reference in new issue
Block a user