relay.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package controller
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "io"
  9. "net/http"
  10. "one-api/common"
  11. "one-api/model"
  12. "strings"
  13. )
  14. type Message struct {
  15. Role string `json:"role"`
  16. Content string `json:"content"`
  17. }
  18. type TextRequest struct {
  19. Model string `json:"model"`
  20. Messages []Message `json:"messages"`
  21. Prompt string `json:"prompt"`
  22. //Stream bool `json:"stream"`
  23. }
  24. type Usage struct {
  25. PromptTokens int `json:"prompt_tokens"`
  26. CompletionTokens int `json:"completion_tokens"`
  27. TotalTokens int `json:"total_tokens"`
  28. }
  29. type TextResponse struct {
  30. Usage `json:"usage"`
  31. }
  32. type StreamResponse struct {
  33. Choices []struct {
  34. Delta struct {
  35. Content string `json:"content"`
  36. } `json:"delta"`
  37. FinishReason string `json:"finish_reason"`
  38. } `json:"choices"`
  39. }
  40. func Relay(c *gin.Context) {
  41. channelType := c.GetInt("channel")
  42. tokenId := c.GetInt("token_id")
  43. consumeQuota := c.GetBool("consume_quota")
  44. baseURL := common.ChannelBaseURLs[channelType]
  45. if channelType == common.ChannelTypeCustom {
  46. baseURL = c.GetString("base_url")
  47. }
  48. requestBody, err := io.ReadAll(c.Request.Body)
  49. if err != nil {
  50. c.JSON(http.StatusOK, gin.H{
  51. "error": gin.H{
  52. "message": err.Error(),
  53. "type": "one_api_error",
  54. },
  55. })
  56. return
  57. }
  58. err = c.Request.Body.Close()
  59. if err != nil {
  60. c.JSON(http.StatusOK, gin.H{
  61. "error": gin.H{
  62. "message": err.Error(),
  63. "type": "one_api_error",
  64. },
  65. })
  66. return
  67. }
  68. var textRequest TextRequest
  69. err = json.Unmarshal(requestBody, &textRequest)
  70. if err != nil {
  71. c.JSON(http.StatusOK, gin.H{
  72. "error": gin.H{
  73. "message": err.Error(),
  74. "type": "one_api_error",
  75. },
  76. })
  77. return
  78. }
  79. // Reset request body
  80. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  81. requestURL := c.Request.URL.String()
  82. req, err := http.NewRequest(c.Request.Method, fmt.Sprintf("%s%s", baseURL, requestURL), c.Request.Body)
  83. if err != nil {
  84. c.JSON(http.StatusOK, gin.H{
  85. "error": gin.H{
  86. "message": err.Error(),
  87. "type": "one_api_error",
  88. },
  89. })
  90. return
  91. }
  92. req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
  93. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  94. req.Header.Set("Accept", c.Request.Header.Get("Accept"))
  95. req.Header.Set("Connection", c.Request.Header.Get("Connection"))
  96. client := &http.Client{}
  97. resp, err := client.Do(req)
  98. if err != nil {
  99. c.JSON(http.StatusOK, gin.H{
  100. "error": gin.H{
  101. "message": err.Error(),
  102. "type": "one_api_error",
  103. },
  104. })
  105. return
  106. }
  107. err = req.Body.Close()
  108. if err != nil {
  109. c.JSON(http.StatusOK, gin.H{
  110. "error": gin.H{
  111. "message": err.Error(),
  112. "type": "one_api_error",
  113. },
  114. })
  115. return
  116. }
  117. var textResponse TextResponse
  118. isStream := resp.Header.Get("Content-Type") == "text/event-stream"
  119. var streamResponseText string
  120. defer func() {
  121. if consumeQuota {
  122. quota := 0
  123. if isStream {
  124. quota = int(float64(len(streamResponseText)) * 0.8)
  125. } else {
  126. quota = textResponse.Usage.TotalTokens
  127. }
  128. err := model.ConsumeTokenQuota(tokenId, quota)
  129. if err != nil {
  130. common.SysError("Error consuming token remain quota: " + err.Error())
  131. }
  132. }
  133. }()
  134. if isStream {
  135. scanner := bufio.NewScanner(resp.Body)
  136. scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  137. if atEOF && len(data) == 0 {
  138. return 0, nil, nil
  139. }
  140. if i := strings.Index(string(data), "\n\n"); i >= 0 {
  141. return i + 2, data[0:i], nil
  142. }
  143. if atEOF {
  144. return len(data), data, nil
  145. }
  146. return 0, nil, nil
  147. })
  148. dataChan := make(chan string)
  149. stopChan := make(chan bool)
  150. go func() {
  151. for scanner.Scan() {
  152. data := scanner.Text()
  153. dataChan <- data
  154. data = data[6:]
  155. if data != "[DONE]" {
  156. var streamResponse StreamResponse
  157. err = json.Unmarshal([]byte(data), &streamResponse)
  158. if err != nil {
  159. common.SysError("Error unmarshalling stream response: " + err.Error())
  160. return
  161. }
  162. for _, choice := range streamResponse.Choices {
  163. streamResponseText += choice.Delta.Content
  164. }
  165. }
  166. }
  167. stopChan <- true
  168. }()
  169. c.Writer.Header().Set("Content-Type", "text/event-stream")
  170. c.Writer.Header().Set("Cache-Control", "no-cache")
  171. c.Writer.Header().Set("Connection", "keep-alive")
  172. c.Writer.Header().Set("Transfer-Encoding", "chunked")
  173. c.Stream(func(w io.Writer) bool {
  174. select {
  175. case data := <-dataChan:
  176. c.Render(-1, common.CustomEvent{Data: data})
  177. return true
  178. case <-stopChan:
  179. return false
  180. }
  181. })
  182. return
  183. } else {
  184. for k, v := range resp.Header {
  185. c.Writer.Header().Set(k, v[0])
  186. }
  187. responseBody, err := io.ReadAll(resp.Body)
  188. if err != nil {
  189. c.JSON(http.StatusOK, gin.H{
  190. "error": gin.H{
  191. "message": err.Error(),
  192. "type": "one_api_error",
  193. },
  194. })
  195. return
  196. }
  197. err = resp.Body.Close()
  198. if err != nil {
  199. c.JSON(http.StatusOK, gin.H{
  200. "error": gin.H{
  201. "message": err.Error(),
  202. "type": "one_api_error",
  203. },
  204. })
  205. return
  206. }
  207. err = json.Unmarshal(responseBody, &textResponse)
  208. if err != nil {
  209. c.JSON(http.StatusOK, gin.H{
  210. "error": gin.H{
  211. "message": err.Error(),
  212. "type": "one_api_error",
  213. },
  214. })
  215. return
  216. }
  217. // Reset response body
  218. resp.Body = io.NopCloser(bytes.NewBuffer(responseBody))
  219. _, err = io.Copy(c.Writer, resp.Body)
  220. if err != nil {
  221. c.JSON(http.StatusOK, gin.H{
  222. "error": gin.H{
  223. "message": err.Error(),
  224. "type": "one_api_error",
  225. },
  226. })
  227. return
  228. }
  229. }
  230. }
  231. func RelayNotImplemented(c *gin.Context) {
  232. c.JSON(http.StatusOK, gin.H{
  233. "error": gin.H{
  234. "message": "Not Implemented",
  235. "type": "one_api_error",
  236. },
  237. })
  238. }