relay.go 8.8 KB

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