relay.go 11 KB

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