distributor.go 6.9 KB

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