relay.go 8.9 KB

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