relay.go 9.1 KB

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