relay.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package controller
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/model"
  10. "strings"
  11. )
  12. func Relay(c *gin.Context) {
  13. channelType := c.GetInt("channel")
  14. tokenId := c.GetInt("token_id")
  15. isUnlimitedQuota := c.GetBool("unlimited_quota")
  16. baseURL := common.ChannelBaseURLs[channelType]
  17. if channelType == common.ChannelTypeCustom {
  18. baseURL = c.GetString("base_url")
  19. }
  20. requestURL := c.Request.URL.String()
  21. req, err := http.NewRequest(c.Request.Method, fmt.Sprintf("%s%s", baseURL, requestURL), c.Request.Body)
  22. if err != nil {
  23. c.JSON(http.StatusOK, gin.H{
  24. "error": gin.H{
  25. "message": err.Error(),
  26. "type": "one_api_error",
  27. },
  28. })
  29. return
  30. }
  31. //req.Header = c.Request.Header.Clone()
  32. // Fix HTTP Decompression failed
  33. // https://github.com/stoplightio/prism/issues/1064#issuecomment-824682360
  34. //req.Header.Del("Accept-Encoding")
  35. req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
  36. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  37. req.Header.Set("Accept", c.Request.Header.Get("Accept"))
  38. req.Header.Set("Connection", c.Request.Header.Get("Connection"))
  39. client := &http.Client{}
  40. resp, err := client.Do(req)
  41. if err != nil {
  42. c.JSON(http.StatusOK, gin.H{
  43. "error": gin.H{
  44. "message": err.Error(),
  45. "type": "one_api_error",
  46. },
  47. })
  48. return
  49. }
  50. defer func() {
  51. err := req.Body.Close()
  52. if err != nil {
  53. common.SysError("Error closing request body: " + err.Error())
  54. }
  55. if !isUnlimitedQuota && requestURL == "/v1/chat/completions" {
  56. err := model.DecreaseTokenRemainQuotaById(tokenId)
  57. if err != nil {
  58. common.SysError("Error decreasing token remain times: " + err.Error())
  59. }
  60. }
  61. }()
  62. isStream := resp.Header.Get("Content-Type") == "text/event-stream"
  63. if isStream {
  64. scanner := bufio.NewScanner(resp.Body)
  65. scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  66. if atEOF && len(data) == 0 {
  67. return 0, nil, nil
  68. }
  69. if i := strings.Index(string(data), "\n\n"); i >= 0 {
  70. return i + 2, data[0:i], nil
  71. }
  72. if atEOF {
  73. return len(data), data, nil
  74. }
  75. return 0, nil, nil
  76. })
  77. dataChan := make(chan string)
  78. stopChan := make(chan bool)
  79. go func() {
  80. for scanner.Scan() {
  81. data := scanner.Text()
  82. dataChan <- data
  83. }
  84. stopChan <- true
  85. }()
  86. c.Writer.Header().Set("Content-Type", "text/event-stream")
  87. c.Writer.Header().Set("Cache-Control", "no-cache")
  88. c.Writer.Header().Set("Connection", "keep-alive")
  89. c.Writer.Header().Set("Transfer-Encoding", "chunked")
  90. c.Stream(func(w io.Writer) bool {
  91. select {
  92. case data := <-dataChan:
  93. c.Render(-1, common.CustomEvent{Data: data})
  94. return true
  95. case <-stopChan:
  96. return false
  97. }
  98. })
  99. return
  100. } else {
  101. for k, v := range resp.Header {
  102. c.Writer.Header().Set(k, v[0])
  103. }
  104. _, err = io.Copy(c.Writer, resp.Body)
  105. if err != nil {
  106. c.JSON(http.StatusOK, gin.H{
  107. "error": gin.H{
  108. "message": err.Error(),
  109. "type": "one_api_error",
  110. },
  111. })
  112. return
  113. }
  114. }
  115. }