distributor.go 8.0 KB

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