relay.go 15 KB

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