distributor.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. "one-api/setting"
  13. "one-api/setting/ratio_setting"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type ModelRequest struct {
  20. Model string `json:"model"`
  21. Group string `json:"group,omitempty"`
  22. }
  23. func Distribute() func(c *gin.Context) {
  24. return func(c *gin.Context) {
  25. allowIpsMap := common.GetContextKeyStringMap(c, constant.ContextKeyTokenAllowIps)
  26. if len(allowIpsMap) != 0 {
  27. clientIp := c.ClientIP()
  28. if _, ok := allowIpsMap[clientIp]; !ok {
  29. abortWithOpenAiMessage(c, http.StatusForbidden, "您的 IP 不在令牌允许访问的列表中")
  30. return
  31. }
  32. }
  33. var channel *model.Channel
  34. channelId, ok := common.GetContextKey(c, constant.ContextKeyTokenSpecificChannelId)
  35. modelRequest, shouldSelectChannel, err := getModelRequest(c)
  36. if err != nil {
  37. abortWithOpenAiMessage(c, http.StatusBadRequest, "Invalid request, "+err.Error())
  38. return
  39. }
  40. userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
  41. tokenGroup := common.GetContextKeyString(c, constant.ContextKeyTokenGroup)
  42. if tokenGroup != "" {
  43. // check common.UserUsableGroups[userGroup]
  44. if _, ok := setting.GetUserUsableGroups(userGroup)[tokenGroup]; !ok {
  45. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("令牌分组 %s 已被禁用", tokenGroup))
  46. return
  47. }
  48. // check group in common.GroupRatio
  49. if !ratio_setting.ContainsGroupRatio(tokenGroup) {
  50. if tokenGroup != "auto" {
  51. abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup))
  52. return
  53. }
  54. }
  55. userGroup = tokenGroup
  56. }
  57. common.SetContextKey(c, constant.ContextKeyUsingGroup, userGroup)
  58. if ok {
  59. id, err := strconv.Atoi(channelId.(string))
  60. if err != nil {
  61. abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的渠道 Id")
  62. return
  63. }
  64. channel, err = model.GetChannelById(id, true)
  65. if err != nil {
  66. abortWithOpenAiMessage(c, http.StatusBadRequest, "无效的渠道 Id")
  67. return
  68. }
  69. if channel.Status != common.ChannelStatusEnabled {
  70. abortWithOpenAiMessage(c, http.StatusForbidden, "该渠道已被禁用")
  71. return
  72. }
  73. } else {
  74. // Select a channel for the user
  75. // check token model mapping
  76. modelLimitEnable := common.GetContextKeyBool(c, constant.ContextKeyTokenModelLimitEnabled)
  77. if modelLimitEnable {
  78. s, ok := common.GetContextKey(c, constant.ContextKeyTokenModelLimit)
  79. var tokenModelLimit map[string]bool
  80. if ok {
  81. tokenModelLimit = s.(map[string]bool)
  82. } else {
  83. tokenModelLimit = map[string]bool{}
  84. }
  85. if tokenModelLimit != nil {
  86. if _, ok := tokenModelLimit[modelRequest.Model]; !ok {
  87. abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问模型 "+modelRequest.Model)
  88. return
  89. }
  90. } else {
  91. // token model limit is empty, all models are not allowed
  92. abortWithOpenAiMessage(c, http.StatusForbidden, "该令牌无权访问任何模型")
  93. return
  94. }
  95. }
  96. if shouldSelectChannel {
  97. var selectGroup string
  98. channel, selectGroup, err = model.CacheGetRandomSatisfiedChannel(c, userGroup, modelRequest.Model, 0)
  99. if err != nil {
  100. showGroup := userGroup
  101. if userGroup == "auto" {
  102. showGroup = fmt.Sprintf("auto(%s)", selectGroup)
  103. }
  104. message := fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道", showGroup, modelRequest.Model)
  105. // 如果错误,但是渠道不为空,说明是数据库一致性问题
  106. if channel != nil {
  107. common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
  108. message = "数据库一致性已被破坏,请联系管理员"
  109. }
  110. // 如果错误,而且渠道为空,说明是没有可用渠道
  111. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message)
  112. return
  113. }
  114. if channel == nil {
  115. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道(数据库一致性已被破坏)", userGroup, modelRequest.Model))
  116. return
  117. }
  118. }
  119. }
  120. common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
  121. SetupContextForSelectedChannel(c, channel, modelRequest.Model)
  122. c.Next()
  123. }
  124. }
  125. func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
  126. var modelRequest ModelRequest
  127. shouldSelectChannel := true
  128. var err error
  129. if strings.Contains(c.Request.URL.Path, "/mj/") {
  130. relayMode := relayconstant.Path2RelayModeMidjourney(c.Request.URL.Path)
  131. if relayMode == relayconstant.RelayModeMidjourneyTaskFetch ||
  132. relayMode == relayconstant.RelayModeMidjourneyTaskFetchByCondition ||
  133. relayMode == relayconstant.RelayModeMidjourneyNotify ||
  134. relayMode == relayconstant.RelayModeMidjourneyTaskImageSeed {
  135. shouldSelectChannel = false
  136. } else {
  137. midjourneyRequest := dto.MidjourneyRequest{}
  138. err = common.UnmarshalBodyReusable(c, &midjourneyRequest)
  139. if err != nil {
  140. return nil, false, err
  141. }
  142. midjourneyModel, mjErr, success := service.GetMjRequestModel(relayMode, &midjourneyRequest)
  143. if mjErr != nil {
  144. return nil, false, fmt.Errorf(mjErr.Description)
  145. }
  146. if midjourneyModel == "" {
  147. if !success {
  148. return nil, false, fmt.Errorf("无效的请求, 无法解析模型")
  149. } else {
  150. // task fetch, task fetch by condition, notify
  151. shouldSelectChannel = false
  152. }
  153. }
  154. modelRequest.Model = midjourneyModel
  155. }
  156. c.Set("relay_mode", relayMode)
  157. } else if strings.Contains(c.Request.URL.Path, "/suno/") {
  158. relayMode := relayconstant.Path2RelaySuno(c.Request.Method, c.Request.URL.Path)
  159. if relayMode == relayconstant.RelayModeSunoFetch ||
  160. relayMode == relayconstant.RelayModeSunoFetchByID {
  161. shouldSelectChannel = false
  162. } else {
  163. modelName := service.CoverTaskActionToModelName(constant.TaskPlatformSuno, c.Param("action"))
  164. modelRequest.Model = modelName
  165. }
  166. c.Set("platform", string(constant.TaskPlatformSuno))
  167. c.Set("relay_mode", relayMode)
  168. } else if strings.Contains(c.Request.URL.Path, "/v1/video/generations") {
  169. err = common.UnmarshalBodyReusable(c, &modelRequest)
  170. var platform string
  171. var relayMode int
  172. if strings.HasPrefix(modelRequest.Model, "jimeng") {
  173. platform = string(constant.TaskPlatformJimeng)
  174. relayMode = relayconstant.Path2RelayJimeng(c.Request.Method, c.Request.URL.Path)
  175. if relayMode == relayconstant.RelayModeJimengFetchByID {
  176. shouldSelectChannel = false
  177. }
  178. } else {
  179. platform = string(constant.TaskPlatformKling)
  180. relayMode = relayconstant.Path2RelayKling(c.Request.Method, c.Request.URL.Path)
  181. if relayMode == relayconstant.RelayModeKlingFetchByID {
  182. shouldSelectChannel = false
  183. }
  184. }
  185. c.Set("platform", platform)
  186. c.Set("relay_mode", relayMode)
  187. } else if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models/") || strings.HasPrefix(c.Request.URL.Path, "/v1/models/") {
  188. // Gemini API 路径处理: /v1beta/models/gemini-2.0-flash:generateContent
  189. relayMode := relayconstant.RelayModeGemini
  190. modelName := extractModelNameFromGeminiPath(c.Request.URL.Path)
  191. if modelName != "" {
  192. modelRequest.Model = modelName
  193. }
  194. c.Set("relay_mode", relayMode)
  195. } else if !strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") && !strings.HasPrefix(c.Request.URL.Path, "/v1/images/edits") {
  196. err = common.UnmarshalBodyReusable(c, &modelRequest)
  197. }
  198. if err != nil {
  199. return nil, false, errors.New("无效的请求, " + err.Error())
  200. }
  201. if strings.HasPrefix(c.Request.URL.Path, "/v1/realtime") {
  202. //wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01
  203. modelRequest.Model = c.Query("model")
  204. }
  205. if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  206. if modelRequest.Model == "" {
  207. modelRequest.Model = "text-moderation-stable"
  208. }
  209. }
  210. if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  211. if modelRequest.Model == "" {
  212. modelRequest.Model = c.Param("model")
  213. }
  214. }
  215. if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  216. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "dall-e")
  217. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/edits") {
  218. modelRequest.Model = common.GetStringIfEmpty(c.PostForm("model"), "gpt-image-1")
  219. }
  220. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  221. relayMode := relayconstant.RelayModeAudioSpeech
  222. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/speech") {
  223. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "tts-1")
  224. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/translations") {
  225. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, c.PostForm("model"))
  226. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "whisper-1")
  227. relayMode = relayconstant.RelayModeAudioTranslation
  228. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
  229. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, c.PostForm("model"))
  230. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "whisper-1")
  231. relayMode = relayconstant.RelayModeAudioTranscription
  232. }
  233. c.Set("relay_mode", relayMode)
  234. }
  235. if strings.HasPrefix(c.Request.URL.Path, "/pg/chat/completions") {
  236. // playground chat completions
  237. err = common.UnmarshalBodyReusable(c, &modelRequest)
  238. if err != nil {
  239. return nil, false, errors.New("无效的请求, " + err.Error())
  240. }
  241. common.SetContextKey(c, constant.ContextKeyTokenGroup, modelRequest.Group)
  242. }
  243. return &modelRequest, shouldSelectChannel, nil
  244. }
  245. func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, modelName string) {
  246. c.Set("original_model", modelName) // for retry
  247. if channel == nil {
  248. return
  249. }
  250. common.SetContextKey(c, constant.ContextKeyChannelId, channel.Id)
  251. common.SetContextKey(c, constant.ContextKeyChannelName, channel.Name)
  252. common.SetContextKey(c, constant.ContextKeyChannelType, channel.Type)
  253. common.SetContextKey(c, constant.ContextKeyChannelCreateTime, channel.CreatedTime)
  254. common.SetContextKey(c, constant.ContextKeyChannelSetting, channel.GetSetting())
  255. common.SetContextKey(c, constant.ContextKeyChannelParamOverride, channel.GetParamOverride())
  256. if nil != channel.OpenAIOrganization && *channel.OpenAIOrganization != "" {
  257. common.SetContextKey(c, constant.ContextKeyChannelOrganization, *channel.OpenAIOrganization)
  258. }
  259. common.SetContextKey(c, constant.ContextKeyChannelAutoBan, channel.GetAutoBan())
  260. common.SetContextKey(c, constant.ContextKeyChannelModelMapping, channel.GetModelMapping())
  261. common.SetContextKey(c, constant.ContextKeyChannelStatusCodeMapping, channel.GetStatusCodeMapping())
  262. if channel.ChannelInfo.IsMultiKey {
  263. common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, true)
  264. }
  265. c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
  266. common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, channel.GetBaseURL())
  267. // TODO: api_version统一
  268. switch channel.Type {
  269. case constant.ChannelTypeAzure:
  270. c.Set("api_version", channel.Other)
  271. case constant.ChannelTypeVertexAi:
  272. c.Set("region", channel.Other)
  273. case constant.ChannelTypeXunfei:
  274. c.Set("api_version", channel.Other)
  275. case constant.ChannelTypeGemini:
  276. c.Set("api_version", channel.Other)
  277. case constant.ChannelTypeAli:
  278. c.Set("plugin", channel.Other)
  279. case constant.ChannelCloudflare:
  280. c.Set("api_version", channel.Other)
  281. case constant.ChannelTypeMokaAI:
  282. c.Set("api_version", channel.Other)
  283. case constant.ChannelTypeCoze:
  284. c.Set("bot_id", channel.Other)
  285. }
  286. }
  287. // extractModelNameFromGeminiPath 从 Gemini API URL 路径中提取模型名
  288. // 输入格式: /v1beta/models/gemini-2.0-flash:generateContent
  289. // 输出: gemini-2.0-flash
  290. func extractModelNameFromGeminiPath(path string) string {
  291. // 查找 "/models/" 的位置
  292. modelsPrefix := "/models/"
  293. modelsIndex := strings.Index(path, modelsPrefix)
  294. if modelsIndex == -1 {
  295. return ""
  296. }
  297. // 从 "/models/" 之后开始提取
  298. startIndex := modelsIndex + len(modelsPrefix)
  299. if startIndex >= len(path) {
  300. return ""
  301. }
  302. // 查找 ":" 的位置,模型名在 ":" 之前
  303. colonIndex := strings.Index(path[startIndex:], ":")
  304. if colonIndex == -1 {
  305. // 如果没有找到 ":",返回从 "/models/" 到路径结尾的部分
  306. return path[startIndex:]
  307. }
  308. // 返回模型名部分
  309. return path[startIndex : startIndex+colonIndex]
  310. }