relay.go 14 KB

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