2
0

relay.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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, channel.GetAutoBan(), 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. autoBan := c.GetBool("auto_ban")
  89. autoBanInt := 1
  90. if !autoBan {
  91. autoBanInt = 0
  92. }
  93. return &model.Channel{
  94. Id: c.GetInt("channel_id"),
  95. Type: c.GetInt("channel_type"),
  96. Name: c.GetString("channel_name"),
  97. AutoBan: &autoBanInt,
  98. }, nil
  99. }
  100. channel, err := model.CacheGetRandomSatisfiedChannel(group, originalModel, retryCount)
  101. if err != nil {
  102. return nil, errors.New(fmt.Sprintf("获取重试渠道失败: %s", err.Error()))
  103. }
  104. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  105. return channel, nil
  106. }
  107. func shouldRetry(c *gin.Context, openaiErr *dto.OpenAIErrorWithStatusCode, retryTimes int) bool {
  108. if openaiErr == nil {
  109. return false
  110. }
  111. if retryTimes <= 0 {
  112. return false
  113. }
  114. if _, ok := c.Get("specific_channel_id"); ok {
  115. return false
  116. }
  117. if openaiErr.StatusCode == http.StatusTooManyRequests {
  118. return true
  119. }
  120. if openaiErr.StatusCode == 307 {
  121. return true
  122. }
  123. if openaiErr.StatusCode/100 == 5 {
  124. // 超时不重试
  125. if openaiErr.StatusCode == 504 || openaiErr.StatusCode == 524 {
  126. return false
  127. }
  128. return true
  129. }
  130. if openaiErr.StatusCode == http.StatusBadRequest {
  131. channelType := c.GetInt("channel_type")
  132. if channelType == common.ChannelTypeAnthropic {
  133. return true
  134. }
  135. return false
  136. }
  137. if openaiErr.StatusCode == 408 {
  138. // azure处理超时不重试
  139. return false
  140. }
  141. if openaiErr.LocalError {
  142. return false
  143. }
  144. if openaiErr.StatusCode/100 == 2 {
  145. return false
  146. }
  147. return true
  148. }
  149. func processChannelError(c *gin.Context, channelId int, channelType int, channelName string, autoBan bool, err *dto.OpenAIErrorWithStatusCode) {
  150. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  151. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  152. common.LogError(c.Request.Context(), fmt.Sprintf("relay error (channel #%d, status code: %d): %s", channelId, err.StatusCode, err.Error.Message))
  153. if service.ShouldDisableChannel(channelType, err) && autoBan {
  154. service.DisableChannel(channelId, channelName, err.Error.Message)
  155. }
  156. }
  157. func RelayMidjourney(c *gin.Context) {
  158. relayMode := c.GetInt("relay_mode")
  159. var err *dto.MidjourneyResponse
  160. switch relayMode {
  161. case relayconstant.RelayModeMidjourneyNotify:
  162. err = relay.RelayMidjourneyNotify(c)
  163. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  164. err = relay.RelayMidjourneyTask(c, relayMode)
  165. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  166. err = relay.RelayMidjourneyTaskImageSeed(c)
  167. case relayconstant.RelayModeSwapFace:
  168. err = relay.RelaySwapFace(c)
  169. default:
  170. err = relay.RelayMidjourneySubmit(c, relayMode)
  171. }
  172. //err = relayMidjourneySubmit(c, relayMode)
  173. log.Println(err)
  174. if err != nil {
  175. statusCode := http.StatusBadRequest
  176. if err.Code == 30 {
  177. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  178. statusCode = http.StatusTooManyRequests
  179. }
  180. c.JSON(statusCode, gin.H{
  181. "description": fmt.Sprintf("%s %s", err.Description, err.Result),
  182. "type": "upstream_error",
  183. "code": err.Code,
  184. })
  185. channelId := c.GetInt("channel_id")
  186. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", err.Description, err.Result)))
  187. }
  188. }
  189. func RelayNotImplemented(c *gin.Context) {
  190. err := dto.OpenAIError{
  191. Message: "API not implemented",
  192. Type: "new_api_error",
  193. Param: "",
  194. Code: "api_not_implemented",
  195. }
  196. c.JSON(http.StatusNotImplemented, gin.H{
  197. "error": err,
  198. })
  199. }
  200. func RelayNotFound(c *gin.Context) {
  201. err := dto.OpenAIError{
  202. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  203. Type: "invalid_request_error",
  204. Param: "",
  205. Code: "",
  206. }
  207. c.JSON(http.StatusNotFound, gin.H{
  208. "error": err,
  209. })
  210. }
  211. func RelayTask(c *gin.Context) {
  212. retryTimes := common.RetryTimes
  213. channelId := c.GetInt("channel_id")
  214. relayMode := c.GetInt("relay_mode")
  215. group := c.GetString("group")
  216. originalModel := c.GetString("original_model")
  217. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  218. taskErr := taskRelayHandler(c, relayMode)
  219. if taskErr == nil {
  220. retryTimes = 0
  221. }
  222. for i := 0; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && i < retryTimes; i++ {
  223. channel, err := model.CacheGetRandomSatisfiedChannel(group, originalModel, i)
  224. if err != nil {
  225. common.LogError(c.Request.Context(), fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", err.Error()))
  226. break
  227. }
  228. channelId = channel.Id
  229. useChannel := c.GetStringSlice("use_channel")
  230. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  231. c.Set("use_channel", useChannel)
  232. common.LogInfo(c.Request.Context(), fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  233. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  234. requestBody, err := common.GetRequestBody(c)
  235. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  236. taskErr = taskRelayHandler(c, relayMode)
  237. }
  238. useChannel := c.GetStringSlice("use_channel")
  239. if len(useChannel) > 1 {
  240. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  241. common.LogInfo(c.Request.Context(), retryLogStr)
  242. }
  243. if taskErr != nil {
  244. if taskErr.StatusCode == http.StatusTooManyRequests {
  245. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  246. }
  247. c.JSON(taskErr.StatusCode, taskErr)
  248. }
  249. }
  250. func taskRelayHandler(c *gin.Context, relayMode int) *dto.TaskError {
  251. var err *dto.TaskError
  252. switch relayMode {
  253. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID:
  254. err = relay.RelayTaskFetch(c, relayMode)
  255. default:
  256. err = relay.RelayTaskSubmit(c, relayMode)
  257. }
  258. return err
  259. }
  260. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  261. if taskErr == nil {
  262. return false
  263. }
  264. if retryTimes <= 0 {
  265. return false
  266. }
  267. if _, ok := c.Get("specific_channel_id"); ok {
  268. return false
  269. }
  270. if taskErr.StatusCode == http.StatusTooManyRequests {
  271. return true
  272. }
  273. if taskErr.StatusCode == 307 {
  274. return true
  275. }
  276. if taskErr.StatusCode/100 == 5 {
  277. // 超时不重试
  278. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  279. return false
  280. }
  281. return true
  282. }
  283. if taskErr.StatusCode == http.StatusBadRequest {
  284. return false
  285. }
  286. if taskErr.StatusCode == 408 {
  287. // azure处理超时不重试
  288. return false
  289. }
  290. if taskErr.LocalError {
  291. return false
  292. }
  293. if taskErr.StatusCode/100 == 2 {
  294. return false
  295. }
  296. return true
  297. }