relay.go 14 KB

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