cache.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "one-api/common"
  7. "one-api/setting"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/gin-gonic/gin"
  13. )
  14. var group2model2channels map[string]map[string][]*Channel
  15. var channelsIDM map[int]*Channel
  16. var channelSyncLock sync.RWMutex
  17. func InitChannelCache() {
  18. if !common.MemoryCacheEnabled {
  19. return
  20. }
  21. newChannelId2channel := make(map[int]*Channel)
  22. var channels []*Channel
  23. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  24. for _, channel := range channels {
  25. newChannelId2channel[channel.Id] = channel
  26. }
  27. var abilities []*Ability
  28. DB.Find(&abilities)
  29. groups := make(map[string]bool)
  30. for _, ability := range abilities {
  31. groups[ability.Group] = true
  32. }
  33. newGroup2model2channels := make(map[string]map[string][]*Channel)
  34. newChannelsIDM := make(map[int]*Channel)
  35. for group := range groups {
  36. newGroup2model2channels[group] = make(map[string][]*Channel)
  37. }
  38. for _, channel := range channels {
  39. newChannelsIDM[channel.Id] = channel
  40. groups := strings.Split(channel.Group, ",")
  41. for _, group := range groups {
  42. models := strings.Split(channel.Models, ",")
  43. for _, model := range models {
  44. if _, ok := newGroup2model2channels[group][model]; !ok {
  45. newGroup2model2channels[group][model] = make([]*Channel, 0)
  46. }
  47. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  48. }
  49. }
  50. }
  51. // sort by priority
  52. for group, model2channels := range newGroup2model2channels {
  53. for model, channels := range model2channels {
  54. sort.Slice(channels, func(i, j int) bool {
  55. return channels[i].GetPriority() > channels[j].GetPriority()
  56. })
  57. newGroup2model2channels[group][model] = channels
  58. }
  59. }
  60. channelSyncLock.Lock()
  61. group2model2channels = newGroup2model2channels
  62. channelsIDM = newChannelsIDM
  63. channelSyncLock.Unlock()
  64. common.SysLog("channels synced from database")
  65. }
  66. func SyncChannelCache(frequency int) {
  67. for {
  68. time.Sleep(time.Duration(frequency) * time.Second)
  69. common.SysLog("syncing channels from database")
  70. InitChannelCache()
  71. }
  72. }
  73. func CacheGetRandomSatisfiedChannel(c *gin.Context, group string, model string, retry int) (*Channel, string, error) {
  74. var channel *Channel
  75. var err error
  76. selectGroup := group
  77. if group == "auto" {
  78. if len(setting.AutoGroups) == 0 {
  79. return nil, selectGroup, errors.New("auto groups is not enabled")
  80. }
  81. for _, autoGroup := range setting.AutoGroups {
  82. if common.DebugEnabled {
  83. println("autoGroup:", autoGroup)
  84. }
  85. channel, _ = getRandomSatisfiedChannel(autoGroup, model, retry)
  86. if channel == nil {
  87. continue
  88. } else {
  89. c.Set("auto_group", autoGroup)
  90. selectGroup = autoGroup
  91. if common.DebugEnabled {
  92. println("selectGroup:", selectGroup)
  93. }
  94. break
  95. }
  96. }
  97. } else {
  98. channel, err = getRandomSatisfiedChannel(group, model, retry)
  99. if err != nil {
  100. return nil, group, err
  101. }
  102. }
  103. if channel == nil {
  104. return nil, group, errors.New("channel not found")
  105. }
  106. return channel, selectGroup, nil
  107. }
  108. func getRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  109. if strings.HasPrefix(model, "gpt-4-gizmo") {
  110. model = "gpt-4-gizmo-*"
  111. }
  112. if strings.HasPrefix(model, "gpt-4o-gizmo") {
  113. model = "gpt-4o-gizmo-*"
  114. }
  115. // if memory cache is disabled, get channel directly from database
  116. if !common.MemoryCacheEnabled {
  117. return GetRandomSatisfiedChannel(group, model, retry)
  118. }
  119. channelSyncLock.RLock()
  120. channels := group2model2channels[group][model]
  121. channelSyncLock.RUnlock()
  122. if len(channels) == 0 {
  123. return nil, errors.New("channel not found")
  124. }
  125. uniquePriorities := make(map[int]bool)
  126. for _, channel := range channels {
  127. uniquePriorities[int(channel.GetPriority())] = true
  128. }
  129. var sortedUniquePriorities []int
  130. for priority := range uniquePriorities {
  131. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  132. }
  133. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  134. if retry >= len(uniquePriorities) {
  135. retry = len(uniquePriorities) - 1
  136. }
  137. targetPriority := int64(sortedUniquePriorities[retry])
  138. // get the priority for the given retry number
  139. var targetChannels []*Channel
  140. for _, channel := range channels {
  141. if channel.GetPriority() == targetPriority {
  142. targetChannels = append(targetChannels, channel)
  143. }
  144. }
  145. // 平滑系数
  146. smoothingFactor := 10
  147. // Calculate the total weight of all channels up to endIdx
  148. totalWeight := 0
  149. for _, channel := range targetChannels {
  150. totalWeight += channel.GetWeight() + smoothingFactor
  151. }
  152. // Generate a random value in the range [0, totalWeight)
  153. randomWeight := rand.Intn(totalWeight)
  154. // Find a channel based on its weight
  155. for _, channel := range targetChannels {
  156. randomWeight -= channel.GetWeight() + smoothingFactor
  157. if randomWeight < 0 {
  158. return channel, nil
  159. }
  160. }
  161. // return null if no channel is not found
  162. return nil, errors.New("channel not found")
  163. }
  164. func CacheGetChannel(id int) (*Channel, error) {
  165. if !common.MemoryCacheEnabled {
  166. return GetChannelById(id, true)
  167. }
  168. channelSyncLock.RLock()
  169. defer channelSyncLock.RUnlock()
  170. c, ok := channelsIDM[id]
  171. if !ok {
  172. return nil, errors.New(fmt.Sprintf("当前渠道# %d,已不存在", id))
  173. }
  174. return c, nil
  175. }
  176. func CacheUpdateChannelStatus(id int, status int) {
  177. if !common.MemoryCacheEnabled {
  178. return
  179. }
  180. channelSyncLock.Lock()
  181. defer channelSyncLock.Unlock()
  182. if channel, ok := channelsIDM[id]; ok {
  183. channel.Status = status
  184. }
  185. }