relay.go 15 KB

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