distributor.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "one-api/common"
  6. "one-api/constant"
  7. "one-api/dto"
  8. "one-api/model"
  9. relayconstant "one-api/relay/constant"
  10. "one-api/service"
  11. "strconv"
  12. "strings"
  13. "github.com/gin-gonic/gin"
  14. )
  15. type ModelRequest struct {
  16. Model string `json:"model"`
  17. }
  18. func Distribute() func(c *gin.Context) {
  19. return func(c *gin.Context) {
  20. userId := c.GetInt("id")
  21. var channel *model.Channel
  22. channelId, ok := c.Get("channelId")
  23. if ok {
  24. id, err := strconv.Atoi(channelId.(string))
  25. if err != nil {
  26. abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的渠道 Id")
  27. return
  28. }
  29. channel, err = model.GetChannelById(id, true)
  30. if err != nil {
  31. abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的渠道 Id")
  32. return
  33. }
  34. if channel.Status != common.ChannelStatusEnabled {
  35. abortWithOpenAiMessage(c, http.StatusForbidden, "该渠道已被禁用")
  36. return
  37. }
  38. } else {
  39. shouldSelectChannel := true
  40. // Select a channel for the user
  41. var modelRequest ModelRequest
  42. var err error
  43. if strings.HasPrefix(c.Request.URL.Path, "/mj") {
  44. relayMode := relayconstant.Path2RelayModeMidjourney(c.Request.URL.Path)
  45. if relayMode == relayconstant.RelayModeMidjourneyTaskFetch ||
  46. relayMode == relayconstant.RelayModeMidjourneyTaskFetchByCondition ||
  47. relayMode == relayconstant.RelayModeMidjourneyNotify {
  48. shouldSelectChannel = false
  49. } else {
  50. midjourneyRequest := dto.MidjourneyRequest{}
  51. err = common.UnmarshalBodyReusable(c, &midjourneyRequest)
  52. if err != nil {
  53. abortWithMidjourneyMessage(c, http.StatusBadRequest, constant.MjErrorUnknown, "无效的请求, "+err.Error())
  54. return
  55. }
  56. midjourneyModel, mjErr, success := service.GetMjRequestModel(relayMode, &midjourneyRequest)
  57. if mjErr != nil {
  58. abortWithMidjourneyMessage(c, http.StatusBadRequest, mjErr.Code, mjErr.Description)
  59. return
  60. }
  61. if midjourneyModel == "" {
  62. if !success {
  63. abortWithMidjourneyMessage(c, http.StatusBadRequest, constant.MjErrorUnknown, "无效的请求, 无法解析模型")
  64. return
  65. } else {
  66. // task fetch, task fetch by condition, notify
  67. shouldSelectChannel = false
  68. }
  69. }
  70. modelRequest.Model = midjourneyModel
  71. }
  72. c.Set("relay_mode", relayMode)
  73. } else if !strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
  74. err = common.UnmarshalBodyReusable(c, &modelRequest)
  75. }
  76. if err != nil {
  77. abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的请求, "+err.Error())
  78. return
  79. }
  80. if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  81. if modelRequest.Model == "" {
  82. modelRequest.Model = "text-moderation-stable"
  83. }
  84. }
  85. if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  86. if modelRequest.Model == "" {
  87. modelRequest.Model = c.Param("model")
  88. }
  89. }
  90. if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  91. if modelRequest.Model == "" {
  92. modelRequest.Model = "dall-e"
  93. }
  94. }
  95. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  96. if modelRequest.Model == "" {
  97. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/speech") {
  98. modelRequest.Model = "tts-1"
  99. } else {
  100. modelRequest.Model = "whisper-1"
  101. }
  102. }
  103. }
  104. // check token model mapping
  105. modelLimitEnable := c.GetBool("token_model_limit_enabled")
  106. if modelLimitEnable {
  107. s, ok := c.Get("token_model_limit")
  108. var tokenModelLimit map[string]bool
  109. if ok {
  110. tokenModelLimit = s.(map[string]bool)
  111. } else {
  112. tokenModelLimit = map[string]bool{}
  113. }
  114. if tokenModelLimit != nil {
  115. if _, ok := tokenModelLimit[modelRequest.Model]; !ok {
  116. abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问模型 "+modelRequest.Model)
  117. return
  118. }
  119. } else {
  120. // token model limit is empty, all models are not allowed
  121. abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问任何模型")
  122. return
  123. }
  124. }
  125. userGroup, _ := model.CacheGetUserGroup(userId)
  126. c.Set("group", userGroup)
  127. if shouldSelectChannel {
  128. channel, err = model.CacheGetRandomSatisfiedChannel(userGroup, modelRequest.Model)
  129. if err != nil {
  130. message := fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道", userGroup, modelRequest.Model)
  131. // 如果错误,但是渠道不为空,说明是数据库一致性问题
  132. if channel != nil {
  133. common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
  134. message = "数据库一致性已被破坏,请联系管理员"
  135. }
  136. // 如果错误,而且渠道为空,说明是没有可用渠道
  137. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message)
  138. return
  139. }
  140. if channel == nil {
  141. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道(数据库一致性已被破坏)", userGroup, modelRequest.Model))
  142. return
  143. }
  144. c.Set("channel", channel.Type)
  145. c.Set("channel_id", channel.Id)
  146. c.Set("channel_name", channel.Name)
  147. ban := true
  148. // parse *int to bool
  149. if channel.AutoBan != nil && *channel.AutoBan == 0 {
  150. ban = false
  151. }
  152. c.Set("auto_ban", ban)
  153. c.Set("model_mapping", channel.GetModelMapping())
  154. c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
  155. c.Set("base_url", channel.GetBaseURL())
  156. // TODO: api_version统一
  157. switch channel.Type {
  158. case common.ChannelTypeAzure:
  159. c.Set("api_version", channel.Other)
  160. case common.ChannelTypeXunfei:
  161. c.Set("api_version", channel.Other)
  162. //case common.ChannelTypeAIProxyLibrary:
  163. // c.Set("library_id", channel.Other)
  164. case common.ChannelTypeGemini:
  165. c.Set("api_version", channel.Other)
  166. case common.ChannelTypeAli:
  167. c.Set("plugin", channel.Other)
  168. }
  169. }
  170. }
  171. c.Next()
  172. }
  173. }