distributor.go 7.7 KB

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