relay.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. package controller
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/constant"
  11. constant2 "one-api/constant"
  12. "one-api/dto"
  13. "one-api/middleware"
  14. "one-api/model"
  15. "one-api/relay"
  16. relayconstant "one-api/relay/constant"
  17. "one-api/relay/helper"
  18. "one-api/service"
  19. "one-api/types"
  20. "strings"
  21. "github.com/gin-gonic/gin"
  22. "github.com/gorilla/websocket"
  23. )
  24. func relayHandler(c *gin.Context, relayMode int) *types.NewAPIError {
  25. var err *types.NewAPIError
  26. switch relayMode {
  27. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  28. err = relay.ImageHelper(c)
  29. case relayconstant.RelayModeAudioSpeech:
  30. fallthrough
  31. case relayconstant.RelayModeAudioTranslation:
  32. fallthrough
  33. case relayconstant.RelayModeAudioTranscription:
  34. err = relay.AudioHelper(c)
  35. case relayconstant.RelayModeRerank:
  36. err = relay.RerankHelper(c, relayMode)
  37. case relayconstant.RelayModeEmbeddings:
  38. err = relay.EmbeddingHelper(c)
  39. case relayconstant.RelayModeResponses:
  40. err = relay.ResponsesHelper(c)
  41. case relayconstant.RelayModeGemini:
  42. if strings.Contains(c.Request.URL.Path, "embed") {
  43. err = relay.GeminiEmbeddingHandler(c)
  44. } else {
  45. err = relay.GeminiHelper(c)
  46. }
  47. default:
  48. err = relay.TextHelper(c)
  49. }
  50. if constant2.ErrorLogEnabled && err != nil && types.IsRecordErrorLog(err) {
  51. // 保存错误日志到mysql中
  52. userId := c.GetInt("id")
  53. tokenName := c.GetString("token_name")
  54. modelName := c.GetString("original_model")
  55. tokenId := c.GetInt("token_id")
  56. userGroup := c.GetString("group")
  57. channelId := c.GetInt("channel_id")
  58. other := make(map[string]interface{})
  59. other["error_type"] = err.GetErrorType()
  60. other["error_code"] = err.GetErrorCode()
  61. other["status_code"] = err.StatusCode
  62. other["channel_id"] = channelId
  63. other["channel_name"] = c.GetString("channel_name")
  64. other["channel_type"] = c.GetInt("channel_type")
  65. adminInfo := make(map[string]interface{})
  66. adminInfo["use_channel"] = c.GetStringSlice("use_channel")
  67. isMultiKey := common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey)
  68. if isMultiKey {
  69. adminInfo["is_multi_key"] = true
  70. adminInfo["multi_key_index"] = common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex)
  71. }
  72. other["admin_info"] = adminInfo
  73. model.RecordErrorLog(c, userId, channelId, modelName, tokenName, err.MaskSensitiveError(), tokenId, 0, false, userGroup, other)
  74. }
  75. return err
  76. }
  77. func Relay(c *gin.Context) {
  78. relayMode := relayconstant.Path2RelayMode(c.Request.URL.Path)
  79. requestId := c.GetString(common.RequestIdKey)
  80. group := c.GetString("group")
  81. originalModel := c.GetString("original_model")
  82. var newAPIError *types.NewAPIError
  83. for i := 0; i <= common.RetryTimes; i++ {
  84. channel, err := getChannel(c, group, originalModel, i)
  85. if err != nil {
  86. common.LogError(c, err.Error())
  87. newAPIError = err
  88. break
  89. }
  90. newAPIError = relayRequest(c, relayMode, channel)
  91. if newAPIError == nil {
  92. return // 成功处理请求,直接返回
  93. }
  94. go processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  95. if !shouldRetry(c, newAPIError, common.RetryTimes-i) {
  96. break
  97. }
  98. }
  99. useChannel := c.GetStringSlice("use_channel")
  100. if len(useChannel) > 1 {
  101. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  102. common.LogInfo(c, retryLogStr)
  103. }
  104. if newAPIError != nil {
  105. //if newAPIError.StatusCode == http.StatusTooManyRequests {
  106. // common.LogError(c, fmt.Sprintf("origin 429 error: %s", newAPIError.Error()))
  107. // newAPIError.SetMessage("当前分组上游负载已饱和,请稍后再试")
  108. //}
  109. newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId))
  110. c.JSON(newAPIError.StatusCode, gin.H{
  111. "error": newAPIError.ToOpenAIError(),
  112. })
  113. }
  114. }
  115. var upgrader = websocket.Upgrader{
  116. Subprotocols: []string{"realtime"}, // WS 握手支持的协议,如果有使用 Sec-WebSocket-Protocol,则必须在此声明对应的 Protocol TODO add other protocol
  117. CheckOrigin: func(r *http.Request) bool {
  118. return true // 允许跨域
  119. },
  120. }
  121. func WssRelay(c *gin.Context) {
  122. // 将 HTTP 连接升级为 WebSocket 连接
  123. ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  124. defer ws.Close()
  125. if err != nil {
  126. helper.WssError(c, ws, types.NewError(err, types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry()).ToOpenAIError())
  127. return
  128. }
  129. relayMode := relayconstant.Path2RelayMode(c.Request.URL.Path)
  130. requestId := c.GetString(common.RequestIdKey)
  131. group := c.GetString("group")
  132. //wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01
  133. originalModel := c.GetString("original_model")
  134. var newAPIError *types.NewAPIError
  135. for i := 0; i <= common.RetryTimes; i++ {
  136. channel, err := getChannel(c, group, originalModel, i)
  137. if err != nil {
  138. common.LogError(c, err.Error())
  139. newAPIError = err
  140. break
  141. }
  142. newAPIError = wssRequest(c, ws, relayMode, channel)
  143. if newAPIError == nil {
  144. return // 成功处理请求,直接返回
  145. }
  146. go processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  147. if !shouldRetry(c, newAPIError, common.RetryTimes-i) {
  148. break
  149. }
  150. }
  151. useChannel := c.GetStringSlice("use_channel")
  152. if len(useChannel) > 1 {
  153. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  154. common.LogInfo(c, retryLogStr)
  155. }
  156. if newAPIError != nil {
  157. //if newAPIError.StatusCode == http.StatusTooManyRequests {
  158. // newAPIError.SetMessage("当前分组上游负载已饱和,请稍后再试")
  159. //}
  160. newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId))
  161. helper.WssError(c, ws, newAPIError.ToOpenAIError())
  162. }
  163. }
  164. func RelayClaude(c *gin.Context) {
  165. //relayMode := constant.Path2RelayMode(c.Request.URL.Path)
  166. requestId := c.GetString(common.RequestIdKey)
  167. group := c.GetString("group")
  168. originalModel := c.GetString("original_model")
  169. var newAPIError *types.NewAPIError
  170. for i := 0; i <= common.RetryTimes; i++ {
  171. channel, err := getChannel(c, group, originalModel, i)
  172. if err != nil {
  173. common.LogError(c, err.Error())
  174. newAPIError = err
  175. break
  176. }
  177. newAPIError = claudeRequest(c, channel)
  178. if newAPIError == nil {
  179. return // 成功处理请求,直接返回
  180. }
  181. go processChannelError(c, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(c, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  182. if !shouldRetry(c, newAPIError, common.RetryTimes-i) {
  183. break
  184. }
  185. }
  186. useChannel := c.GetStringSlice("use_channel")
  187. if len(useChannel) > 1 {
  188. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  189. common.LogInfo(c, retryLogStr)
  190. }
  191. if newAPIError != nil {
  192. newAPIError.SetMessage(common.MessageWithRequestId(newAPIError.Error(), requestId))
  193. c.JSON(newAPIError.StatusCode, gin.H{
  194. "type": "error",
  195. "error": newAPIError.ToClaudeError(),
  196. })
  197. }
  198. }
  199. func relayRequest(c *gin.Context, relayMode int, channel *model.Channel) *types.NewAPIError {
  200. addUsedChannel(c, channel.Id)
  201. requestBody, _ := common.GetRequestBody(c)
  202. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  203. return relayHandler(c, relayMode)
  204. }
  205. func wssRequest(c *gin.Context, ws *websocket.Conn, relayMode int, channel *model.Channel) *types.NewAPIError {
  206. addUsedChannel(c, channel.Id)
  207. requestBody, _ := common.GetRequestBody(c)
  208. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  209. return relay.WssHelper(c, ws)
  210. }
  211. func claudeRequest(c *gin.Context, channel *model.Channel) *types.NewAPIError {
  212. addUsedChannel(c, channel.Id)
  213. requestBody, _ := common.GetRequestBody(c)
  214. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  215. return relay.ClaudeHelper(c)
  216. }
  217. func addUsedChannel(c *gin.Context, channelId int) {
  218. useChannel := c.GetStringSlice("use_channel")
  219. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  220. c.Set("use_channel", useChannel)
  221. }
  222. func getChannel(c *gin.Context, group, originalModel string, retryCount int) (*model.Channel, *types.NewAPIError) {
  223. if retryCount == 0 {
  224. autoBan := c.GetBool("auto_ban")
  225. autoBanInt := 1
  226. if !autoBan {
  227. autoBanInt = 0
  228. }
  229. return &model.Channel{
  230. Id: c.GetInt("channel_id"),
  231. Type: c.GetInt("channel_type"),
  232. Name: c.GetString("channel_name"),
  233. AutoBan: &autoBanInt,
  234. }, nil
  235. }
  236. channel, selectGroup, err := model.CacheGetRandomSatisfiedChannel(c, group, originalModel, retryCount)
  237. if err != nil {
  238. return nil, types.NewError(errors.New(fmt.Sprintf("获取分组 %s 下模型 %s 的可用渠道失败(retry): %s", selectGroup, originalModel, err.Error())), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  239. }
  240. if channel == nil {
  241. return nil, types.NewError(errors.New(fmt.Sprintf("分组 %s 下模型 %s 的可用渠道不存在(数据库一致性已被破坏,retry)", selectGroup, originalModel)), types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  242. }
  243. newAPIError := middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  244. if newAPIError != nil {
  245. return nil, newAPIError
  246. }
  247. return channel, nil
  248. }
  249. func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
  250. if openaiErr == nil {
  251. return false
  252. }
  253. if types.IsChannelError(openaiErr) {
  254. return true
  255. }
  256. if types.IsSkipRetryError(openaiErr) {
  257. return false
  258. }
  259. if retryTimes <= 0 {
  260. return false
  261. }
  262. if _, ok := c.Get("specific_channel_id"); ok {
  263. return false
  264. }
  265. if openaiErr.StatusCode == http.StatusTooManyRequests {
  266. return true
  267. }
  268. if openaiErr.StatusCode == 307 {
  269. return true
  270. }
  271. if openaiErr.StatusCode/100 == 5 {
  272. // 超时不重试
  273. if openaiErr.StatusCode == 504 || openaiErr.StatusCode == 524 {
  274. return false
  275. }
  276. return true
  277. }
  278. if openaiErr.StatusCode == http.StatusBadRequest {
  279. return false
  280. }
  281. if openaiErr.StatusCode == 408 {
  282. // azure处理超时不重试
  283. return false
  284. }
  285. if openaiErr.StatusCode/100 == 2 {
  286. return false
  287. }
  288. return true
  289. }
  290. func processChannelError(c *gin.Context, channelError types.ChannelError, err *types.NewAPIError) {
  291. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  292. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  293. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code: %d): %s", channelError.ChannelId, err.StatusCode, err.Error()))
  294. if service.ShouldDisableChannel(channelError.ChannelId, err) && channelError.AutoBan {
  295. service.DisableChannel(channelError, err.Error())
  296. }
  297. }
  298. func RelayMidjourney(c *gin.Context) {
  299. relayMode := c.GetInt("relay_mode")
  300. var err *dto.MidjourneyResponse
  301. switch relayMode {
  302. case relayconstant.RelayModeMidjourneyNotify:
  303. err = relay.RelayMidjourneyNotify(c)
  304. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  305. err = relay.RelayMidjourneyTask(c, relayMode)
  306. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  307. err = relay.RelayMidjourneyTaskImageSeed(c)
  308. case relayconstant.RelayModeSwapFace:
  309. err = relay.RelaySwapFace(c)
  310. default:
  311. err = relay.RelayMidjourneySubmit(c, relayMode)
  312. }
  313. //err = relayMidjourneySubmit(c, relayMode)
  314. log.Println(err)
  315. if err != nil {
  316. statusCode := http.StatusBadRequest
  317. if err.Code == 30 {
  318. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  319. statusCode = http.StatusTooManyRequests
  320. }
  321. c.JSON(statusCode, gin.H{
  322. "description": fmt.Sprintf("%s %s", err.Description, err.Result),
  323. "type": "upstream_error",
  324. "code": err.Code,
  325. })
  326. channelId := c.GetInt("channel_id")
  327. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", err.Description, err.Result)))
  328. }
  329. }
  330. func RelayNotImplemented(c *gin.Context) {
  331. err := dto.OpenAIError{
  332. Message: "API not implemented",
  333. Type: "new_api_error",
  334. Param: "",
  335. Code: "api_not_implemented",
  336. }
  337. c.JSON(http.StatusNotImplemented, gin.H{
  338. "error": err,
  339. })
  340. }
  341. func RelayNotFound(c *gin.Context) {
  342. err := dto.OpenAIError{
  343. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  344. Type: "invalid_request_error",
  345. Param: "",
  346. Code: "",
  347. }
  348. c.JSON(http.StatusNotFound, gin.H{
  349. "error": err,
  350. })
  351. }
  352. func RelayTask(c *gin.Context) {
  353. retryTimes := common.RetryTimes
  354. channelId := c.GetInt("channel_id")
  355. relayMode := c.GetInt("relay_mode")
  356. group := c.GetString("group")
  357. originalModel := c.GetString("original_model")
  358. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  359. taskErr := taskRelayHandler(c, relayMode)
  360. if taskErr == nil {
  361. retryTimes = 0
  362. }
  363. for i := 0; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && i < retryTimes; i++ {
  364. channel, newAPIError := getChannel(c, group, originalModel, i)
  365. if newAPIError != nil {
  366. common.LogError(c, fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", newAPIError.Error()))
  367. taskErr = service.TaskErrorWrapperLocal(newAPIError.Err, "get_channel_failed", http.StatusInternalServerError)
  368. break
  369. }
  370. channelId = channel.Id
  371. useChannel := c.GetStringSlice("use_channel")
  372. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  373. c.Set("use_channel", useChannel)
  374. common.LogInfo(c, fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  375. //middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  376. requestBody, _ := common.GetRequestBody(c)
  377. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  378. taskErr = taskRelayHandler(c, relayMode)
  379. }
  380. useChannel := c.GetStringSlice("use_channel")
  381. if len(useChannel) > 1 {
  382. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  383. common.LogInfo(c, retryLogStr)
  384. }
  385. if taskErr != nil {
  386. if taskErr.StatusCode == http.StatusTooManyRequests {
  387. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  388. }
  389. c.JSON(taskErr.StatusCode, taskErr)
  390. }
  391. }
  392. func taskRelayHandler(c *gin.Context, relayMode int) *dto.TaskError {
  393. var err *dto.TaskError
  394. switch relayMode {
  395. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID, relayconstant.RelayModeVideoFetchByID:
  396. err = relay.RelayTaskFetch(c, relayMode)
  397. default:
  398. err = relay.RelayTaskSubmit(c, relayMode)
  399. }
  400. return err
  401. }
  402. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  403. if taskErr == nil {
  404. return false
  405. }
  406. if retryTimes <= 0 {
  407. return false
  408. }
  409. if _, ok := c.Get("specific_channel_id"); ok {
  410. return false
  411. }
  412. if taskErr.StatusCode == http.StatusTooManyRequests {
  413. return true
  414. }
  415. if taskErr.StatusCode == 307 {
  416. return true
  417. }
  418. if taskErr.StatusCode/100 == 5 {
  419. // 超时不重试
  420. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  421. return false
  422. }
  423. return true
  424. }
  425. if taskErr.StatusCode == http.StatusBadRequest {
  426. return false
  427. }
  428. if taskErr.StatusCode == 408 {
  429. // azure处理超时不重试
  430. return false
  431. }
  432. if taskErr.LocalError {
  433. return false
  434. }
  435. if taskErr.StatusCode/100 == 2 {
  436. return false
  437. }
  438. return true
  439. }