distributor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package middleware
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  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/model"
  13. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  14. "github.com/QuantumNous/new-api/service"
  15. "github.com/QuantumNous/new-api/setting"
  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. userGroup := 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, "无效的请求, "+err.Error())
  83. return
  84. }
  85. if playgroundRequest.Group != "" {
  86. if !setting.GroupInUserUsableGroups(playgroundRequest.Group) && playgroundRequest.Group != userGroup {
  87. abortWithOpenAiMessage(c, http.StatusForbidden, "无权访问该分组")
  88. return
  89. }
  90. userGroup = playgroundRequest.Group
  91. }
  92. }
  93. channel, selectGroup, err = model.CacheGetRandomSatisfiedChannel(c, userGroup, modelRequest.Model, 0)
  94. if err != nil {
  95. showGroup := userGroup
  96. if userGroup == "auto" {
  97. showGroup = fmt.Sprintf("auto(%s)", selectGroup)
  98. }
  99. message := fmt.Sprintf("获取分组 %s 下模型 %s 的可用渠道失败(数据库一致性已被破坏,distributor): %s", showGroup, modelRequest.Model, err.Error())
  100. // 如果错误,但是渠道不为空,说明是数据库一致性问题
  101. //if channel != nil {
  102. // common.SysError(fmt.Sprintf("渠道不存在:%d", channel.Id))
  103. // message = "数据库一致性已被破坏,请联系管理员"
  104. //}
  105. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, message, string(types.ErrorCodeModelNotFound))
  106. return
  107. }
  108. if channel == nil {
  109. abortWithOpenAiMessage(c, http.StatusServiceUnavailable, fmt.Sprintf("分组 %s 下模型 %s 无可用渠道(distributor)", userGroup, modelRequest.Model), string(types.ErrorCodeModelNotFound))
  110. return
  111. }
  112. }
  113. }
  114. common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
  115. SetupContextForSelectedChannel(c, channel, modelRequest.Model)
  116. c.Next()
  117. }
  118. }
  119. func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
  120. var modelRequest ModelRequest
  121. shouldSelectChannel := true
  122. var err error
  123. if strings.Contains(c.Request.URL.Path, "/mj/") {
  124. relayMode := relayconstant.Path2RelayModeMidjourney(c.Request.URL.Path)
  125. if relayMode == relayconstant.RelayModeMidjourneyTaskFetch ||
  126. relayMode == relayconstant.RelayModeMidjourneyTaskFetchByCondition ||
  127. relayMode == relayconstant.RelayModeMidjourneyNotify ||
  128. relayMode == relayconstant.RelayModeMidjourneyTaskImageSeed {
  129. shouldSelectChannel = false
  130. } else {
  131. midjourneyRequest := dto.MidjourneyRequest{}
  132. err = common.UnmarshalBodyReusable(c, &midjourneyRequest)
  133. if err != nil {
  134. return nil, false, err
  135. }
  136. midjourneyModel, mjErr, success := service.GetMjRequestModel(relayMode, &midjourneyRequest)
  137. if mjErr != nil {
  138. return nil, false, fmt.Errorf(mjErr.Description)
  139. }
  140. if midjourneyModel == "" {
  141. if !success {
  142. return nil, false, fmt.Errorf("无效的请求, 无法解析模型")
  143. } else {
  144. // task fetch, task fetch by condition, notify
  145. shouldSelectChannel = false
  146. }
  147. }
  148. modelRequest.Model = midjourneyModel
  149. }
  150. c.Set("relay_mode", relayMode)
  151. } else if strings.Contains(c.Request.URL.Path, "/suno/") {
  152. relayMode := relayconstant.Path2RelaySuno(c.Request.Method, c.Request.URL.Path)
  153. if relayMode == relayconstant.RelayModeSunoFetch ||
  154. relayMode == relayconstant.RelayModeSunoFetchByID {
  155. shouldSelectChannel = false
  156. } else {
  157. modelName := service.CoverTaskActionToModelName(constant.TaskPlatformSuno, c.Param("action"))
  158. modelRequest.Model = modelName
  159. }
  160. c.Set("platform", string(constant.TaskPlatformSuno))
  161. c.Set("relay_mode", relayMode)
  162. } else if strings.Contains(c.Request.URL.Path, "/v1/videos") {
  163. //curl https://api.openai.com/v1/videos \
  164. // -H "Authorization: Bearer $OPENAI_API_KEY" \
  165. // -F "model=sora-2" \
  166. // -F "prompt=A calico cat playing a piano on stage"
  167. // -F input_reference="@image.jpg"
  168. relayMode := relayconstant.RelayModeUnknown
  169. if c.Request.Method == http.MethodPost {
  170. relayMode = relayconstant.RelayModeVideoSubmit
  171. contentType := c.Request.Header.Get("Content-Type")
  172. if strings.HasPrefix(contentType, "multipart/form-data") {
  173. form, err := common.ParseMultipartFormReusable(c)
  174. if err != nil {
  175. return nil, false, errors.New("无效的video请求, " + err.Error())
  176. }
  177. defer form.RemoveAll()
  178. if form != nil {
  179. if values, ok := form.Value["model"]; ok && len(values) > 0 {
  180. modelRequest.Model = values[0]
  181. }
  182. }
  183. } else if strings.HasPrefix(contentType, "application/json") {
  184. err = common.UnmarshalBodyReusable(c, &modelRequest)
  185. if err != nil {
  186. return nil, false, errors.New("无效的video请求, " + err.Error())
  187. }
  188. }
  189. } else if c.Request.Method == http.MethodGet {
  190. relayMode = relayconstant.RelayModeVideoFetchByID
  191. shouldSelectChannel = false
  192. }
  193. c.Set("relay_mode", relayMode)
  194. } else if strings.Contains(c.Request.URL.Path, "/v1/video/generations") {
  195. relayMode := relayconstant.RelayModeUnknown
  196. if c.Request.Method == http.MethodPost {
  197. err = common.UnmarshalBodyReusable(c, &modelRequest)
  198. if err != nil {
  199. return nil, false, errors.New("video无效的请求, " + err.Error())
  200. }
  201. relayMode = relayconstant.RelayModeVideoSubmit
  202. } else if c.Request.Method == http.MethodGet {
  203. relayMode = relayconstant.RelayModeVideoFetchByID
  204. shouldSelectChannel = false
  205. }
  206. if _, ok := c.Get("relay_mode"); !ok {
  207. c.Set("relay_mode", relayMode)
  208. }
  209. } else if strings.HasPrefix(c.Request.URL.Path, "/v1beta/models/") || strings.HasPrefix(c.Request.URL.Path, "/v1/models/") {
  210. // Gemini API 路径处理: /v1beta/models/gemini-2.0-flash:generateContent
  211. relayMode := relayconstant.RelayModeGemini
  212. modelName := extractModelNameFromGeminiPath(c.Request.URL.Path)
  213. if modelName != "" {
  214. modelRequest.Model = modelName
  215. }
  216. c.Set("relay_mode", relayMode)
  217. } else if !strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") && !strings.Contains(c.Request.Header.Get("Content-Type"), "multipart/form-data") {
  218. err = common.UnmarshalBodyReusable(c, &modelRequest)
  219. }
  220. if err != nil {
  221. return nil, false, errors.New("无效的请求, " + err.Error())
  222. }
  223. if strings.HasPrefix(c.Request.URL.Path, "/v1/realtime") {
  224. //wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01
  225. modelRequest.Model = c.Query("model")
  226. }
  227. if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  228. if modelRequest.Model == "" {
  229. modelRequest.Model = "text-moderation-stable"
  230. }
  231. }
  232. if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  233. if modelRequest.Model == "" {
  234. modelRequest.Model = c.Param("model")
  235. }
  236. }
  237. if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  238. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "dall-e")
  239. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/edits") {
  240. //modelRequest.Model = common.GetStringIfEmpty(c.PostForm("model"), "gpt-image-1")
  241. if strings.Contains(c.Request.Header.Get("Content-Type"), "multipart/form-data") {
  242. modelRequest.Model = c.PostForm("model")
  243. }
  244. }
  245. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  246. relayMode := relayconstant.RelayModeAudioSpeech
  247. if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/speech") {
  248. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "tts-1")
  249. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/translations") {
  250. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, c.PostForm("model"))
  251. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "whisper-1")
  252. relayMode = relayconstant.RelayModeAudioTranslation
  253. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
  254. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, c.PostForm("model"))
  255. modelRequest.Model = common.GetStringIfEmpty(modelRequest.Model, "whisper-1")
  256. relayMode = relayconstant.RelayModeAudioTranscription
  257. }
  258. c.Set("relay_mode", relayMode)
  259. }
  260. if strings.HasPrefix(c.Request.URL.Path, "/pg/chat/completions") {
  261. // playground chat completions
  262. err = common.UnmarshalBodyReusable(c, &modelRequest)
  263. if err != nil {
  264. return nil, false, errors.New("无效的请求, " + err.Error())
  265. }
  266. common.SetContextKey(c, constant.ContextKeyTokenGroup, modelRequest.Group)
  267. }
  268. return &modelRequest, shouldSelectChannel, nil
  269. }
  270. func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, modelName string) *types.NewAPIError {
  271. c.Set("original_model", modelName) // for retry
  272. if channel == nil {
  273. return types.NewError(errors.New("channel is nil"), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  274. }
  275. common.SetContextKey(c, constant.ContextKeyChannelId, channel.Id)
  276. common.SetContextKey(c, constant.ContextKeyChannelName, channel.Name)
  277. common.SetContextKey(c, constant.ContextKeyChannelType, channel.Type)
  278. common.SetContextKey(c, constant.ContextKeyChannelCreateTime, channel.CreatedTime)
  279. common.SetContextKey(c, constant.ContextKeyChannelSetting, channel.GetSetting())
  280. common.SetContextKey(c, constant.ContextKeyChannelOtherSetting, channel.GetOtherSettings())
  281. common.SetContextKey(c, constant.ContextKeyChannelParamOverride, channel.GetParamOverride())
  282. common.SetContextKey(c, constant.ContextKeyChannelHeaderOverride, channel.GetHeaderOverride())
  283. if nil != channel.OpenAIOrganization && *channel.OpenAIOrganization != "" {
  284. common.SetContextKey(c, constant.ContextKeyChannelOrganization, *channel.OpenAIOrganization)
  285. }
  286. common.SetContextKey(c, constant.ContextKeyChannelAutoBan, channel.GetAutoBan())
  287. common.SetContextKey(c, constant.ContextKeyChannelModelMapping, channel.GetModelMapping())
  288. common.SetContextKey(c, constant.ContextKeyChannelStatusCodeMapping, channel.GetStatusCodeMapping())
  289. key, index, newAPIError := channel.GetNextEnabledKey()
  290. if newAPIError != nil {
  291. return newAPIError
  292. }
  293. if channel.ChannelInfo.IsMultiKey {
  294. common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, true)
  295. common.SetContextKey(c, constant.ContextKeyChannelMultiKeyIndex, index)
  296. } else {
  297. // 必须设置为 false,否则在重试到单个 key 的时候会导致日志显示错误
  298. common.SetContextKey(c, constant.ContextKeyChannelIsMultiKey, false)
  299. }
  300. // c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", key))
  301. common.SetContextKey(c, constant.ContextKeyChannelKey, key)
  302. common.SetContextKey(c, constant.ContextKeyChannelBaseUrl, channel.GetBaseURL())
  303. common.SetContextKey(c, constant.ContextKeySystemPromptOverride, false)
  304. // TODO: api_version统一
  305. switch channel.Type {
  306. case constant.ChannelTypeAzure:
  307. c.Set("api_version", channel.Other)
  308. case constant.ChannelTypeVertexAi:
  309. c.Set("region", channel.Other)
  310. case constant.ChannelTypeXunfei:
  311. c.Set("api_version", channel.Other)
  312. case constant.ChannelTypeGemini:
  313. c.Set("api_version", channel.Other)
  314. case constant.ChannelTypeAli:
  315. c.Set("plugin", channel.Other)
  316. case constant.ChannelCloudflare:
  317. c.Set("api_version", channel.Other)
  318. case constant.ChannelTypeMokaAI:
  319. c.Set("api_version", channel.Other)
  320. case constant.ChannelTypeCoze:
  321. c.Set("bot_id", channel.Other)
  322. }
  323. return nil
  324. }
  325. // extractModelNameFromGeminiPath 从 Gemini API URL 路径中提取模型名
  326. // 输入格式: /v1beta/models/gemini-2.0-flash:generateContent
  327. // 输出: gemini-2.0-flash
  328. func extractModelNameFromGeminiPath(path string) string {
  329. // 查找 "/models/" 的位置
  330. modelsPrefix := "/models/"
  331. modelsIndex := strings.Index(path, modelsPrefix)
  332. if modelsIndex == -1 {
  333. return ""
  334. }
  335. // 从 "/models/" 之后开始提取
  336. startIndex := modelsIndex + len(modelsPrefix)
  337. if startIndex >= len(path) {
  338. return ""
  339. }
  340. // 查找 ":" 的位置,模型名在 ":" 之前
  341. colonIndex := strings.Index(path[startIndex:], ":")
  342. if colonIndex == -1 {
  343. // 如果没有找到 ":",返回从 "/models/" 到路径结尾的部分
  344. return path[startIndex:]
  345. }
  346. // 返回模型名部分
  347. return path[startIndex : startIndex+colonIndex]
  348. }