Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions constant/context_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ const (
// and for adaptors that build official endpoints themselves.
ContextKeyUpstreamRequestOrigin ContextKey = "upstream_request_origin"

// ContextKeySubscriptionRoute holds the *relaycommon.SubscriptionRoute the
// distributor records when it steers a request to a binding's dedicated
// group.
ContextKeySubscriptionRoute ContextKey = "subscription_route"
// ContextKeyUpstreamRateLimitHeaders holds the usage-limit headers of the
// last upstream answer of a subscription OAuth channel (http.Header).
ContextKeyUpstreamRateLimitHeaders ContextKey = "upstream_rate_limit_headers"

ContextKeyAutoGroup ContextKey = "auto_group"
ContextKeyAutoGroupIndex ContextKey = "auto_group_index"
ContextKeyAutoGroupRetryIndex ContextKey = "auto_group_retry_index"
Expand Down
13 changes: 11 additions & 2 deletions controller/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {

retryParam := &service.RetryParam{
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
TokenGroup: service.RelayRetryGroup(relayInfo),
ModelName: relayInfo.OriginModelName,
RequestPath: c.Request.URL.Path,
Retry: common.GetPointer(0),
Expand Down Expand Up @@ -227,6 +227,15 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
service.RecordPolicyFailure(c, channel.Id, newAPIError, decision)
processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError, relayInfo)

routeErr, fellBack := service.HandleSubscriptionRouteFailure(c, relayInfo, retryParam, newAPIError, helper.ResponseContentStarted(c))
if fellBack {
continue
}
if routeErr != newAPIError {
newAPIError = routeErr
relayInfo.LastError = routeErr
break
}
if decision.Action != "retry" {
break
}
Expand Down Expand Up @@ -533,7 +542,7 @@ func executeTaskSubmissionWith(

retryParam := &service.RetryParam{
Ctx: c,
TokenGroup: relayInfo.TokenGroup,
TokenGroup: service.RelayRetryGroup(relayInfo),
ModelName: relayInfo.OriginModelName,
RequestPath: c.Request.URL.Path,
Retry: common.GetPointer(0),
Expand Down
6 changes: 6 additions & 0 deletions controller/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,9 @@ func AdminCreateSubscriptionPlan(c *gin.Context) {
if req.Plan.AllowWalletOverflow == nil {
req.Plan.AllowWalletOverflow = common.GetPointer(true)
}
if req.Plan.FallbackToSharedPoolOnLimit == nil {
req.Plan.FallbackToSharedPoolOnLimit = common.GetPointer(false)
}
if req.Plan.DurationUnit == "" {
req.Plan.DurationUnit = model.SubscriptionDurationMonth
}
Expand Down Expand Up @@ -315,6 +318,9 @@ func AdminUpdateSubscriptionPlan(c *gin.Context) {
if req.Plan.AllowWalletOverflow != nil {
updateMap["allow_wallet_overflow"] = *req.Plan.AllowWalletOverflow
}
if req.Plan.FallbackToSharedPoolOnLimit != nil {
updateMap["fallback_to_shared_pool_on_limit"] = *req.Plan.FallbackToSharedPoolOnLimit
}
if err := tx.Model(&model.SubscriptionPlan{}).Where("id = ?", id).Updates(updateMap).Error; err != nil {
return err
}
Expand Down
9 changes: 9 additions & 0 deletions i18n/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ const (
MsgRelayRetryGetChannelFailed = "relay.retry_get_channel_failed"
MsgRelayRetryNoAvailableChannel = "relay.retry_no_available_channel"
MsgRelayAccessTokenUnsupported = "relay.access_token_unsupported"

MsgQuotaBoundSubscriptionInsufficient = "quota.bound_subscription_insufficient"
MsgRelaySubscriptionAccountLimited = "relay.subscription_account_limited"
MsgRelaySubscriptionAccountLimitedNoReset = "relay.subscription_account_limited_no_reset"
MsgRelaySubscriptionAccountLimitedGenericReset = "relay.subscription_account_limited_generic_reset"
MsgRelaySubscriptionAccountLimitedGeneric = "relay.subscription_account_limited_generic"
MsgRelaySubscriptionWindow5h = "relay.subscription_window_5h"
MsgRelaySubscriptionWindow7d = "relay.subscription_window_7d"
MsgRelaySubscriptionWindow7dOi = "relay.subscription_window_7d_oi"
)

// Emails and the name of the token created at registration, in the
Expand Down
8 changes: 8 additions & 0 deletions i18n/locales/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ distributor.invalid_request_parse_model: "unable to parse model"
quota.user_insufficient: "Insufficient user quota, remaining quota: {{.Remaining}}"
quota.pre_consume_insufficient: "Not enough quota to pre-consume for this request: {{.Remaining}} remaining, {{.Required}} required"
quota.subscription_insufficient: "Subscription quota is insufficient or no subscription is configured: {{.Error}}"
quota.bound_subscription_insufficient: "The subscription bound to this account does not have enough quota: {{.Remaining}} remaining, {{.Required}} required. Models of the bound account are billed to that subscription only."
relay.model_price_not_configured: "Model {{.Model}} has not been priced by the administrator yet. Please contact the site administrator to enable this model."
relay.model_price_not_configured_admin: "Model {{.Model}} price not configured. Go to System Settings → Operation Settings to enable self-use mode, or configure the model price in System Settings → Group & Model Pricing."
relay.task_usage_price_unsupported: "Model {{.Model}} uses a task usage expression; configure ordinary relay pricing and separate plugin billing expressions"
Expand All @@ -41,6 +42,13 @@ relay.group_upstream_saturated: "The upstream of the current group is at capacit
relay.retry_get_channel_failed: "Failed to get available channel for model {{.Model}} under group {{.Group}} (retry): {{.Error}}"
relay.retry_no_available_channel: "No available channel for model {{.Model}} under group {{.Group}} (retry)"
relay.access_token_unsupported: "Access tokens are not supported here"
relay.subscription_account_limited: "The subscription account has used up its {{.Window}} limit; it resets at {{.ResetAt}}"
relay.subscription_account_limited_no_reset: "The subscription account has used up its {{.Window}} limit; please try again later"
relay.subscription_account_limited_generic_reset: "The subscription account has used up its usage limit; it resets at {{.ResetAt}}"
relay.subscription_account_limited_generic: "The subscription account has used up its usage limit; please try again later"
relay.subscription_window_5h: "5-hour"
relay.subscription_window_7d: "7-day"
relay.subscription_window_7d_oi: "7-day Fable"

# Emails and the name of the token created at registration
user.default_token_name: "{{.Username}}'s initial token"
Expand Down
8 changes: 8 additions & 0 deletions i18n/locales/zh-CN.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ distributor.invalid_request_parse_model: "无法解析模型"
quota.user_insufficient: "用户额度不足, 剩余额度: {{.Remaining}}"
quota.pre_consume_insufficient: "预扣费额度失败, 用户剩余额度: {{.Remaining}}, 需要预扣费额度: {{.Required}}"
quota.subscription_insufficient: "订阅额度不足或未配置订阅: {{.Error}}"
quota.bound_subscription_insufficient: "绑定账号的订阅额度不足:剩余 {{.Remaining}},需要 {{.Required}}。绑定账号的模型只从该订阅扣费"
relay.model_price_not_configured: "模型 {{.Model}} 的价格尚未由管理员配置,暂时无法使用,请联系站点管理员开启该模型;Model {{.Model}} has not been priced by the administrator yet. Please contact the site administrator to enable this model."
relay.model_price_not_configured_admin: "模型 {{.Model}} 的价格未配置。请前往「系统设置 → 运营设置」开启自用模式,或在「系统设置 → 分组与模型定价设置」中为该模型配置价格;Model {{.Model}} price not configured. Go to System Settings → Operation Settings to enable self-use mode, or configure the model price in System Settings → Group & Model Pricing."
relay.task_usage_price_unsupported: "模型 {{.Model}} 使用了任务用量表达式;请为普通转发配置常规定价,并为插件单独配置计费表达式"
Expand All @@ -42,6 +43,13 @@ relay.group_upstream_saturated: "当前分组上游负载已饱和,请稍后
relay.retry_get_channel_failed: "获取分组 {{.Group}} 下模型 {{.Model}} 的可用渠道失败(retry): {{.Error}}"
relay.retry_no_available_channel: "分组 {{.Group}} 下模型 {{.Model}} 的可用渠道不存在(retry)"
relay.access_token_unsupported: "暂不支持使用 access token"
relay.subscription_account_limited: "订阅账号的{{.Window}}额度已用尽,将于 {{.ResetAt}} 重置"
relay.subscription_account_limited_no_reset: "订阅账号的{{.Window}}额度已用尽,请稍后再试"
relay.subscription_account_limited_generic_reset: "订阅账号的用量额度已用尽,将于 {{.ResetAt}} 重置"
relay.subscription_account_limited_generic: "订阅账号的用量额度已用尽,请稍后再试"
relay.subscription_window_5h: " 5 小时"
relay.subscription_window_7d: " 7 天"
relay.subscription_window_7d_oi: " Fable 7 天"

# Emails and the name of the token created at registration
user.default_token_name: "{{.Username}}的初始令牌"
Expand Down
8 changes: 8 additions & 0 deletions i18n/locales/zh-TW.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ distributor.invalid_request_parse_model: "無法解析模型"
quota.user_insufficient: "使用者額度不足,剩餘額度:{{.Remaining}}"
quota.pre_consume_insufficient: "預扣費額度失敗,使用者剩餘額度:{{.Remaining}},需要預扣費額度:{{.Required}}"
quota.subscription_insufficient: "訂閱額度不足或未設定訂閱:{{.Error}}"
quota.bound_subscription_insufficient: "綁定帳號的訂閱額度不足:剩餘 {{.Remaining}},需要 {{.Required}}。綁定帳號的模型只從該訂閱扣費"
relay.model_price_not_configured: "模型 {{.Model}} 的價格尚未由管理員設定,暫時無法使用,請聯絡站點管理員開啟該模型"
relay.model_price_not_configured_admin: "模型 {{.Model}} 的價格未設定。請前往「系統設定 → 營運設定」開啟自用模式,或在「系統設定 → 分組與模型定價設定」中為該模型設定價格"
relay.task_usage_price_unsupported: "模型 {{.Model}} 使用了任務用量表達式;請為一般轉發設定常規定價,並為插件單獨設定計費表達式"
Expand All @@ -42,6 +43,13 @@ relay.group_upstream_saturated: "目前分組上游負載已飽和,請稍後
relay.retry_get_channel_failed: "獲取分組 {{.Group}} 下模型 {{.Model}} 的可用管道失敗(retry):{{.Error}}"
relay.retry_no_available_channel: "分組 {{.Group}} 下模型 {{.Model}} 的可用管道不存在(retry)"
relay.access_token_unsupported: "暫不支援使用 access token"
relay.subscription_account_limited: "訂閱帳號的{{.Window}}額度已用盡,將於 {{.ResetAt}} 重置"
relay.subscription_account_limited_no_reset: "訂閱帳號的{{.Window}}額度已用盡,請稍後再試"
relay.subscription_account_limited_generic_reset: "訂閱帳號的用量額度已用盡,將於 {{.ResetAt}} 重置"
relay.subscription_account_limited_generic: "訂閱帳號的用量額度已用盡,請稍後再試"
relay.subscription_window_5h: " 5 小時"
relay.subscription_window_7d: " 7 天"
relay.subscription_window_7d_oi: " Fable 7 天"

# Emails and the name of the token created at registration
user.default_token_name: "{{.Username}}的初始令牌"
Expand Down
21 changes: 15 additions & 6 deletions middleware/distributor.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/jsplugin"
relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/relaykit/types"
Expand Down Expand Up @@ -97,12 +98,20 @@ func Distribute() func(c *gin.Context) {
}
// A user whose subscription is bound to an OAuth channel account
// has that channel's models served from the binding's dedicated
// group, whatever group the token or playground asked for; every
// other model keeps the group chosen above.
if group, ok := model.ResolveSubscriptionRouteGroup(c.GetInt("id"), modelRequest.Model, common.GetTimestamp()); ok {
if previous := common.GetContextKeyString(c, constant.ContextKeyUsingGroup); previous != group {
common.SetContextKey(c, constant.ContextKeyUsingGroup, group)
logger.LogDebug(c, "subscription binding routes model %s from group %s to the dedicated group %s", modelRequest.Model, previous, group)
// group, whatever group the token or playground asked for, and
// billed to that subscription only; every other model keeps the
// group chosen above.
if binding, ok := model.ResolveSubscriptionRoute(c.GetInt("id"), modelRequest.Model, common.GetTimestamp()); ok {
previous := common.GetContextKeyString(c, constant.ContextKeyUsingGroup)
common.SetContextKey(c, constant.ContextKeySubscriptionRoute, &relaycommon.SubscriptionRoute{
SubscriptionId: binding.SubscriptionId,
ChannelId: binding.ChannelId,
Group: binding.Group,
OriginalGroup: previous,
})
if previous != binding.Group {
common.SetContextKey(c, constant.ContextKeyUsingGroup, binding.Group)
logger.LogDebug(c, "subscription binding routes model %s from group %s to the dedicated group %s", modelRequest.Model, previous, binding.Group)
}
}
}
Expand Down
46 changes: 32 additions & 14 deletions middleware/distributor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/pkg/jsplugin"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/setting"
"github.com/QuantumNous/new-api/setting/model_setting"
Expand Down Expand Up @@ -484,10 +485,13 @@ func setupSubscriptionRouteDistributeTest(t *testing.T) {
model.InitChannelCache()
}

func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string, modelName string) (string, int) {
// serveSubscriptionRouteRequest returns the group and channel the distributor
// chose and the route it recorded for billing (nil when not steered).
func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string, modelName string) (string, int, *relaycommon.SubscriptionRoute) {
t.Helper()
var gotGroup string
var gotChannel int
var gotRoute *relaycommon.SubscriptionRoute
router := gin.New()
router.POST("/v1/chat/completions", RequestId(), func(c *gin.Context) {
c.Set("id", userId)
Expand All @@ -496,14 +500,15 @@ func serveSubscriptionRouteRequest(t *testing.T, userId int, tokenGroup string,
}, Distribute(), func(c *gin.Context) {
gotGroup = common.GetContextKeyString(c, constant.ContextKeyUsingGroup)
gotChannel = common.GetContextKeyInt(c, constant.ContextKeyChannelId)
gotRoute, _ = common.GetContextKeyType[*relaycommon.SubscriptionRoute](c, constant.ContextKeySubscriptionRoute)
c.Status(http.StatusNoContent)
})
request := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(fmt.Sprintf(`{"model":%q}`, modelName)))
request.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusNoContent, recorder.Code, recorder.Body.String())
return gotGroup, gotChannel
return gotGroup, gotChannel, gotRoute
}

func TestDistributeRoutesBoundUsersModelsToTheDedicatedGroup(t *testing.T) {
Expand All @@ -516,39 +521,52 @@ func TestDistributeRoutesBoundUsersModelsToTheDedicatedGroup(t *testing.T) {
modelName string
wantGroup string
wantChannel int
// group recorded as the fallback target; "" when the request is not
// steered and so not billed to the bound subscription
wantOriginal string
}{
{"bound user, model on the bound channel", 10, "default", "claude-x", "claude-ch1", 1},
{"bound user, model not on the bound channel", 10, "default", "gpt-x", "default", 2},
{"binding wins over a token pinned to another group", 10, "vip", "claude-x", "claude-ch1", 1},
{"binding wins over Auto", 10, "auto", "claude-x", "claude-ch1", 1},
{"Auto still serves the other models", 10, "auto", "gpt-x", "auto", 2},
{"user without a binding", 11, "default", "claude-x", "default", 4},
{"expired binding", 12, "default", "claude-x", "default", 4},
{"cancelled binding", 13, "default", "claude-x", "default", 4},
{"bound user, model on the bound channel", 10, "default", "claude-x", "claude-ch1", 1, "default"},
{"bound user, model not on the bound channel", 10, "default", "gpt-x", "default", 2, ""},
{"binding wins over a token pinned to another group", 10, "vip", "claude-x", "claude-ch1", 1, "vip"},
{"binding wins over Auto", 10, "auto", "claude-x", "claude-ch1", 1, "auto"},
{"token already in the dedicated group is still billed to the binding", 10, "claude-ch1", "claude-x", "claude-ch1", 1, "claude-ch1"},
{"Auto still serves the other models", 10, "auto", "gpt-x", "auto", 2, ""},
{"user without a binding", 11, "default", "claude-x", "default", 4, ""},
{"expired binding", 12, "default", "claude-x", "default", 4, ""},
{"cancelled binding", 13, "default", "claude-x", "default", 4, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gotGroup, gotChannel := serveSubscriptionRouteRequest(t, tc.userId, tc.tokenGroup, tc.modelName)
gotGroup, gotChannel, gotRoute := serveSubscriptionRouteRequest(t, tc.userId, tc.tokenGroup, tc.modelName)
assert.Equal(t, tc.wantGroup, gotGroup)
assert.Equal(t, tc.wantChannel, gotChannel)
if tc.wantOriginal == "" {
assert.Nil(t, gotRoute)
return
}
require.NotNil(t, gotRoute)
assert.Equal(t, tc.wantOriginal, gotRoute.OriginalGroup)
assert.Equal(t, "claude-ch1", gotRoute.Group)
assert.Equal(t, 1, gotRoute.ChannelId)
assert.Positive(t, gotRoute.SubscriptionId)
})
}
}

func TestDistributeStopsRoutingOnceTheBindingCacheIsInvalidated(t *testing.T) {
setupSubscriptionRouteDistributeTest(t)

group, channel := serveSubscriptionRouteRequest(t, 10, "default", "claude-x")
group, channel, _ := serveSubscriptionRouteRequest(t, 10, "default", "claude-x")
assert.Equal(t, "claude-ch1", group)
assert.Equal(t, 1, channel)

require.NoError(t, model.DB.Model(&model.UserSubscription{}).Where("user_id = ?", 10).Update("bound_channel_id", 0).Error)
group, channel = serveSubscriptionRouteRequest(t, 10, "default", "claude-x")
group, channel, _ = serveSubscriptionRouteRequest(t, 10, "default", "claude-x")
assert.Equal(t, "claude-ch1", group, "the cached binding still routes")
assert.Equal(t, 1, channel)

model.InvalidateSubscriptionRouteBindingCache(10)
group, channel = serveSubscriptionRouteRequest(t, 10, "default", "claude-x")
group, channel, _ = serveSubscriptionRouteRequest(t, 10, "default", "claude-x")
assert.Equal(t, "default", group)
assert.Equal(t, 4, channel)
}
2 changes: 2 additions & 0 deletions model/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ func ensureSubscriptionPlanTableSQLite() error {
` + "`sort_order`" + ` integer DEFAULT 0,
` + "`allow_balance_pay`" + ` numeric DEFAULT 1,
` + "`allow_wallet_overflow`" + ` numeric DEFAULT 1,
` + "`fallback_to_shared_pool_on_limit`" + ` numeric DEFAULT 0,
` + "`stripe_price_id`" + ` varchar(128) DEFAULT '',
` + "`creem_product_id`" + ` varchar(128) DEFAULT '',
` + "`waffo_pancake_product_id`" + ` varchar(128) DEFAULT '',
Expand Down Expand Up @@ -561,6 +562,7 @@ PRIMARY KEY (` + "`id`" + `)
{Name: "sort_order", DDL: "`sort_order` integer DEFAULT 0"},
{Name: "allow_balance_pay", DDL: "`allow_balance_pay` numeric DEFAULT 1"},
{Name: "allow_wallet_overflow", DDL: "`allow_wallet_overflow` numeric DEFAULT 1"},
{Name: "fallback_to_shared_pool_on_limit", DDL: "`fallback_to_shared_pool_on_limit` numeric DEFAULT 0"},
{Name: "stripe_price_id", DDL: "`stripe_price_id` varchar(128) DEFAULT ''"},
{Name: "creem_product_id", DDL: "`creem_product_id` varchar(128) DEFAULT ''"},
{Name: "waffo_pancake_product_id", DDL: "`waffo_pancake_product_id` varchar(128) DEFAULT ''"},
Expand Down
Loading
Loading