channel_select.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package service
  2. import (
  3. "errors"
  4. "github.com/QuantumNous/new-api/common"
  5. "github.com/QuantumNous/new-api/constant"
  6. "github.com/QuantumNous/new-api/logger"
  7. "github.com/QuantumNous/new-api/model"
  8. "github.com/QuantumNous/new-api/setting"
  9. "github.com/gin-gonic/gin"
  10. )
  11. // CacheGetRandomSatisfiedChannel tries to get a random channel that satisfies the requirements.
  12. func CacheGetRandomSatisfiedChannel(c *gin.Context, tokenGroup string, modelName string, retry int) (*model.Channel, string, error) {
  13. var channel *model.Channel
  14. var err error
  15. selectGroup := tokenGroup
  16. userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
  17. if tokenGroup == "auto" {
  18. if len(setting.GetAutoGroups()) == 0 {
  19. return nil, selectGroup, errors.New("auto groups is not enabled")
  20. }
  21. autoGroups := GetUserAutoGroup(userGroup)
  22. startIndex := 0
  23. priorityRetry := retry
  24. crossGroupRetry := common.GetContextKeyBool(c, constant.ContextKeyTokenCrossGroupRetry)
  25. if crossGroupRetry && retry > 0 {
  26. logger.LogDebug(c, "Auto group retry cross group, retry: %d", retry)
  27. if lastIndex, exists := common.GetContextKey(c, constant.ContextKeyAutoGroupIndex); exists {
  28. if idx, ok := lastIndex.(int); ok {
  29. startIndex = idx + 1
  30. priorityRetry = 0
  31. }
  32. }
  33. logger.LogDebug(c, "Auto group retry cross group, start index: %d", startIndex)
  34. }
  35. for i := startIndex; i < len(autoGroups); i++ {
  36. autoGroup := autoGroups[i]
  37. logger.LogDebug(c, "Auto selecting group: %s", autoGroup)
  38. channel, _ = model.GetRandomSatisfiedChannel(autoGroup, modelName, priorityRetry)
  39. if channel == nil {
  40. priorityRetry = 0
  41. continue
  42. } else {
  43. c.Set("auto_group", autoGroup)
  44. common.SetContextKey(c, constant.ContextKeyAutoGroupIndex, i)
  45. selectGroup = autoGroup
  46. logger.LogDebug(c, "Auto selected group: %s", autoGroup)
  47. break
  48. }
  49. }
  50. } else {
  51. channel, err = model.GetRandomSatisfiedChannel(tokenGroup, modelName, retry)
  52. if err != nil {
  53. return nil, tokenGroup, err
  54. }
  55. }
  56. return channel, selectGroup, nil
  57. }