You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

182 lines
6.9 KiB

  1. package service
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/constant"
  8. "github.com/QuantumNous/new-api/logger"
  9. "github.com/QuantumNous/new-api/model"
  10. "github.com/QuantumNous/new-api/relay/helper"
  11. "github.com/QuantumNous/new-api/setting"
  12. "github.com/QuantumNous/new-api/types"
  13. "github.com/gin-gonic/gin"
  14. )
  15. type RetryParam struct {
  16. Ctx *gin.Context
  17. TokenGroup string
  18. ModelName string
  19. Retry *int
  20. RequireMatrixUsageBilling bool
  21. resetNextTry bool
  22. }
  23. func (p *RetryParam) GetRetry() int {
  24. if p.Retry == nil {
  25. return 0
  26. }
  27. return *p.Retry
  28. }
  29. func (p *RetryParam) SetRetry(retry int) {
  30. p.Retry = &retry
  31. }
  32. func (p *RetryParam) IncreaseRetry() {
  33. if p.resetNextTry {
  34. p.resetNextTry = false
  35. return
  36. }
  37. if p.Retry == nil {
  38. p.Retry = new(int)
  39. }
  40. *p.Retry++
  41. }
  42. func (p *RetryParam) ResetRetryNextTry() {
  43. p.resetNextTry = true
  44. }
  45. // CacheGetRandomSatisfiedChannel tries to get a random channel that satisfies the requirements.
  46. // 尝试获取一个满足要求的随机渠道。
  47. //
  48. // For "auto" tokenGroup with cross-group Retry enabled:
  49. // 对于启用了跨分组重试的 "auto" tokenGroup:
  50. //
  51. // - Each group will exhaust all its priorities before moving to the next group.
  52. // 每个分组会用完所有优先级后才会切换到下一个分组。
  53. //
  54. // - Uses ContextKeyAutoGroupIndex to track current group index.
  55. // 使用 ContextKeyAutoGroupIndex 跟踪当前分组索引。
  56. //
  57. // - Uses ContextKeyAutoGroupRetryIndex to track the global Retry count when current group started.
  58. // 使用 ContextKeyAutoGroupRetryIndex 跟踪当前分组开始时的全局重试次数。
  59. //
  60. // - priorityRetry = Retry - startRetryIndex, represents the priority level within current group.
  61. // priorityRetry = Retry - startRetryIndex,表示当前分组内的优先级级别。
  62. //
  63. // - When GetRandomSatisfiedChannel returns nil (priorities exhausted), moves to next group.
  64. // 当 GetRandomSatisfiedChannel 返回 nil(优先级用完)时,切换到下一个分组。
  65. //
  66. // Example flow (2 groups, each with 2 priorities, RetryTimes=3):
  67. // 示例流程(2个分组,每个有2个优先级,RetryTimes=3):
  68. //
  69. // Retry=0: GroupA, priority0 (startRetryIndex=0, priorityRetry=0)
  70. // 分组A, 优先级0
  71. //
  72. // Retry=1: GroupA, priority1 (startRetryIndex=0, priorityRetry=1)
  73. // 分组A, 优先级1
  74. //
  75. // Retry=2: GroupA exhausted → GroupB, priority0 (startRetryIndex=2, priorityRetry=0)
  76. // 分组A用完 → 分组B, 优先级0
  77. //
  78. // Retry=3: GroupB, priority1 (startRetryIndex=2, priorityRetry=1)
  79. // 分组B, 优先级1
  80. func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, error) {
  81. var channel *model.Channel
  82. var err error
  83. selectGroup := param.TokenGroup
  84. userGroup := common.GetContextKeyString(param.Ctx, constant.ContextKeyUserGroup)
  85. if param.TokenGroup == "auto" {
  86. if len(setting.GetAutoGroups()) == 0 {
  87. return nil, selectGroup, errors.New("auto groups is not enabled")
  88. }
  89. autoGroups := GetUserAutoGroup(userGroup)
  90. // startGroupIndex: the group index to start searching from
  91. // startGroupIndex: 开始搜索的分组索引
  92. startGroupIndex := 0
  93. crossGroupRetry := common.GetContextKeyBool(param.Ctx, constant.ContextKeyTokenCrossGroupRetry)
  94. if lastGroupIndex, exists := common.GetContextKey(param.Ctx, constant.ContextKeyAutoGroupIndex); exists {
  95. if idx, ok := lastGroupIndex.(int); ok {
  96. startGroupIndex = idx
  97. }
  98. }
  99. for i := startGroupIndex; i < len(autoGroups); i++ {
  100. autoGroup := autoGroups[i]
  101. // Calculate priorityRetry for current group
  102. // 计算当前分组的 priorityRetry
  103. priorityRetry := param.GetRetry()
  104. // If moved to a new group, reset priorityRetry and update startRetryIndex
  105. // 如果切换到新分组,重置 priorityRetry 并更新 startRetryIndex
  106. if i > startGroupIndex {
  107. priorityRetry = 0
  108. }
  109. logger.LogDebug(param.Ctx, "Auto selecting group: %s, priorityRetry: %d", autoGroup, priorityRetry)
  110. channel, _ = model.GetRandomSatisfiedChannel(autoGroup, param.ModelName, priorityRetry)
  111. if channel == nil {
  112. // Current group has no available channel for this model, try next group
  113. // 当前分组没有该模型的可用渠道,尝试下一个分组
  114. logger.LogDebug(param.Ctx, "No available channel in group %s for model %s at priorityRetry %d, trying next group", autoGroup, param.ModelName, priorityRetry)
  115. // 重置状态以尝试下一个分组
  116. common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroupIndex, i+1)
  117. common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroupRetryIndex, 0)
  118. // Reset retry counter so outer loop can continue for next group
  119. // 重置重试计数器,以便外层循环可以为下一个分组继续
  120. param.SetRetry(0)
  121. continue
  122. }
  123. common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroup, autoGroup)
  124. selectGroup = autoGroup
  125. logger.LogDebug(param.Ctx, "Auto selected group: %s", autoGroup)
  126. // Prepare state for next retry
  127. // 为下一次重试准备状态
  128. if crossGroupRetry && priorityRetry >= common.RetryTimes {
  129. // Current group has exhausted all retries, prepare to switch to next group
  130. // This request still uses current group, but next retry will use next group
  131. // 当前分组已用完所有重试次数,准备切换到下一个分组
  132. // 本次请求仍使用当前分组,但下次重试将使用下一个分组
  133. logger.LogDebug(param.Ctx, "Current group %s retries exhausted (priorityRetry=%d >= RetryTimes=%d), preparing switch to next group for next retry", autoGroup, priorityRetry, common.RetryTimes)
  134. common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroupIndex, i+1)
  135. // Reset retry counter so outer loop can continue for next group
  136. // 重置重试计数器,以便外层循环可以为下一个分组继续
  137. param.SetRetry(0)
  138. param.ResetRetryNextTry()
  139. } else {
  140. // Stay in current group, save current state
  141. // 保持在当前分组,保存当前状态
  142. common.SetContextKey(param.Ctx, constant.ContextKeyAutoGroupIndex, i)
  143. }
  144. break
  145. }
  146. } else {
  147. channel, err = model.GetRandomSatisfiedChannel(param.TokenGroup, param.ModelName, param.GetRetry())
  148. if err != nil {
  149. return nil, param.TokenGroup, err
  150. }
  151. }
  152. if channel != nil && param.RequireMatrixUsageBilling {
  153. mappedModel, mapErr := helper.ResolvePricingModelMapping(param.ModelName, channel.GetModelMapping())
  154. if mapErr != nil {
  155. return nil, selectGroup, mapErr
  156. }
  157. if !helper.SupportsMatrixUsageBilling(param.ModelName, channel.Type, mappedModel) {
  158. return nil, selectGroup, types.NewErrorWithStatusCode(
  159. fmt.Errorf("matrix_usage_billing_channel_unavailable"),
  160. types.ErrorCode("matrix_usage_billing_channel_unavailable"),
  161. http.StatusBadRequest,
  162. types.ErrOptionWithSkipRetry(),
  163. )
  164. }
  165. }
  166. return channel, selectGroup, nil
  167. }