Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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