relay.go 15 KB

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