relay.go 12 KB

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