relay.go 11 KB

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