distributor.go 8.7 KB

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