relay.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package controller
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "log"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/dto"
  11. "one-api/middleware"
  12. "one-api/model"
  13. "one-api/relay"
  14. "one-api/relay/constant"
  15. relayconstant "one-api/relay/constant"
  16. "one-api/service"
  17. "strings"
  18. )
  19. func relayHandler(c *gin.Context, relayMode int) *dto.OpenAIErrorWithStatusCode {
  20. var err *dto.OpenAIErrorWithStatusCode
  21. switch relayMode {
  22. case relayconstant.RelayModeImagesGenerations:
  23. err = relay.RelayImageHelper(c, relayMode)
  24. case relayconstant.RelayModeAudioSpeech:
  25. fallthrough
  26. case relayconstant.RelayModeAudioTranslation:
  27. fallthrough
  28. case relayconstant.RelayModeAudioTranscription:
  29. err = relay.AudioHelper(c, relayMode)
  30. default:
  31. err = relay.TextHelper(c)
  32. }
  33. return err
  34. }
  35. func Relay(c *gin.Context) {
  36. relayMode := constant.Path2RelayMode(c.Request.URL.Path)
  37. retryTimes := common.RetryTimes
  38. requestId := c.GetString(common.RequestIdKey)
  39. channelId := c.GetInt("channel_id")
  40. group := c.GetString("group")
  41. originalModel := c.GetString("original_model")
  42. openaiErr := relayHandler(c, relayMode)
  43. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  44. if openaiErr != nil {
  45. go processChannelError(c, channelId, openaiErr)
  46. } else {
  47. retryTimes = 0
  48. }
  49. for i := 0; shouldRetry(c, channelId, openaiErr, retryTimes) && i < retryTimes; i++ {
  50. channel, err := model.CacheGetRandomSatisfiedChannel(group, originalModel, i)
  51. if err != nil {
  52. common.LogError(c.Request.Context(), fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", err.Error()))
  53. break
  54. }
  55. channelId = channel.Id
  56. useChannel := c.GetStringSlice("use_channel")
  57. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  58. c.Set("use_channel", useChannel)
  59. common.LogInfo(c.Request.Context(), fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  60. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  61. requestBody, err := common.GetRequestBody(c)
  62. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  63. openaiErr = relayHandler(c, relayMode)
  64. if openaiErr != nil {
  65. go processChannelError(c, channelId, openaiErr)
  66. }
  67. }
  68. useChannel := c.GetStringSlice("use_channel")
  69. if len(useChannel) > 1 {
  70. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  71. common.LogInfo(c.Request.Context(), retryLogStr)
  72. }
  73. if openaiErr != nil {
  74. if openaiErr.StatusCode == http.StatusTooManyRequests {
  75. openaiErr.Error.Message = "当前分组上游负载已饱和,请稍后再试"
  76. }
  77. openaiErr.Error.Message = common.MessageWithRequestId(openaiErr.Error.Message, requestId)
  78. c.JSON(openaiErr.StatusCode, gin.H{
  79. "error": openaiErr.Error,
  80. })
  81. }
  82. }
  83. func shouldRetry(c *gin.Context, channelId int, openaiErr *dto.OpenAIErrorWithStatusCode, retryTimes int) bool {
  84. if openaiErr == nil {
  85. return false
  86. }
  87. if retryTimes <= 0 {
  88. return false
  89. }
  90. if _, ok := c.Get("specific_channel_id"); ok {
  91. return false
  92. }
  93. if openaiErr.StatusCode == http.StatusTooManyRequests {
  94. return true
  95. }
  96. if openaiErr.StatusCode == 307 {
  97. return true
  98. }
  99. if openaiErr.StatusCode/100 == 5 {
  100. // 超时不重试
  101. if openaiErr.StatusCode == 504 || openaiErr.StatusCode == 524 {
  102. return false
  103. }
  104. return true
  105. }
  106. if openaiErr.StatusCode == http.StatusBadRequest {
  107. return false
  108. }
  109. if openaiErr.StatusCode == 408 {
  110. // azure处理超时不重试
  111. return false
  112. }
  113. if openaiErr.LocalError {
  114. return false
  115. }
  116. if openaiErr.StatusCode/100 == 2 {
  117. return false
  118. }
  119. return true
  120. }
  121. func processChannelError(c *gin.Context, channelId int, err *dto.OpenAIErrorWithStatusCode) {
  122. autoBan := c.GetBool("auto_ban")
  123. common.LogError(c.Request.Context(), fmt.Sprintf("relay error (channel #%d, status code: %d): %s", channelId, err.StatusCode, err.Error.Message))
  124. if service.ShouldDisableChannel(&err.Error, err.StatusCode) && autoBan {
  125. channelName := c.GetString("channel_name")
  126. service.DisableChannel(channelId, channelName, err.Error.Message)
  127. }
  128. }
  129. func RelayMidjourney(c *gin.Context) {
  130. relayMode := c.GetInt("relay_mode")
  131. var err *dto.MidjourneyResponse
  132. switch relayMode {
  133. case relayconstant.RelayModeMidjourneyNotify:
  134. err = relay.RelayMidjourneyNotify(c)
  135. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  136. err = relay.RelayMidjourneyTask(c, relayMode)
  137. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  138. err = relay.RelayMidjourneyTaskImageSeed(c)
  139. case relayconstant.RelayModeSwapFace:
  140. err = relay.RelaySwapFace(c)
  141. default:
  142. err = relay.RelayMidjourneySubmit(c, relayMode)
  143. }
  144. //err = relayMidjourneySubmit(c, relayMode)
  145. log.Println(err)
  146. if err != nil {
  147. statusCode := http.StatusBadRequest
  148. if err.Code == 30 {
  149. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  150. statusCode = http.StatusTooManyRequests
  151. }
  152. c.JSON(statusCode, gin.H{
  153. "description": fmt.Sprintf("%s %s", err.Description, err.Result),
  154. "type": "upstream_error",
  155. "code": err.Code,
  156. })
  157. channelId := c.GetInt("channel_id")
  158. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", err.Description, err.Result)))
  159. }
  160. }
  161. func RelayNotImplemented(c *gin.Context) {
  162. err := dto.OpenAIError{
  163. Message: "API not implemented",
  164. Type: "new_api_error",
  165. Param: "",
  166. Code: "api_not_implemented",
  167. }
  168. c.JSON(http.StatusNotImplemented, gin.H{
  169. "error": err,
  170. })
  171. }
  172. func RelayNotFound(c *gin.Context) {
  173. err := dto.OpenAIError{
  174. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  175. Type: "invalid_request_error",
  176. Param: "",
  177. Code: "",
  178. }
  179. c.JSON(http.StatusNotFound, gin.H{
  180. "error": err,
  181. })
  182. }
  183. func RelayTask(c *gin.Context) {
  184. retryTimes := common.RetryTimes
  185. channelId := c.GetInt("channel_id")
  186. relayMode := c.GetInt("relay_mode")
  187. group := c.GetString("group")
  188. originalModel := c.GetString("original_model")
  189. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  190. taskErr := taskRelayHandler(c, relayMode)
  191. if taskErr == nil {
  192. retryTimes = 0
  193. }
  194. for i := 0; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && i < retryTimes; i++ {
  195. channel, err := model.CacheGetRandomSatisfiedChannel(group, originalModel, i)
  196. if err != nil {
  197. common.LogError(c.Request.Context(), fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", err.Error()))
  198. break
  199. }
  200. channelId = channel.Id
  201. useChannel := c.GetStringSlice("use_channel")
  202. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  203. c.Set("use_channel", useChannel)
  204. common.LogInfo(c.Request.Context(), fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  205. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  206. requestBody, err := common.GetRequestBody(c)
  207. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  208. taskErr = taskRelayHandler(c, relayMode)
  209. }
  210. useChannel := c.GetStringSlice("use_channel")
  211. if len(useChannel) > 1 {
  212. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  213. common.LogInfo(c.Request.Context(), retryLogStr)
  214. }
  215. if taskErr != nil {
  216. if taskErr.StatusCode == http.StatusTooManyRequests {
  217. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  218. }
  219. c.JSON(taskErr.StatusCode, taskErr)
  220. }
  221. }
  222. func taskRelayHandler(c *gin.Context, relayMode int) *dto.TaskError {
  223. var err *dto.TaskError
  224. switch relayMode {
  225. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID:
  226. err = relay.RelayTaskFetch(c, relayMode)
  227. default:
  228. err = relay.RelayTaskSubmit(c, relayMode)
  229. }
  230. return err
  231. }
  232. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  233. if taskErr == nil {
  234. return false
  235. }
  236. if retryTimes <= 0 {
  237. return false
  238. }
  239. if _, ok := c.Get("specific_channel_id"); ok {
  240. return false
  241. }
  242. if taskErr.StatusCode == http.StatusTooManyRequests {
  243. return true
  244. }
  245. if taskErr.StatusCode == 307 {
  246. return true
  247. }
  248. if taskErr.StatusCode/100 == 5 {
  249. // 超时不重试
  250. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  251. return false
  252. }
  253. return true
  254. }
  255. if taskErr.StatusCode == http.StatusBadRequest {
  256. return false
  257. }
  258. if taskErr.StatusCode == 408 {
  259. // azure处理超时不重试
  260. return false
  261. }
  262. if taskErr.LocalError {
  263. return false
  264. }
  265. if taskErr.StatusCode/100 == 2 {
  266. return false
  267. }
  268. return true
  269. }