relay.go 14 KB

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