relay.go 8.4 KB

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