Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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