distributor.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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("specific_channel_id")
  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.Contains(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. relayMode == relayconstant.RelayModeMidjourneyTaskImageSeed {
  49. shouldSelectChannel = false
  50. } else {
  51. midjourneyRequest := dto.MidjourneyRequest{}
  52. err = common.UnmarshalBodyReusable(c, &midjourneyRequest)
  53. if err != nil {
  54. abortWithMidjourneyMessage(c, http.StatusBadRequest, constant.MjErrorUnknown, "无效的请求, "+err.Error())
  55. return
  56. }
  57. midjourneyModel, mjErr, success := service.GetMjRequestModel(relayMode, &midjourneyRequest)
  58. if mjErr != nil {
  59. abortWithMidjourneyMessage(c, http.StatusBadRequest, mjErr.Code, mjErr.Description)
  60. return
  61. }
  62. if midjourneyModel == "" {
  63. if !success {
  64. abortWithMidjourneyMessage(c, http.StatusBadRequest, constant.MjErrorUnknown, "无效的请求, 无法解析模型")
  65. return
  66. } else {
  67. // task fetch, task fetch by condition, notify
  68. shouldSelectChannel = false
  69. }
  70. }
  71. modelRequest.Model = midjourneyModel
  72. }
  73. c.Set("relay_mode", relayMode)
  74. } else if !strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
  75. err = common.UnmarshalBodyReusable(c, &modelRequest)
  76. }
  77. if err != nil {
  78. abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的请求, "+err.Error())
  79. return
  80. }
  81. if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  82. if modelRequest.Model == "" {
  83. modelRequest.Model = "text-moderation-stable"
  84. }
  85. }
  86. if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  87. if modelRequest.Model == "" {
  88. modelRequest.Model = c.Param("model")
  89. }
  90. }
  91. if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  92. if modelRequest.Model == "" {
  93. modelRequest.Model = "dall-e"
  94. }
  95. }
  96. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  97. if modelRequest.Model == "" {
  98. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/speech") {
  99. modelRequest.Model = "tts-1"
  100. } else {
  101. modelRequest.Model = "whisper-1"
  102. }
  103. }
  104. }
  105. // check token model mapping
  106. modelLimitEnable := c.GetBool("token_model_limit_enabled")
  107. if modelLimitEnable {
  108. s, ok := c.Get("token_model_limit")
  109. var tokenModelLimit map[string]bool
  110. if ok {
  111. tokenModelLimit = s.(map[string]bool)
  112. } else {
  113. tokenModelLimit = map[string]bool{}
  114. }
  115. if tokenModelLimit != nil {
  116. if _, ok := tokenModelLimit[modelRequest.Model]; !ok {
  117. abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问模型 "+modelRequest.Model)
  118. return
  119. }
  120. } else {
  121. // token model limit is empty, all models are not allowed
  122. abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问任何模型")
  123. return
  124. }
  125. }
  126. userGroup, _ := model.CacheGetUserGroup(userId)
  127. c.Set("group", userGroup)
  128. if shouldSelectChannel {
  129. channel, err = model.CacheGetRandomSatisfiedChannel(userGroup, modelRequest.Model, 0)
  130. if err != nil {
  131. message := fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道", userGroup, modelRequest.Model)
  132. // 如果错误,但是渠道不为空,说明是数据库一致性问题
  133. if channel != nil {
  134. common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
  135. message = "数据库一致性已被破坏,请联系管理员"
  136. }
  137. // 如果错误,而且渠道为空,说明是没有可用渠道
  138. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message)
  139. return
  140. }
  141. if channel == nil {
  142. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道(数据库一致性已被破坏)", userGroup, modelRequest.Model))
  143. return
  144. }
  145. SetupContextForSelectedChannel(c, channel, modelRequest.Model)
  146. }
  147. }
  148. c.Next()
  149. }
  150. }
  151. func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, modelName string) {
  152. c.Set("channel", channel.Type)
  153. c.Set("channel_id", channel.Id)
  154. c.Set("channel_name", channel.Name)
  155. ban := true
  156. // parse *int to bool
  157. if channel.AutoBan != nil && *channel.AutoBan == 0 {
  158. ban = false
  159. }
  160. if nil != channel.OpenAIOrganization {
  161. c.Set("channel_organization", *channel.OpenAIOrganization)
  162. }
  163. c.Set("auto_ban", ban)
  164. c.Set("model_mapping", channel.GetModelMapping())
  165. c.Set("original_model", modelName) // for retry
  166. c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
  167. c.Set("base_url", channel.GetBaseURL())
  168. // TODO: api_version统一
  169. switch channel.Type {
  170. case common.ChannelTypeAzure:
  171. c.Set("api_version", channel.Other)
  172. case common.ChannelTypeXunfei:
  173. c.Set("api_version", channel.Other)
  174. //case common.ChannelTypeAIProxyLibrary:
  175. // c.Set("library_id", channel.Other)
  176. case common.ChannelTypeGemini:
  177. c.Set("api_version", channel.Other)
  178. case common.ChannelTypeAli:
  179. c.Set("plugin", channel.Other)
  180. }
  181. }