relay.go 15 KB

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