distributor.go 14 KB

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