relay.go 10 KB

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