relay.go 8.5 KB

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