Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

474 строки
18 KiB

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