distributor.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package middleware
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "slices"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/i18n"
  14. "github.com/QuantumNous/new-api/model"
  15. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  16. "github.com/QuantumNous/new-api/service"
  17. "github.com/QuantumNous/new-api/setting/ratio_setting"
  18. "github.com/QuantumNous/new-api/types"
  19. "github.com/gin-gonic/gin"
  20. )
  21. type ModelRequest struct {
  22. Model string `json:"model"`
  23. Group string `json:"group,omitempty"`
  24. }
  25. func Distribute() func(c *gin.Context) {
  26. return func(c *gin.Context) {
  27. var channel *model.Channel
  28. channelId, ok := common.GetContextKey(c, constant.ContextKeyTokenSpecificChannelId)
  29. modelRequest, shouldSelectChannel, err := getModelRequest(c)
  30. if err != nil {
  31. abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
  32. return
  33. }
  34. if ok {
  35. id, err := strconv.Atoi(channelId.(string))
  36. if err != nil {
  37. abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidChannelId))
  38. return
  39. }
  40. channel, err = model.GetChannelById(id, true)
  41. if err != nil {
  42. abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidChannelId))
  43. return
  44. }
  45. if channel.Status != common.ChannelStatusEnabled {
  46. abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorChannelDisabled))
  47. return
  48. }
  49. } else {
  50. // Select a channel for the user
  51. // check token model mapping
  52. modelLimitEnable := common.GetContextKeyBool(c, constant.ContextKeyTokenModelLimitEnabled)
  53. if modelLimitEnable {
  54. s, ok := common.GetContextKey(c, constant.ContextKeyTokenModelLimit)
  55. if !ok {
  56. // token model limit is empty, all models are not allowed
  57. abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorTokenNoModelAccess))
  58. return
  59. }
  60. var tokenModelLimit map[string]bool
  61. tokenModelLimit, ok = s.(map[string]bool)
  62. if !ok {
  63. tokenModelLimit = map[string]bool{}
  64. }
  65. matchName := ratio_setting.FormatMatchingModelName(modelRequest.Model) // match gpts & thinking-*
  66. if _, ok := tokenModelLimit[matchName]; !ok {
  67. abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorTokenModelForbidden, map[string]any{"Model": modelRequest.Model}))
  68. return
  69. }
  70. }
  71. if shouldSelectChannel {
  72. if modelRequest.Model == "" {
  73. abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorModelNameRequired))
  74. return
  75. }
  76. var selectGroup string
  77. usingGroup := common.GetContextKeyString(c, constant.ContextKeyUsingGroup)
  78. // check path is /pg/chat/completions
  79. if strings.HasPrefix(c.Request.URL.Path, "/pg/chat/completions") {
  80. playgroundRequest := &dto.PlayGroundRequest{}
  81. err = common.UnmarshalBodyReusable(c, playgroundRequest)
  82. if err != nil {
  83. abortWithOpenAiMessage(c, http.StatusBadRequest, i18n.T(c, i18n.MsgDistributorInvalidPlayground, map[string]any{"Error": err.Error()}))
  84. return
  85. }
  86. if playgroundRequest.Group != "" {
  87. if !service.GroupInUserUsableGroups(usingGroup, playgroundRequest.Group) && playgroundRequest.Group != usingGroup {
  88. abortWithOpenAiMessage(c, http.StatusForbidden, i18n.T(c, i18n.MsgDistributorGroupAccessDenied))
  89. return
  90. }
  91. usingGroup = playgroundRequest.Group
  92. common.SetContextKey(c, constant.ContextKeyUsingGroup, usingGroup)
  93. }
  94. }
  95. if preferredChannelID, found := service.GetPreferredChannelByAffinity(c, modelRequest.Model, usingGroup); found {
  96. preferred, err := model.CacheGetChannel(preferredChannelID)
  97. if err == nil && preferred != nil && preferred.Status == common.ChannelStatusEnabled {
  98. if usingGroup == "auto" {
  99. userGroup := common.GetContextKeyString(c, constant.ContextKeyUserGroup)
  100. autoGroups := service.GetUserAutoGroup(userGroup)
  101. for _, g := range autoGroups {
  102. if model.IsChannelEnabledForGroupModel(g, modelRequest.Model, preferred.Id) {
  103. selectGroup = g
  104. common.SetContextKey(c, constant.ContextKeyAutoGroup, g)
  105. channel = preferred
  106. service.MarkChannelAffinityUsed(c, g, preferred.Id)
  107. break
  108. }
  109. }
  110. } else if model.IsChannelEnabledForGroupModel(usingGroup, modelRequest.Model, preferred.Id) {
  111. channel = preferred
  112. selectGroup = usingGroup
  113. service.MarkChannelAffinityUsed(c, usingGroup, preferred.Id)
  114. }
  115. }
  116. }
  117. if channel == nil {
  118. channel, selectGroup, err = service.CacheGetRandomSatisfiedChannel(&service.RetryParam{
  119. Ctx: c,
  120. ModelName: modelRequest.Model,
  121. TokenGroup: usingGroup,
  122. Retry: common.GetPointer(0),
  123. })
  124. if err != nil {
  125. showGroup := usingGroup
  126. if usingGroup == "auto" {
  127. showGroup = fmt.Sprintf("auto(%s)", selectGroup)
  128. }
  129. message := i18n.T(c, i18n.MsgDistributorGetChannelFailed, map[string]any{"Group": showGroup, "Model": modelRequest.Model, "Error": err.Error()})
  130. // 如果错误,但是渠道不为空,说明是数据库一致性问题
  131. //if channel != nil {
  132. // common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
  133. // message = "数据库一致性已被破坏,请联系管理员"
  134. //}
  135. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message, types.ErrorCodeModelNotFound)
  136. return
  137. }
  138. if channel == nil {
  139. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, i18n.T(c, i18n.MsgDistributorNoAvailableChannel, map[string]any{"Group": usingGroup, "Model": modelRequest.Model}), types.ErrorCodeModelNotFound)
  140. return
  141. }
  142. }
  143. }
  144. }
  145. common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
  146. SetupContextForSelectedChannel(c, channel, modelRequest.Model)
  147. c.Next()
  148. if channel != nil && c.Writer != nil && c.Writer.Status() < http.StatusBadRequest {
  149. service.RecordChannelAffinity(c, channel.Id)
  150. }
  151. }
  152. }
  153. // getModelFromRequest 从请求中读取模型信息
  154. // 根据 Content-Type 自动处理:
  155. // - application/json
  156. // - application/x-www-form-urlencoded
  157. // - multipart/form-data
  158. func getModelFromRequest(c *gin.Context) (*ModelRequest, error) {
  159. var modelRequest ModelRequest
  160. err := common.UnmarshalBodyReusable(c, &modelRequest)
  161. if err != nil {
  162. return nil, errors.New(i18n.T(c, i18n.MsgDistributorInvalidRequest, map[string]any{"Error": err.Error()}))
  163. }
  164. return &modelRequest, nil
  165. }
  166. func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
  167. var modelRequest ModelRequest
  168. shouldSelectChannel := true
  169. var err error
  170. if strings.Contains(c.Request.URL.Path, "/mj/") {
  171. relayMode := relayconstant.Path2RelayModeMidjourney(c.Request.URL.Path)
  172. if relayMode == relayconstant.RelayModeMidjourneyTaskFetch ||
  173. relayMode == relayconstant.RelayModeMidjourneyTaskFetchByCondition ||
  174. relayMode == relayconstant.RelayModeMidjourneyNotify ||
  175. relayMode == relayconstant.RelayModeMidjourneyTaskImageSeed {
  176. shouldSelectChannel = false
  177. } else {
  178. midjourneyRequest := dto.MidjourneyRequest{}
  179. err = common.UnmarshalBodyReusable(c, &midjourneyRequest)
  180. if err != nil {
  181. return nil, false, errors.New(i18n.T(c, i18n.MsgDistributorInvalidMidjourney, map[string]any{"Error": err.Error()}))
  182. }
  183. midjourneyModel, mjErr, success := service.GetMjRequestModel(relayMode, &midjourneyRequest)
  184. if mjErr != nil {
  185. return nil, false, fmt.Errorf("%s", mjErr.Description)
  186. }
  187. if midjourneyModel == "" {
  188. if !success {
  189. return nil, false, fmt.Errorf("%s", i18n.T(c, i18n.MsgDistributorInvalidParseModel))
  190. } else {
  191. // task fetch, task fetch by condition, notify
  192. shouldSelectChannel = false
  193. }
  194. }
  195. modelRequest.Model = midjourneyModel
  196. }
  197. c.Set("relay_mode", relayMode)
  198. } else if strings.Contains(c.Request.URL.Path, "/suno/") {
  199. relayMode := relayconstant.Path2RelaySuno(c.Request.Method, c.Request.URL.Path)
  200. if relayMode == relayconstant.RelayModeSunoFetch ||
  201. relayMode == relayconstant.RelayModeSunoFetchByID {
  202. shouldSelectChannel = false
  203. } else {
  204. modelName := service.CoverTaskActionToModelName(constant.TaskPlatformSuno, c.Param("action"))
  205. modelRequest.Model = modelName
  206. }
  207. c.Set("platform", string(constant.TaskPlatformSuno))
  208. c.Set("relay_mode", relayMode)
  209. } else if strings.Contains(c.Request.URL.Path, "/v1/videos/") && strings.HasSuffix(c.Request.URL.Path, "/remix") {
  210. relayMode := relayconstant.RelayModeVideoSubmit
  211. c.Set("relay_mode", relayMode)
  212. shouldSelectChannel = false
  213. } else if strings.Contains(c.Request.URL.Path, "/v1/videos") {
  214. //curl https://api.openai.com/v1/videos \
  215. // -H "Authorization: Bearer $OPENAI_API_KEY" \
  216. // -F "model=sora-2" \
  217. // -F "prompt=A calico cat playing a piano on stage"
  218. // -F input_reference="@image.jpg"
  219. relayMode := relayconstant.RelayModeUnknown
  220. if c.Request.Method == http.MethodPost {
  221. relayMode = relayconstant.RelayModeVideoSubmit
  222. req, err := getModelFromRequest(c)
  223. if err != nil {
  224. return nil, false, err
  225. }
  226. if req != nil {
  227. modelRequest.Model = req.Model
  228. }
  229. } else if c.Request.Method == http.MethodGet {
  230. relayMode = relayconstant.RelayModeVideoFetchByID
  231. shouldSelectChannel = false
  232. }
  233. c.Set("relay_mode", relayMode)
  234. } else if strings.Contains(c.Request.URL.Path, "/v1/video/generations") {
  235. relayMode := relayconstant.RelayModeUnknown
  236. if c.Request.Method == http.MethodPost {
  237. req, err := getModelFromRequest(c)
  238. if err != nil {
  239. return nil, false, err
  240. }
  241. modelRequest.Model = req.Model
  242. relayMode = relayconstant.RelayModeVideoSubmit
  243. } else if c.Request.Method == http.MethodGet {
  244. relayMode = relayconstant.RelayModeVideoFetchByID
  245. shouldSelectChannel = false
  246. }
  247. if _, ok := c.Get("relay_mode"); !ok {
  248. c.Set("relay_mode", relayMode)
  249. }
  250. } else if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models/") || strings.HasPrefix(c.Request.URL.Path, "/v1/models/") {
  251. // Gemini API 路径处理: /v1beta/models/gemini-2.0-flash:generateContent
  252. relayMode := relayconstant.RelayModeGemini
  253. modelName := extractModelNameFromGeminiPath(c.Request.URL.Path)
  254. if modelName != "" {
  255. modelRequest.Model = modelName
  256. }
  257. c.Set("relay_mode", relayMode)
  258. } else if !strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") && !strings.Contains(c.Request.Header.Get("Content-Type"), "multipart/form-data") {
  259. req, err := getModelFromRequest(c)
  260. if err != nil {
  261. return nil, false, err
  262. }
  263. modelRequest.Model = req.Model
  264. }
  265. if strings.HasPrefix(c.Request.URL.Path, "/v1/realtime") {
  266. //wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01
  267. modelRequest.Model = c.Query("model")
  268. }
  269. if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  270. if modelRequest.Model == "" {
  271. modelRequest.Model = "text-moderation-stable"
  272. }
  273. }
  274. if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  275. if modelRequest.Model == "" {
  276. modelRequest.Model = c.Param("model")
  277. }
  278. }
  279. if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  280. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "dall-e")
  281. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/edits") {
  282. //modelRequest.Model = common.GetStringIfEmpty(c.PostForm("model"), "gpt-image-1")
  283. contentType := c.ContentType()
  284. if slices.Contains([]string{gin.MIMEPOSTForm, gin.MIMEMultipartPOSTForm}, contentType) {
  285. req, err := getModelFromRequest(c)
  286. if err == nil && req.Model != "" {
  287. modelRequest.Model = req.Model
  288. }
  289. }
  290. }
  291. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  292. relayMode := relayconstant.RelayModeAudioSpeech
  293. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/speech") {
  294. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "tts-1")
  295. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/translations") {
  296. // 先尝试从请求读取
  297. if req, err := getModelFromRequest(c); err == nil && req.Model != "" {
  298. modelRequest.Model = req.Model
  299. }
  300. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "whisper-1")
  301. relayMode = relayconstant.RelayModeAudioTranslation
  302. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
  303. // 先尝试从请求读取
  304. if req, err := getModelFromRequest(c); err == nil && req.Model != "" {
  305. modelRequest.Model = req.Model
  306. }
  307. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "whisper-1")
  308. relayMode = relayconstant.RelayModeAudioTranscription
  309. }
  310. c.Set("relay_mode", relayMode)
  311. }
  312. if strings.HasPrefix(c.Request.URL.Path, "/pg/chat/completions") {
  313. // playground chat completions
  314. req, err := getModelFromRequest(c)
  315. if err != nil {
  316. return nil, false, err
  317. }
  318. modelRequest.Model = req.Model
  319. modelRequest.Group = req.Group
  320. common.SetContextKey(c, constant.ContextKeyTokenGroup, modelRequest.Group)
  321. }
  322. if strings.HasPrefix(c.Request.URL.Path, "/v1/responses/compact") && modelRequest.Model != "" {
  323. modelRequest.Model = ratio_setting.WithCompactModelSuffix(modelRequest.Model)
  324. }
  325. return &modelRequest, shouldSelectChannel, nil
  326. }
  327. func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, modelName string) *types.NewAPIError {
  328. c.Set("original_model", modelName) // for retry
  329. if channel == nil {
  330. return types.NewError(errors.New("channel is nil"), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  331. }
  332. common.SetContextKey(c, constant.ContextKeyChannelId, channel.Id)
  333. common.SetContextKey(c, constant.ContextKeyChannelName, channel.Name)
  334. common.SetContextKey(c, constant.ContextKeyChannelType, channel.Type)
  335. common.SetContextKey(c, constant.ContextKeyChannelCreateTime, channel.CreatedTime)
  336. common.SetContextKey(c, constant.ContextKeyChannelSetting, channel.GetSetting())
  337. common.SetContextKey(c, constant.ContextKeyChannelOtherSetting, channel.GetOtherSettings())
  338. common.SetContextKey(c, constant.ContextKeyChannelParamOverride, channel.GetParamOverride())
  339. common.SetContextKey(c, constant.ContextKeyChannelHeaderOverride, channel.GetHeaderOverride())
  340. if nil != channel.OpenAIOrganization && *channel.OpenAIOrganization != "" {
  341. common.SetContextKey(c, constant.ContextKeyChannelOrganization, *channel.OpenAIOrganization)
  342. }
  343. common.SetContextKey(c, constant.ContextKeyChannelAutoBan, channel.GetAutoBan())
  344. common.SetContextKey(c, constant.ContextKeyChannelModelMapping, channel.GetModelMapping())
  345. common.SetContextKey(c, constant.ContextKeyChannelStatusCodeMapping, channel.GetStatusCodeMapping())
  346. key, index, newAPIError := channel.GetNextEnabledKey()
  347. if newAPIError != nil {
  348. return newAPIError
  349. }
  350. if channel.ChannelInfo.IsMultiKey {
  351. common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, true)
  352. common.SetContextKey(c, constant.ContextKeyChannelMultiKeyIndex, index)
  353. } else {
  354. // 必须设置为 false,否则在重试到单个 key 的时候会导致日志显示错误
  355. common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, false)
  356. }
  357. // c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", key))
  358. common.SetContextKey(c, constant.ContextKeyChannelKey, key)
  359. common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, channel.GetBaseURL())
  360. common.SetContextKey(c, constant.ContextKeySystemPromptOverride, false)
  361. // TODO: api_version统一
  362. switch channel.Type {
  363. case constant.ChannelTypeAzure:
  364. c.Set("api_version", channel.Other)
  365. case constant.ChannelTypeVertexAi:
  366. c.Set("region", channel.Other)
  367. case constant.ChannelTypeXunfei:
  368. c.Set("api_version", channel.Other)
  369. case constant.ChannelTypeGemini:
  370. c.Set("api_version", channel.Other)
  371. case constant.ChannelTypeAli:
  372. c.Set("plugin", channel.Other)
  373. case constant.ChannelCloudflare:
  374. c.Set("api_version", channel.Other)
  375. case constant.ChannelTypeMokaAI:
  376. c.Set("api_version", channel.Other)
  377. case constant.ChannelTypeCoze:
  378. c.Set("bot_id", channel.Other)
  379. }
  380. return nil
  381. }
  382. // extractModelNameFromGeminiPath 从 Gemini API URL 路径中提取模型名
  383. // 输入格式: /v1beta/models/gemini-2.0-flash:generateContent
  384. // 输出: gemini-2.0-flash
  385. func extractModelNameFromGeminiPath(path string) string {
  386. // 查找 "/models/" 的位置
  387. modelsPrefix := "/models/"
  388. modelsIndex := strings.Index(path, modelsPrefix)
  389. if modelsIndex == -1 {
  390. return ""
  391. }
  392. // 从 "/models/" 之后开始提取
  393. startIndex := modelsIndex + len(modelsPrefix)
  394. if startIndex >= len(path) {
  395. return ""
  396. }
  397. // 查找 ":" 的位置,模型名在 ":" 之前
  398. colonIndex := strings.Index(path[startIndex:], ":")
  399. if colonIndex == -1 {
  400. // 如果没有找到 ":",返回从 "/models/" 到路径结尾的部分
  401. return path[startIndex:]
  402. }
  403. // 返回模型名部分
  404. return path[startIndex : startIndex+colonIndex]
  405. }