relay.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 = types.NewError(err, types.ErrorCodeGetChannelFailed)
  76. break
  77. }
  78. newAPIError = relayRequest(c, relayMode, channel)
  79. if newAPIError == nil {
  80. return // 成功处理请求,直接返回
  81. }
  82. go processChannelError(c, channel.Id, channel.Type, channel.Name, 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 = types.NewError(err, types.ErrorCodeGetChannelFailed)
  128. break
  129. }
  130. newAPIError = wssRequest(c, ws, relayMode, channel)
  131. if newAPIError == nil {
  132. return // 成功处理请求,直接返回
  133. }
  134. go processChannelError(c, channel.Id, channel.Type, channel.Name, 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 = types.NewError(err, types.ErrorCodeGetChannelFailed)
  163. break
  164. }
  165. newAPIError = claudeRequest(c, channel)
  166. if newAPIError == nil {
  167. return // 成功处理请求,直接返回
  168. }
  169. go processChannelError(c, channel.Id, channel.Type, channel.Name, 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, error) {
  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, errors.New(fmt.Sprintf("获取自动分组下模型 %s 的可用渠道失败: %s", originalModel, err.Error()))
  228. }
  229. return nil, errors.New(fmt.Sprintf("获取分组 %s 下模型 %s 的可用渠道失败: %s", selectGroup, originalModel, err.Error()))
  230. }
  231. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  232. return channel, nil
  233. }
  234. func shouldRetry(c *gin.Context, openaiErr *types.NewAPIError, retryTimes int) bool {
  235. if openaiErr == nil {
  236. return false
  237. }
  238. if types.IsChannelError(openaiErr) {
  239. return true
  240. }
  241. if types.IsLocalError(openaiErr) {
  242. return false
  243. }
  244. if retryTimes <= 0 {
  245. return false
  246. }
  247. if _, ok := c.Get("specific_channel_id"); ok {
  248. return false
  249. }
  250. if openaiErr.StatusCode == http.StatusTooManyRequests {
  251. return true
  252. }
  253. if openaiErr.StatusCode == 307 {
  254. return true
  255. }
  256. if openaiErr.StatusCode/100 == 5 {
  257. // 超时不重试
  258. if openaiErr.StatusCode == 504 || openaiErr.StatusCode == 524 {
  259. return false
  260. }
  261. return true
  262. }
  263. if openaiErr.StatusCode == http.StatusBadRequest {
  264. channelType := c.GetInt("channel_type")
  265. if channelType == constant.ChannelTypeAnthropic {
  266. return true
  267. }
  268. return false
  269. }
  270. if openaiErr.StatusCode == 408 {
  271. // azure处理超时不重试
  272. return false
  273. }
  274. if openaiErr.StatusCode/100 == 2 {
  275. return false
  276. }
  277. return true
  278. }
  279. func processChannelError(c *gin.Context, channelId int, channelType int, channelName string, autoBan bool, err *types.NewAPIError) {
  280. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  281. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  282. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code: %d): %s", channelId, err.StatusCode, err.Error()))
  283. if service.ShouldDisableChannel(channelType, err) && autoBan {
  284. service.DisableChannel(channelId, channelName, err.Error())
  285. }
  286. }
  287. func RelayMidjourney(c *gin.Context) {
  288. relayMode := c.GetInt("relay_mode")
  289. var err *dto.MidjourneyResponse
  290. switch relayMode {
  291. case relayconstant.RelayModeMidjourneyNotify:
  292. err = relay.RelayMidjourneyNotify(c)
  293. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  294. err = relay.RelayMidjourneyTask(c, relayMode)
  295. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  296. err = relay.RelayMidjourneyTaskImageSeed(c)
  297. case relayconstant.RelayModeSwapFace:
  298. err = relay.RelaySwapFace(c)
  299. default:
  300. err = relay.RelayMidjourneySubmit(c, relayMode)
  301. }
  302. //err = relayMidjourneySubmit(c, relayMode)
  303. log.Println(err)
  304. if err != nil {
  305. statusCode := http.StatusBadRequest
  306. if err.Code == 30 {
  307. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  308. statusCode = http.StatusTooManyRequests
  309. }
  310. c.JSON(statusCode, gin.H{
  311. "description": fmt.Sprintf("%s %s", err.Description, err.Result),
  312. "type": "upstream_error",
  313. "code": err.Code,
  314. })
  315. channelId := c.GetInt("channel_id")
  316. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", err.Description, err.Result)))
  317. }
  318. }
  319. func RelayNotImplemented(c *gin.Context) {
  320. err := dto.OpenAIError{
  321. Message: "API not implemented",
  322. Type: "new_api_error",
  323. Param: "",
  324. Code: "api_not_implemented",
  325. }
  326. c.JSON(http.StatusNotImplemented, gin.H{
  327. "error": err,
  328. })
  329. }
  330. func RelayNotFound(c *gin.Context) {
  331. err := dto.OpenAIError{
  332. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  333. Type: "invalid_request_error",
  334. Param: "",
  335. Code: "",
  336. }
  337. c.JSON(http.StatusNotFound, gin.H{
  338. "error": err,
  339. })
  340. }
  341. func RelayTask(c *gin.Context) {
  342. retryTimes := common.RetryTimes
  343. channelId := c.GetInt("channel_id")
  344. relayMode := c.GetInt("relay_mode")
  345. group := c.GetString("group")
  346. originalModel := c.GetString("original_model")
  347. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  348. taskErr := taskRelayHandler(c, relayMode)
  349. if taskErr == nil {
  350. retryTimes = 0
  351. }
  352. for i := 0; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && i < retryTimes; i++ {
  353. channel, err := getChannel(c, group, originalModel, i)
  354. if err != nil {
  355. common.LogError(c, fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", err.Error()))
  356. taskErr = service.TaskErrorWrapperLocal(err, "get_channel_failed", http.StatusInternalServerError)
  357. break
  358. }
  359. channelId = channel.Id
  360. useChannel := c.GetStringSlice("use_channel")
  361. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  362. c.Set("use_channel", useChannel)
  363. common.LogInfo(c, fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  364. //middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  365. requestBody, err := common.GetRequestBody(c)
  366. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  367. taskErr = taskRelayHandler(c, relayMode)
  368. }
  369. useChannel := c.GetStringSlice("use_channel")
  370. if len(useChannel) > 1 {
  371. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  372. common.LogInfo(c, retryLogStr)
  373. }
  374. if taskErr != nil {
  375. if taskErr.StatusCode == http.StatusTooManyRequests {
  376. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  377. }
  378. c.JSON(taskErr.StatusCode, taskErr)
  379. }
  380. }
  381. func taskRelayHandler(c *gin.Context, relayMode int) *dto.TaskError {
  382. var err *dto.TaskError
  383. switch relayMode {
  384. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID, relayconstant.RelayModeKlingFetchByID:
  385. err = relay.RelayTaskFetch(c, relayMode)
  386. default:
  387. err = relay.RelayTaskSubmit(c, relayMode)
  388. }
  389. return err
  390. }
  391. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  392. if taskErr == nil {
  393. return false
  394. }
  395. if retryTimes <= 0 {
  396. return false
  397. }
  398. if _, ok := c.Get("specific_channel_id"); ok {
  399. return false
  400. }
  401. if taskErr.StatusCode == http.StatusTooManyRequests {
  402. return true
  403. }
  404. if taskErr.StatusCode == 307 {
  405. return true
  406. }
  407. if taskErr.StatusCode/100 == 5 {
  408. // 超时不重试
  409. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  410. return false
  411. }
  412. return true
  413. }
  414. if taskErr.StatusCode == http.StatusBadRequest {
  415. return false
  416. }
  417. if taskErr.StatusCode == 408 {
  418. // azure处理超时不重试
  419. return false
  420. }
  421. if taskErr.LocalError {
  422. return false
  423. }
  424. if taskErr.StatusCode/100 == 2 {
  425. return false
  426. }
  427. return true
  428. }