relay.go 14 KB

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