relay.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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, _, err := model.CacheGetRandomSatisfiedChannel(c, group, originalModel, retryCount)
  226. if err != nil {
  227. return nil, errors.New(fmt.Sprintf("获取重试渠道失败: %s", err.Error()))
  228. }
  229. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  230. return channel, nil
  231. }
  232. func shouldRetry(c *gin.Context, openaiErr *dto.OpenAIErrorWithStatusCode, retryTimes int) bool {
  233. if openaiErr == nil {
  234. return false
  235. }
  236. if openaiErr.LocalError {
  237. return false
  238. }
  239. if retryTimes <= 0 {
  240. return false
  241. }
  242. if _, ok := c.Get("specific_channel_id"); ok {
  243. return false
  244. }
  245. if openaiErr.StatusCode == http.StatusTooManyRequests {
  246. return true
  247. }
  248. if openaiErr.StatusCode == 307 {
  249. return true
  250. }
  251. if openaiErr.StatusCode/100 == 5 {
  252. // 超时不重试
  253. if openaiErr.StatusCode == 504 || openaiErr.StatusCode == 524 {
  254. return false
  255. }
  256. return true
  257. }
  258. if openaiErr.StatusCode == http.StatusBadRequest {
  259. channelType := c.GetInt("channel_type")
  260. if channelType == constant.ChannelTypeAnthropic {
  261. return true
  262. }
  263. return false
  264. }
  265. if openaiErr.StatusCode == 408 {
  266. // azure处理超时不重试
  267. return false
  268. }
  269. if openaiErr.StatusCode/100 == 2 {
  270. return false
  271. }
  272. return true
  273. }
  274. func processChannelError(c *gin.Context, channelId int, channelType int, channelName string, autoBan bool, err *dto.OpenAIErrorWithStatusCode) {
  275. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  276. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  277. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code: %d): %s", channelId, err.StatusCode, err.Error.Message))
  278. if service.ShouldDisableChannel(channelType, err) && autoBan {
  279. service.DisableChannel(channelId, channelName, err.Error.Message)
  280. }
  281. }
  282. func RelayMidjourney(c *gin.Context) {
  283. relayMode := c.GetInt("relay_mode")
  284. var err *dto.MidjourneyResponse
  285. switch relayMode {
  286. case relayconstant.RelayModeMidjourneyNotify:
  287. err = relay.RelayMidjourneyNotify(c)
  288. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  289. err = relay.RelayMidjourneyTask(c, relayMode)
  290. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  291. err = relay.RelayMidjourneyTaskImageSeed(c)
  292. case relayconstant.RelayModeSwapFace:
  293. err = relay.RelaySwapFace(c)
  294. default:
  295. err = relay.RelayMidjourneySubmit(c, relayMode)
  296. }
  297. //err = relayMidjourneySubmit(c, relayMode)
  298. log.Println(err)
  299. if err != nil {
  300. statusCode := http.StatusBadRequest
  301. if err.Code == 30 {
  302. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  303. statusCode = http.StatusTooManyRequests
  304. }
  305. c.JSON(statusCode, gin.H{
  306. "description": fmt.Sprintf("%s %s", err.Description, err.Result),
  307. "type": "upstream_error",
  308. "code": err.Code,
  309. })
  310. channelId := c.GetInt("channel_id")
  311. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", err.Description, err.Result)))
  312. }
  313. }
  314. func RelayNotImplemented(c *gin.Context) {
  315. err := dto.OpenAIError{
  316. Message: "API not implemented",
  317. Type: "new_api_error",
  318. Param: "",
  319. Code: "api_not_implemented",
  320. }
  321. c.JSON(http.StatusNotImplemented, gin.H{
  322. "error": err,
  323. })
  324. }
  325. func RelayNotFound(c *gin.Context) {
  326. err := dto.OpenAIError{
  327. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  328. Type: "invalid_request_error",
  329. Param: "",
  330. Code: "",
  331. }
  332. c.JSON(http.StatusNotFound, gin.H{
  333. "error": err,
  334. })
  335. }
  336. func RelayTask(c *gin.Context) {
  337. retryTimes := common.RetryTimes
  338. channelId := c.GetInt("channel_id")
  339. relayMode := c.GetInt("relay_mode")
  340. group := c.GetString("group")
  341. originalModel := c.GetString("original_model")
  342. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  343. taskErr := taskRelayHandler(c, relayMode)
  344. if taskErr == nil {
  345. retryTimes = 0
  346. }
  347. for i := 0; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && i < retryTimes; i++ {
  348. channel, _, err := model.CacheGetRandomSatisfiedChannel(c, group, originalModel, i)
  349. if err != nil {
  350. common.LogError(c, fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", err.Error()))
  351. break
  352. }
  353. channelId = channel.Id
  354. useChannel := c.GetStringSlice("use_channel")
  355. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  356. c.Set("use_channel", useChannel)
  357. common.LogInfo(c, fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  358. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  359. requestBody, err := common.GetRequestBody(c)
  360. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  361. taskErr = taskRelayHandler(c, relayMode)
  362. }
  363. useChannel := c.GetStringSlice("use_channel")
  364. if len(useChannel) > 1 {
  365. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  366. common.LogInfo(c, retryLogStr)
  367. }
  368. if taskErr != nil {
  369. if taskErr.StatusCode == http.StatusTooManyRequests {
  370. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  371. }
  372. c.JSON(taskErr.StatusCode, taskErr)
  373. }
  374. }
  375. func taskRelayHandler(c *gin.Context, relayMode int) *dto.TaskError {
  376. var err *dto.TaskError
  377. switch relayMode {
  378. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID, relayconstant.RelayModeKlingFetchByID:
  379. err = relay.RelayTaskFetch(c, relayMode)
  380. default:
  381. err = relay.RelayTaskSubmit(c, relayMode)
  382. }
  383. return err
  384. }
  385. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  386. if taskErr == nil {
  387. return false
  388. }
  389. if retryTimes <= 0 {
  390. return false
  391. }
  392. if _, ok := c.Get("specific_channel_id"); ok {
  393. return false
  394. }
  395. if taskErr.StatusCode == http.StatusTooManyRequests {
  396. return true
  397. }
  398. if taskErr.StatusCode == 307 {
  399. return true
  400. }
  401. if taskErr.StatusCode/100 == 5 {
  402. // 超时不重试
  403. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  404. return false
  405. }
  406. return true
  407. }
  408. if taskErr.StatusCode == http.StatusBadRequest {
  409. return false
  410. }
  411. if taskErr.StatusCode == 408 {
  412. // azure处理超时不重试
  413. return false
  414. }
  415. if taskErr.LocalError {
  416. return false
  417. }
  418. if taskErr.StatusCode/100 == 2 {
  419. return false
  420. }
  421. return true
  422. }