relay.go 13 KB

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