diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 5262134a2b..70591f7241 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -129,11 +129,20 @@ func isOpenAIPersonalAccessTokenAuthMode(value string) bool { } } +// TempUnschedulableRule.Scope 的取值:命中后隔离的粒度。 +const ( + TempUnschedScopeAccount = "account" + TempUnschedScopeModel = "model" +) + type TempUnschedulableRule struct { ErrorCode int `json:"error_code"` Keywords []string `json:"keywords"` DurationMinutes int `json:"duration_minutes"` Description string `json:"description"` + // Scope 决定命中后的隔离粒度:account 暂停整个账号,model 只冷却本次请求的模型。 + // 为空时模型已知且非 401 走模型级,否则账号级。 + Scope string `json:"scope,omitempty"` } func (a *Account) IsActive() bool { @@ -460,6 +469,7 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule { Keywords: parseTempUnschedStrings(entry["keywords"]), DurationMinutes: parseTempUnschedInt(entry["duration_minutes"]), Description: parseTempUnschedString(entry["description"]), + Scope: normalizeTempUnschedScope(entry["scope"]), } if rule.ErrorCode <= 0 || rule.DurationMinutes <= 0 || len(rule.Keywords) == 0 { @@ -472,6 +482,18 @@ func (a *Account) GetTempUnschedulableRules() []TempUnschedulableRule { return rules } +// normalizeTempUnschedScope 只认 account / model 两个值,其余一律视为未设置。 +func normalizeTempUnschedScope(raw any) string { + switch strings.ToLower(strings.TrimSpace(parseTempUnschedString(raw))) { + case TempUnschedScopeAccount: + return TempUnschedScopeAccount + case TempUnschedScopeModel: + return TempUnschedScopeModel + default: + return "" + } +} + func parseTempUnschedString(value any) string { s, ok := value.(string) if !ok { diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 6438efc3e2..421de77a5c 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -2564,6 +2564,23 @@ func firstRequestedModel(requestedModel []string) string { return strings.TrimSpace(requestedModel[0]) } +// tempUnschedRuleUsesModelScope 决定一次命中按模型级冷却还是账号级暂停。 +// 显式 scope 完全由规则决定;scope 为空时模型已知且非 401 走模型级。 +// 模型未知时无法隔离,一律账号级。 +func tempUnschedRuleUsesModelScope(rule TempUnschedulableRule, modelKey string, statusCode int) bool { + if strings.TrimSpace(modelKey) == "" { + return false + } + switch rule.Scope { + case TempUnschedScopeAccount: + return false + case TempUnschedScopeModel: + return true + default: + return statusCode != http.StatusUnauthorized + } +} + type tempUnschedulableModelContextKey struct{} func withTempUnschedulableModel(ctx context.Context, requestedModel []string) context.Context { @@ -2696,6 +2713,8 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account now := time.Now() until := now.Add(time.Duration(rule.DurationMinutes) * time.Minute) + modelKey := firstRequestedModel(requestedModel) + modelScoped := tempUnschedRuleUsesModelScope(rule, modelKey, statusCode) state := &TempUnschedState{ UntilUnix: until.Unix(), @@ -2704,6 +2723,11 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account MatchedKeyword: matchedKeyword, RuleIndex: ruleIndex, ErrorMessage: truncateTempUnschedMessage(responseBody, tempUnschedMessageMaxBytes), + Scope: TempUnschedScopeAccount, + } + if modelScoped { + state.Scope = TempUnschedScopeModel + state.Model = modelKey } reason := "" @@ -2714,18 +2738,16 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account reason = strings.TrimSpace(state.ErrorMessage) } - // Persist known-model failures under the model key so the scheduler excludes - // only this (account, model) pair. Authentication and model-unknown failures - // retain the legacy account-wide temporary-unschedulable behavior below. - modelKey := firstRequestedModel(requestedModel) - if modelKey != "" && statusCode != http.StatusUnauthorized { + // Persist model-scoped hits under the model key so the scheduler excludes + // only this (account, model) pair; every other hit pauses the whole account below. + if modelScoped { if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, until, reason); err != nil { slog.Warn("temp_unsched_model_rate_limit_set_failed", "account_id", account.ID, "model", modelKey, "error", err) // The rule matched, so fail over the current request even if persistence // failed; never widen a model-scoped failure into an account-wide block. return true } - slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "status_code", statusCode) + slog.Info("account_model_temp_unschedulable", "account_id", account.ID, "model", modelKey, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode) return true } @@ -2741,7 +2763,7 @@ func (s *RateLimitService) triggerTempUnschedulable(ctx context.Context, account } } - slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "status_code", statusCode) + slog.Info("account_temp_unschedulable", "account_id", account.ID, "until", until, "rule_index", ruleIndex, "rule_scope", rule.Scope, "status_code", statusCode) return true } diff --git a/backend/internal/service/temp_unsched.go b/backend/internal/service/temp_unsched.go index 92b7da3f72..67ecb8e70e 100644 --- a/backend/internal/service/temp_unsched.go +++ b/backend/internal/service/temp_unsched.go @@ -16,6 +16,8 @@ type TempUnschedState struct { TriggerCount int64 `json:"trigger_count,omitempty"` // 本次触发累计命中次数 TriggerThreshold int `json:"trigger_threshold,omitempty"` // 触发阈值 TriggerWindowMinutes int `json:"trigger_window_minutes,omitempty"` // 计数窗口(分钟) + Scope string `json:"scope,omitempty"` // 隔离粒度:account / model + Model string `json:"model,omitempty"` // 模型级时被冷却的模型键 } // TempUnschedCache 临时不可调度缓存接口 diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 64cea06900..e3482a11b7 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -2561,6 +2561,44 @@ :placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')" /> +
+ +
+ +
+

{{ t('admin.accounts.tempUnschedulable.scopeHint') }}

+
getPresetMappingsByPlatform(form.platform)) +const tempUnschedScopeOptions = computed>(() => [ + { + value: 'model', + label: t('admin.accounts.tempUnschedulable.scopeModel'), + description: t('admin.accounts.tempUnschedulable.scopeModelDesc') + }, + { + value: 'account', + label: t('admin.accounts.tempUnschedulable.scopeAccount'), + description: t('admin.accounts.tempUnschedulable.scopeAccountDesc') + } +]) + const tempUnschedPresets = computed(() => [ { label: t('admin.accounts.tempUnschedulable.presets.overloadLabel'), @@ -4720,7 +4774,8 @@ const tempUnschedPresets = computed(() => [ error_code: 529, keywords: 'overloaded, too many', duration_minutes: 60, - description: t('admin.accounts.tempUnschedulable.presets.overloadDesc') + description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'), + scope: 'model' as const } }, { @@ -4729,7 +4784,8 @@ const tempUnschedPresets = computed(() => [ error_code: 429, keywords: 'rate limit, too many requests', duration_minutes: 10, - description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc') + description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'), + scope: 'model' as const } }, { @@ -4738,7 +4794,8 @@ const tempUnschedPresets = computed(() => [ error_code: 503, keywords: 'unavailable, maintenance', duration_minutes: 30, - description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc') + description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'), + scope: 'model' as const } } ]) @@ -5123,7 +5180,8 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => { error_code: null, keywords: '', duration_minutes: 30, - description: '' + description: '', + scope: 'model' }) } @@ -5146,6 +5204,7 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { keywords: string[] duration_minutes: number description: string + scope: TempUnschedulableScope }> = [] for (const rule of rules) { @@ -5165,7 +5224,8 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { error_code: Math.trunc(errorCode), keywords, duration_minutes: Math.trunc(duration), - description: rule.description.trim() + description: rule.description.trim(), + scope: rule.scope }) } diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index f7af882c7b..9bddf388d2 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -1536,6 +1536,44 @@ :placeholder="t('admin.accounts.tempUnschedulable.durationPlaceholder')" />
+
+ +
+ +
+

{{ t('admin.accounts.tempUnschedulable.scopeHint') }}

+
{ // Computed: current preset mappings based on platform const presetMappings = computed(() => getPresetMappingsByPlatform(props.account?.platform || 'anthropic')) +const tempUnschedScopeOptions = computed>(() => [ + { + value: 'model', + label: t('admin.accounts.tempUnschedulable.scopeModel'), + description: t('admin.accounts.tempUnschedulable.scopeModelDesc') + }, + { + value: 'account', + label: t('admin.accounts.tempUnschedulable.scopeAccount'), + description: t('admin.accounts.tempUnschedulable.scopeAccountDesc') + } +]) + const tempUnschedPresets = computed(() => [ { label: t('admin.accounts.tempUnschedulable.presets.overloadLabel'), @@ -3963,7 +4017,8 @@ const tempUnschedPresets = computed(() => [ error_code: 529, keywords: 'overloaded, too many', duration_minutes: 60, - description: t('admin.accounts.tempUnschedulable.presets.overloadDesc') + description: t('admin.accounts.tempUnschedulable.presets.overloadDesc'), + scope: 'model' as const } }, { @@ -3972,7 +4027,8 @@ const tempUnschedPresets = computed(() => [ error_code: 429, keywords: 'rate limit, too many requests', duration_minutes: 10, - description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc') + description: t('admin.accounts.tempUnschedulable.presets.rateLimitDesc'), + scope: 'model' as const } }, { @@ -3981,7 +4037,8 @@ const tempUnschedPresets = computed(() => [ error_code: 503, keywords: 'unavailable, maintenance', duration_minutes: 30, - description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc') + description: t('admin.accounts.tempUnschedulable.presets.unavailableDesc'), + scope: 'model' as const } } ]) @@ -4718,7 +4775,8 @@ const addTempUnschedRule = (preset?: TempUnschedRuleForm) => { error_code: null, keywords: '', duration_minutes: 30, - description: '' + description: '', + scope: 'model' }) } @@ -4741,6 +4799,7 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { keywords: string[] duration_minutes: number description: string + scope: TempUnschedulableScope }> = [] for (const rule of rules) { @@ -4760,7 +4819,8 @@ const buildTempUnschedRules = (rules: TempUnschedRuleForm[]) => { error_code: Math.trunc(errorCode), keywords, duration_minutes: Math.trunc(duration), - description: rule.description.trim() + description: rule.description.trim(), + scope: rule.scope }) } @@ -4858,11 +4918,13 @@ function loadTempUnschedRules(credentials?: Record) { tempUnschedRules.value = rawRules.map((rule) => { const entry = rule as Record + const errorCode = toPositiveNumber(entry.error_code) return { - error_code: toPositiveNumber(entry.error_code), + error_code: errorCode, keywords: formatTempUnschedKeywords(entry.keywords), duration_minutes: toPositiveNumber(entry.duration_minutes), - description: typeof entry.description === 'string' ? entry.description : '' + description: typeof entry.description === 'string' ? entry.description : '', + scope: resolveTempUnschedScope(entry.scope, errorCode) } }) } @@ -4961,6 +5023,16 @@ function formatTempUnschedKeywords(value: unknown) { return '' } +// 未设置 scope 的规则由后端按「401 账号级、其余模型级」处理,这里按同一规则回显, +// 保证打开再保存不改变规则行为。 +function resolveTempUnschedScope(value: unknown, errorCode: number | null): TempUnschedulableScope { + const scope = typeof value === 'string' ? value.trim().toLowerCase() : '' + if (scope === 'account' || scope === 'model') { + return scope + } + return errorCode === 401 ? 'account' : 'model' +} + const splitTempUnschedKeywords = (value: string) => { return value .split(/[,;]/) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index d11d7a9e7f..c605d27e66 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -409,7 +409,7 @@ export default { tempUnschedulable: { title: 'Temp Unschedulable', statusTitle: 'Temp Unschedulable Status', - hint: 'Disable accounts temporarily when error code and keyword both match.', + hint: 'When error code and keyword both match, pause the whole account or cool down only the model for the configured duration, per the rule scope.', notice: 'Rules are evaluated in order and require both error code and keyword match.', addRule: 'Add Rule', ruleOrder: 'Rule Order', @@ -425,6 +425,12 @@ export default { keywords: 'Keywords', keywordsPlaceholder: 'e.g. overloaded, too many requests', keywordsHint: 'Separate keywords with commas; any keyword match will trigger.', + scope: 'Scope', + scopeModel: 'Model', + scopeModelDesc: 'Cool down only the requested model', + scopeAccount: 'Account', + scopeAccountDesc: 'Pause scheduling for the whole account', + scopeHint: 'Model-scoped rules fall back to account scope when the request model cannot be identified.', description: 'Description', descriptionPlaceholder: 'Optional note for this rule', rulesInvalid: 'Add at least one rule with error code, keywords, and duration.', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index b002e5d54b..a9c4546fc1 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -457,7 +457,7 @@ export default { tempUnschedulable: { title: '临时不可调度', statusTitle: '临时不可调度状态', - hint: '当错误码与关键词同时匹配时,账号会在指定时间内被临时禁用。', + hint: '当错误码与关键词同时匹配时,按规则的作用范围在指定时间内暂停整个账号,或只冷却对应模型。', notice: '规则按顺序匹配,需同时满足错误码与关键词。', addRule: '添加规则', ruleOrder: '规则序号', @@ -473,6 +473,12 @@ export default { keywords: '关键词', keywordsPlaceholder: '例如 overloaded, too many requests', keywordsHint: '多个关键词用逗号分隔,匹配时必须命中其中之一。', + scope: '作用范围', + scopeModel: '模型级', + scopeModelDesc: '只冷却本次请求的模型', + scopeAccount: '账户级', + scopeAccountDesc: '暂停整个账号的调度', + scopeHint: '无法识别请求模型时,模型级规则按账户级处理。', description: '描述', descriptionPlaceholder: '可选,便于记忆规则用途', rulesInvalid: '请至少填写一条包含错误码、关键词和时长的规则。', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 7764284dfd..4d1c658651 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1024,11 +1024,15 @@ export interface GeminiCredentials { model_mapping?: Record } +export type TempUnschedulableScope = 'account' | 'model' + export interface TempUnschedulableRule { error_code: number keywords: string[] duration_minutes: number description: string + // 作用范围:account 暂停整个账号,model 只冷却本次请求的模型;缺省时 401 按 account、其余按 model 处理。 + scope?: TempUnschedulableScope } export interface TempUnschedulableState { @@ -1036,6 +1040,8 @@ export interface TempUnschedulableState { triggered_at_unix: number status_code: number matched_keyword: string + scope?: TempUnschedulableScope + model?: string rule_index: number error_message: string trigger_count?: number