distributor.go 8.3 KB

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