relay.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. package controller
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gorilla/websocket"
  8. "io"
  9. "log"
  10. "net/http"
  11. "one-api/common"
  12. "one-api/dto"
  13. "one-api/middleware"
  14. "one-api/model"
  15. "one-api/relay"
  16. "one-api/relay/constant"
  17. relayconstant "one-api/relay/constant"
  18. "one-api/service"
  19. "strings"
  20. )
  21. func relayHandler(c *gin.Context, relayMode int) *dto.OpenAIErrorWithStatusCode {
  22. var err *dto.OpenAIErrorWithStatusCode
  23. switch relayMode {
  24. case relayconstant.RelayModeImagesGenerations:
  25. err = relay.ImageHelper(c, relayMode)
  26. case relayconstant.RelayModeAudioSpeech:
  27. fallthrough
  28. case relayconstant.RelayModeAudioTranslation:
  29. fallthrough
  30. case relayconstant.RelayModeAudioTranscription:
  31. err = relay.AudioHelper(c)
  32. case relayconstant.RelayModeRerank:
  33. err = relay.RerankHelper(c, relayMode)
  34. default:
  35. err = relay.TextHelper(c)
  36. }
  37. return err
  38. }
  39. func wsHandler(c *gin.Context, ws *websocket.Conn, relayMode int) *dto.OpenAIErrorWithStatusCode {
  40. var err *dto.OpenAIErrorWithStatusCode
  41. switch relayMode {
  42. default:
  43. err = relay.TextHelper(c)
  44. }
  45. return err
  46. }
  47. func Playground(c *gin.Context) {
  48. var openaiErr *dto.OpenAIErrorWithStatusCode
  49. defer func() {
  50. if openaiErr != nil {
  51. c.JSON(openaiErr.StatusCode, gin.H{
  52. "error": openaiErr.Error,
  53. })
  54. }
  55. }()
  56. useAccessToken := c.GetBool("use_access_token")
  57. if useAccessToken {
  58. openaiErr = service.OpenAIErrorWrapperLocal(errors.New("暂不支持使用 access token"), "access_token_not_supported", http.StatusBadRequest)
  59. return
  60. }
  61. playgroundRequest := &dto.PlayGroundRequest{}
  62. err := common.UnmarshalBodyReusable(c, playgroundRequest)
  63. if err != nil {
  64. openaiErr = service.OpenAIErrorWrapperLocal(err, "unmarshal_request_failed", http.StatusBadRequest)
  65. return
  66. }
  67. if playgroundRequest.Model == "" {
  68. openaiErr = service.OpenAIErrorWrapperLocal(errors.New("请选择模型"), "model_required", http.StatusBadRequest)
  69. return
  70. }
  71. c.Set("original_model", playgroundRequest.Model)
  72. group := playgroundRequest.Group
  73. userGroup := c.GetString("group")
  74. if group == "" {
  75. group = userGroup
  76. } else {
  77. if !common.GroupInUserUsableGroups(group) && group != userGroup {
  78. openaiErr = service.OpenAIErrorWrapperLocal(errors.New("无权访问该分组"), "group_not_allowed", http.StatusForbidden)
  79. return
  80. }
  81. c.Set("group", group)
  82. }
  83. c.Set("token_name", "playground-"+group)
  84. channel, err := model.CacheGetRandomSatisfiedChannel(group, playgroundRequest.Model, 0)
  85. if err != nil {
  86. message := fmt.Sprintf("当前分组 %s 下对于模型 %s 无可用渠道", group, playgroundRequest.Model)
  87. openaiErr = service.OpenAIErrorWrapperLocal(errors.New(message), "get_playground_channel_failed", http.StatusInternalServerError)
  88. return
  89. }
  90. middleware.SetupContextForSelectedChannel(c, channel, playgroundRequest.Model)
  91. Relay(c)
  92. }
  93. func Relay(c *gin.Context) {
  94. relayMode := constant.Path2RelayMode(c.Request.URL.Path)
  95. requestId := c.GetString(common.RequestIdKey)
  96. group := c.GetString("group")
  97. originalModel := c.GetString("original_model")
  98. var openaiErr *dto.OpenAIErrorWithStatusCode
  99. for i := 0; i <= common.RetryTimes; i++ {
  100. channel, err := getChannel(c, group, originalModel, i)
  101. if err != nil {
  102. common.LogError(c, err.Error())
  103. openaiErr = service.OpenAIErrorWrapperLocal(err, "get_channel_failed", http.StatusInternalServerError)
  104. break
  105. }
  106. openaiErr = relayRequest(c, relayMode, channel)
  107. if openaiErr == nil {
  108. return // 成功处理请求,直接返回
  109. }
  110. go processChannelError(c, channel.Id, channel.Type, channel.Name, channel.GetAutoBan(), openaiErr)
  111. if !shouldRetry(c, openaiErr, common.RetryTimes-i) {
  112. break
  113. }
  114. }
  115. useChannel := c.GetStringSlice("use_channel")
  116. if len(useChannel) > 1 {
  117. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  118. common.LogInfo(c, retryLogStr)
  119. }
  120. if openaiErr != nil {
  121. if openaiErr.StatusCode == http.StatusTooManyRequests {
  122. openaiErr.Error.Message = "当前分组上游负载已饱和,请稍后再试"
  123. }
  124. openaiErr.Error.Message = common.MessageWithRequestId(openaiErr.Error.Message, requestId)
  125. c.JSON(openaiErr.StatusCode, gin.H{
  126. "error": openaiErr.Error,
  127. })
  128. }
  129. }
  130. var upgrader = websocket.Upgrader{
  131. CheckOrigin: func(r *http.Request) bool {
  132. return true // 允许跨域
  133. },
  134. }
  135. func WssRelay(c *gin.Context) {
  136. // 将 HTTP 连接升级为 WebSocket 连接
  137. ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  138. defer ws.Close()
  139. if err != nil {
  140. openaiErr := service.OpenAIErrorWrapper(err, "get_channel_failed", http.StatusInternalServerError)
  141. service.WssError(c, ws, openaiErr.Error)
  142. return
  143. }
  144. relayMode := constant.Path2RelayMode(c.Request.URL.Path)
  145. requestId := c.GetString(common.RequestIdKey)
  146. group := c.GetString("group")
  147. //wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01
  148. originalModel := c.GetString("original_model")
  149. var openaiErr *dto.OpenAIErrorWithStatusCode
  150. for i := 0; i <= common.RetryTimes; i++ {
  151. channel, err := getChannel(c, group, originalModel, i)
  152. if err != nil {
  153. common.LogError(c, err.Error())
  154. openaiErr = service.OpenAIErrorWrapperLocal(err, "get_channel_failed", http.StatusInternalServerError)
  155. break
  156. }
  157. openaiErr = wssRequest(c, ws, relayMode, channel)
  158. if openaiErr == nil {
  159. return // 成功处理请求,直接返回
  160. }
  161. go processChannelError(c, channel.Id, channel.Type, channel.Name, channel.GetAutoBan(), openaiErr)
  162. if !shouldRetry(c, openaiErr, common.RetryTimes-i) {
  163. break
  164. }
  165. }
  166. useChannel := c.GetStringSlice("use_channel")
  167. if len(useChannel) > 1 {
  168. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  169. common.LogInfo(c, retryLogStr)
  170. }
  171. if openaiErr != nil {
  172. if openaiErr.StatusCode == http.StatusTooManyRequests {
  173. openaiErr.Error.Message = "当前分组上游负载已饱和,请稍后再试"
  174. }
  175. openaiErr.Error.Message = common.MessageWithRequestId(openaiErr.Error.Message, requestId)
  176. service.WssError(c, ws, openaiErr.Error)
  177. }
  178. }
  179. func relayRequest(c *gin.Context, relayMode int, channel *model.Channel) *dto.OpenAIErrorWithStatusCode {
  180. addUsedChannel(c, channel.Id)
  181. requestBody, _ := common.GetRequestBody(c)
  182. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  183. return relayHandler(c, relayMode)
  184. }
  185. func wssRequest(c *gin.Context, ws *websocket.Conn, relayMode int, channel *model.Channel) *dto.OpenAIErrorWithStatusCode {
  186. addUsedChannel(c, channel.Id)
  187. requestBody, _ := common.GetRequestBody(c)
  188. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  189. return relay.WssHelper(c, ws)
  190. }
  191. func addUsedChannel(c *gin.Context, channelId int) {
  192. useChannel := c.GetStringSlice("use_channel")
  193. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  194. c.Set("use_channel", useChannel)
  195. }
  196. func getChannel(c *gin.Context, group, originalModel string, retryCount int) (*model.Channel, error) {
  197. if retryCount == 0 {
  198. autoBan := c.GetBool("auto_ban")
  199. autoBanInt := 1
  200. if !autoBan {
  201. autoBanInt = 0
  202. }
  203. return &model.Channel{
  204. Id: c.GetInt("channel_id"),
  205. Type: c.GetInt("channel_type"),
  206. Name: c.GetString("channel_name"),
  207. AutoBan: &autoBanInt,
  208. }, nil
  209. }
  210. channel, err := model.CacheGetRandomSatisfiedChannel(group, originalModel, retryCount)
  211. if err != nil {
  212. return nil, errors.New(fmt.Sprintf("获取重试渠道失败: %s", err.Error()))
  213. }
  214. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  215. return channel, nil
  216. }
  217. func shouldRetry(c *gin.Context, openaiErr *dto.OpenAIErrorWithStatusCode, retryTimes int) bool {
  218. if openaiErr == nil {
  219. return false
  220. }
  221. if openaiErr.LocalError {
  222. return false
  223. }
  224. if retryTimes <= 0 {
  225. return false
  226. }
  227. if _, ok := c.Get("specific_channel_id"); ok {
  228. return false
  229. }
  230. if openaiErr.StatusCode == http.StatusTooManyRequests {
  231. return true
  232. }
  233. if openaiErr.StatusCode == 307 {
  234. return true
  235. }
  236. if openaiErr.StatusCode/100 == 5 {
  237. // 超时不重试
  238. if openaiErr.StatusCode == 504 || openaiErr.StatusCode == 524 {
  239. return false
  240. }
  241. return true
  242. }
  243. if openaiErr.StatusCode == http.StatusBadRequest {
  244. channelType := c.GetInt("channel_type")
  245. if channelType == common.ChannelTypeAnthropic {
  246. return true
  247. }
  248. return false
  249. }
  250. if openaiErr.StatusCode == 408 {
  251. // azure处理超时不重试
  252. return false
  253. }
  254. if openaiErr.StatusCode/100 == 2 {
  255. return false
  256. }
  257. return true
  258. }
  259. func processChannelError(c *gin.Context, channelId int, channelType int, channelName string, autoBan bool, err *dto.OpenAIErrorWithStatusCode) {
  260. // 不要使用context获取渠道信息,异步处理时可能会出现渠道信息不一致的情况
  261. // do not use context to get channel info, there may be inconsistent channel info when processing asynchronously
  262. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code: %d): %s", channelId, err.StatusCode, err.Error.Message))
  263. if service.ShouldDisableChannel(channelType, err) && autoBan {
  264. service.DisableChannel(channelId, channelName, err.Error.Message)
  265. }
  266. }
  267. func RelayMidjourney(c *gin.Context) {
  268. relayMode := c.GetInt("relay_mode")
  269. var err *dto.MidjourneyResponse
  270. switch relayMode {
  271. case relayconstant.RelayModeMidjourneyNotify:
  272. err = relay.RelayMidjourneyNotify(c)
  273. case relayconstant.RelayModeMidjourneyTaskFetch, relayconstant.RelayModeMidjourneyTaskFetchByCondition:
  274. err = relay.RelayMidjourneyTask(c, relayMode)
  275. case relayconstant.RelayModeMidjourneyTaskImageSeed:
  276. err = relay.RelayMidjourneyTaskImageSeed(c)
  277. case relayconstant.RelayModeSwapFace:
  278. err = relay.RelaySwapFace(c)
  279. default:
  280. err = relay.RelayMidjourneySubmit(c, relayMode)
  281. }
  282. //err = relayMidjourneySubmit(c, relayMode)
  283. log.Println(err)
  284. if err != nil {
  285. statusCode := http.StatusBadRequest
  286. if err.Code == 30 {
  287. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  288. statusCode = http.StatusTooManyRequests
  289. }
  290. c.JSON(statusCode, gin.H{
  291. "description": fmt.Sprintf("%s %s", err.Description, err.Result),
  292. "type": "upstream_error",
  293. "code": err.Code,
  294. })
  295. channelId := c.GetInt("channel_id")
  296. common.LogError(c, fmt.Sprintf("relay error (channel #%d, status code %d): %s", channelId, statusCode, fmt.Sprintf("%s %s", err.Description, err.Result)))
  297. }
  298. }
  299. func RelayNotImplemented(c *gin.Context) {
  300. err := dto.OpenAIError{
  301. Message: "API not implemented",
  302. Type: "new_api_error",
  303. Param: "",
  304. Code: "api_not_implemented",
  305. }
  306. c.JSON(http.StatusNotImplemented, gin.H{
  307. "error": err,
  308. })
  309. }
  310. func RelayNotFound(c *gin.Context) {
  311. err := dto.OpenAIError{
  312. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  313. Type: "invalid_request_error",
  314. Param: "",
  315. Code: "",
  316. }
  317. c.JSON(http.StatusNotFound, gin.H{
  318. "error": err,
  319. })
  320. }
  321. func RelayTask(c *gin.Context) {
  322. retryTimes := common.RetryTimes
  323. channelId := c.GetInt("channel_id")
  324. relayMode := c.GetInt("relay_mode")
  325. group := c.GetString("group")
  326. originalModel := c.GetString("original_model")
  327. c.Set("use_channel", []string{fmt.Sprintf("%d", channelId)})
  328. taskErr := taskRelayHandler(c, relayMode)
  329. if taskErr == nil {
  330. retryTimes = 0
  331. }
  332. for i := 0; shouldRetryTaskRelay(c, channelId, taskErr, retryTimes) && i < retryTimes; i++ {
  333. channel, err := model.CacheGetRandomSatisfiedChannel(group, originalModel, i)
  334. if err != nil {
  335. common.LogError(c, fmt.Sprintf("CacheGetRandomSatisfiedChannel failed: %s", err.Error()))
  336. break
  337. }
  338. channelId = channel.Id
  339. useChannel := c.GetStringSlice("use_channel")
  340. useChannel = append(useChannel, fmt.Sprintf("%d", channelId))
  341. c.Set("use_channel", useChannel)
  342. common.LogInfo(c, fmt.Sprintf("using channel #%d to retry (remain times %d)", channel.Id, i))
  343. middleware.SetupContextForSelectedChannel(c, channel, originalModel)
  344. requestBody, err := common.GetRequestBody(c)
  345. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  346. taskErr = taskRelayHandler(c, relayMode)
  347. }
  348. useChannel := c.GetStringSlice("use_channel")
  349. if len(useChannel) > 1 {
  350. retryLogStr := fmt.Sprintf("重试:%s", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(useChannel)), "->"), "[]"))
  351. common.LogInfo(c, retryLogStr)
  352. }
  353. if taskErr != nil {
  354. if taskErr.StatusCode == http.StatusTooManyRequests {
  355. taskErr.Message = "当前分组上游负载已饱和,请稍后再试"
  356. }
  357. c.JSON(taskErr.StatusCode, taskErr)
  358. }
  359. }
  360. func taskRelayHandler(c *gin.Context, relayMode int) *dto.TaskError {
  361. var err *dto.TaskError
  362. switch relayMode {
  363. case relayconstant.RelayModeSunoFetch, relayconstant.RelayModeSunoFetchByID:
  364. err = relay.RelayTaskFetch(c, relayMode)
  365. default:
  366. err = relay.RelayTaskSubmit(c, relayMode)
  367. }
  368. return err
  369. }
  370. func shouldRetryTaskRelay(c *gin.Context, channelId int, taskErr *dto.TaskError, retryTimes int) bool {
  371. if taskErr == nil {
  372. return false
  373. }
  374. if retryTimes <= 0 {
  375. return false
  376. }
  377. if _, ok := c.Get("specific_channel_id"); ok {
  378. return false
  379. }
  380. if taskErr.StatusCode == http.StatusTooManyRequests {
  381. return true
  382. }
  383. if taskErr.StatusCode == 307 {
  384. return true
  385. }
  386. if taskErr.StatusCode/100 == 5 {
  387. // 超时不重试
  388. if taskErr.StatusCode == 504 || taskErr.StatusCode == 524 {
  389. return false
  390. }
  391. return true
  392. }
  393. if taskErr.StatusCode == http.StatusBadRequest {
  394. return false
  395. }
  396. if taskErr.StatusCode == 408 {
  397. // azure处理超时不重试
  398. return false
  399. }
  400. if taskErr.LocalError {
  401. return false
  402. }
  403. if taskErr.StatusCode/100 == 2 {
  404. return false
  405. }
  406. return true
  407. }