relay.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. Name *string `json:"name,omitempty"`
  18. }
  19. // https://platform.openai.com/docs/api-reference/chat
  20. type GeneralOpenAIRequest struct {
  21. Model string `json:"model"`
  22. Messages []Message `json:"messages"`
  23. Prompt string `json:"prompt"`
  24. Stream bool `json:"stream"`
  25. MaxTokens int `json:"max_tokens"`
  26. Temperature float64 `json:"temperature"`
  27. TopP float64 `json:"top_p"`
  28. N int `json:"n"`
  29. }
  30. type ChatRequest struct {
  31. Model string `json:"model"`
  32. Messages []Message `json:"messages"`
  33. MaxTokens int `json:"max_tokens"`
  34. }
  35. type TextRequest struct {
  36. Model string `json:"model"`
  37. Messages []Message `json:"messages"`
  38. Prompt string `json:"prompt"`
  39. MaxTokens int `json:"max_tokens"`
  40. //Stream bool `json:"stream"`
  41. }
  42. type Usage struct {
  43. PromptTokens int `json:"prompt_tokens"`
  44. CompletionTokens int `json:"completion_tokens"`
  45. TotalTokens int `json:"total_tokens"`
  46. }
  47. type OpenAIError struct {
  48. Message string `json:"message"`
  49. Type string `json:"type"`
  50. Param string `json:"param"`
  51. Code string `json:"code"`
  52. }
  53. type OpenAIErrorWithStatusCode struct {
  54. OpenAIError
  55. StatusCode int `json:"status_code"`
  56. }
  57. type TextResponse struct {
  58. Usage `json:"usage"`
  59. Error OpenAIError `json:"error"`
  60. }
  61. type StreamResponse struct {
  62. Choices []struct {
  63. Delta struct {
  64. Content string `json:"content"`
  65. } `json:"delta"`
  66. FinishReason string `json:"finish_reason"`
  67. } `json:"choices"`
  68. }
  69. func Relay(c *gin.Context) {
  70. err := relayHelper(c)
  71. if err != nil {
  72. if err.StatusCode == http.StatusTooManyRequests {
  73. err.OpenAIError.Message = "负载已满,请稍后再试,或升级账户以提升服务质量。"
  74. }
  75. c.JSON(err.StatusCode, gin.H{
  76. "error": err.OpenAIError,
  77. })
  78. channelId := c.GetInt("channel_id")
  79. common.SysError(fmt.Sprintf("Relay error (channel #%d): %s", channelId, err.Message))
  80. // https://platform.openai.com/docs/guides/error-codes/api-errors
  81. if common.AutomaticDisableChannelEnabled && (err.Type == "insufficient_quota" || err.Code == "invalid_api_key") {
  82. channelId := c.GetInt("channel_id")
  83. channelName := c.GetString("channel_name")
  84. disableChannel(channelId, channelName, err.Message)
  85. }
  86. }
  87. }
  88. func errorWrapper(err error, code string, statusCode int) *OpenAIErrorWithStatusCode {
  89. openAIError := OpenAIError{
  90. Message: err.Error(),
  91. Type: "one_api_error",
  92. Code: code,
  93. }
  94. return &OpenAIErrorWithStatusCode{
  95. OpenAIError: openAIError,
  96. StatusCode: statusCode,
  97. }
  98. }
  99. func relayHelper(c *gin.Context) *OpenAIErrorWithStatusCode {
  100. channelType := c.GetInt("channel")
  101. tokenId := c.GetInt("token_id")
  102. consumeQuota := c.GetBool("consume_quota")
  103. var textRequest GeneralOpenAIRequest
  104. if consumeQuota || channelType == common.ChannelTypeAzure || channelType == common.ChannelTypePaLM {
  105. requestBody, err := io.ReadAll(c.Request.Body)
  106. if err != nil {
  107. return errorWrapper(err, "read_request_body_failed", http.StatusBadRequest)
  108. }
  109. err = c.Request.Body.Close()
  110. if err != nil {
  111. return errorWrapper(err, "close_request_body_failed", http.StatusBadRequest)
  112. }
  113. err = json.Unmarshal(requestBody, &textRequest)
  114. if err != nil {
  115. return errorWrapper(err, "unmarshal_request_body_failed", http.StatusBadRequest)
  116. }
  117. // Reset request body
  118. c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
  119. }
  120. baseURL := common.ChannelBaseURLs[channelType]
  121. requestURL := c.Request.URL.String()
  122. if channelType == common.ChannelTypeCustom {
  123. baseURL = c.GetString("base_url")
  124. }
  125. fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
  126. if channelType == common.ChannelTypeAzure {
  127. // https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
  128. query := c.Request.URL.Query()
  129. apiVersion := query.Get("api-version")
  130. if apiVersion == "" {
  131. apiVersion = c.GetString("api_version")
  132. }
  133. requestURL := strings.Split(requestURL, "?")[0]
  134. requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
  135. baseURL = c.GetString("base_url")
  136. task := strings.TrimPrefix(requestURL, "/v1/")
  137. model_ := textRequest.Model
  138. model_ = strings.Replace(model_, ".", "", -1)
  139. // https://github.com/songquanpeng/one-api/issues/67
  140. model_ = strings.TrimSuffix(model_, "-0301")
  141. model_ = strings.TrimSuffix(model_, "-0314")
  142. fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/%s", baseURL, model_, task)
  143. } else if channelType == common.ChannelTypePaLM {
  144. err := relayPaLM(textRequest, c)
  145. return err
  146. }
  147. promptTokens := countTokenMessages(textRequest.Messages, textRequest.Model)
  148. preConsumedTokens := common.PreConsumedQuota
  149. if textRequest.MaxTokens != 0 {
  150. preConsumedTokens = promptTokens + textRequest.MaxTokens
  151. }
  152. ratio := common.GetModelRatio(textRequest.Model)
  153. preConsumedQuota := int(float64(preConsumedTokens) * ratio)
  154. if consumeQuota {
  155. err := model.PreConsumeTokenQuota(tokenId, preConsumedQuota)
  156. if err != nil {
  157. return errorWrapper(err, "pre_consume_token_quota_failed", http.StatusOK)
  158. }
  159. }
  160. req, err := http.NewRequest(c.Request.Method, fullRequestURL, c.Request.Body)
  161. if err != nil {
  162. return errorWrapper(err, "new_request_failed", http.StatusOK)
  163. }
  164. if channelType == common.ChannelTypeAzure {
  165. key := c.Request.Header.Get("Authorization")
  166. key = strings.TrimPrefix(key, "Bearer ")
  167. req.Header.Set("api-key", key)
  168. } else {
  169. req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
  170. }
  171. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  172. req.Header.Set("Accept", c.Request.Header.Get("Accept"))
  173. req.Header.Set("Connection", c.Request.Header.Get("Connection"))
  174. client := &http.Client{}
  175. resp, err := client.Do(req)
  176. if err != nil {
  177. return errorWrapper(err, "do_request_failed", http.StatusOK)
  178. }
  179. err = req.Body.Close()
  180. if err != nil {
  181. return errorWrapper(err, "close_request_body_failed", http.StatusOK)
  182. }
  183. err = c.Request.Body.Close()
  184. if err != nil {
  185. return errorWrapper(err, "close_request_body_failed", http.StatusOK)
  186. }
  187. var textResponse TextResponse
  188. isStream := strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream")
  189. var streamResponseText string
  190. defer func() {
  191. if consumeQuota {
  192. quota := 0
  193. usingGPT4 := strings.HasPrefix(textRequest.Model, "gpt-4")
  194. completionRatio := 1
  195. if usingGPT4 {
  196. completionRatio = 2
  197. }
  198. if isStream {
  199. responseTokens := countTokenText(streamResponseText, textRequest.Model)
  200. quota = promptTokens + responseTokens*completionRatio
  201. } else {
  202. quota = textResponse.Usage.PromptTokens + textResponse.Usage.CompletionTokens*completionRatio
  203. }
  204. quota = int(float64(quota) * ratio)
  205. quotaDelta := quota - preConsumedQuota
  206. err := model.PostConsumeTokenQuota(tokenId, quotaDelta)
  207. if err != nil {
  208. common.SysError("Error consuming token remain quota: " + err.Error())
  209. }
  210. }
  211. }()
  212. if isStream {
  213. scanner := bufio.NewScanner(resp.Body)
  214. scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
  215. if atEOF && len(data) == 0 {
  216. return 0, nil, nil
  217. }
  218. if i := strings.Index(string(data), "\n\n"); i >= 0 {
  219. return i + 2, data[0:i], nil
  220. }
  221. if atEOF {
  222. return len(data), data, nil
  223. }
  224. return 0, nil, nil
  225. })
  226. dataChan := make(chan string)
  227. stopChan := make(chan bool)
  228. go func() {
  229. for scanner.Scan() {
  230. data := scanner.Text()
  231. if len(data) < 6 { // must be something wrong!
  232. common.SysError("Invalid stream response: " + data)
  233. continue
  234. }
  235. dataChan <- data
  236. data = data[6:]
  237. if !strings.HasPrefix(data, "[DONE]") {
  238. var streamResponse StreamResponse
  239. err = json.Unmarshal([]byte(data), &streamResponse)
  240. if err != nil {
  241. common.SysError("Error unmarshalling stream response: " + err.Error())
  242. return
  243. }
  244. for _, choice := range streamResponse.Choices {
  245. streamResponseText += choice.Delta.Content
  246. }
  247. }
  248. }
  249. stopChan <- true
  250. }()
  251. c.Writer.Header().Set("Content-Type", "text/event-stream")
  252. c.Writer.Header().Set("Cache-Control", "no-cache")
  253. c.Writer.Header().Set("Connection", "keep-alive")
  254. c.Writer.Header().Set("Transfer-Encoding", "chunked")
  255. c.Writer.Header().Set("X-Accel-Buffering", "no")
  256. c.Stream(func(w io.Writer) bool {
  257. select {
  258. case data := <-dataChan:
  259. if strings.HasPrefix(data, "data: [DONE]") {
  260. data = data[:12]
  261. }
  262. c.Render(-1, common.CustomEvent{Data: data})
  263. return true
  264. case <-stopChan:
  265. return false
  266. }
  267. })
  268. err = resp.Body.Close()
  269. if err != nil {
  270. return errorWrapper(err, "close_response_body_failed", http.StatusOK)
  271. }
  272. return nil
  273. } else {
  274. if consumeQuota {
  275. responseBody, err := io.ReadAll(resp.Body)
  276. if err != nil {
  277. return errorWrapper(err, "read_response_body_failed", http.StatusOK)
  278. }
  279. err = resp.Body.Close()
  280. if err != nil {
  281. return errorWrapper(err, "close_response_body_failed", http.StatusOK)
  282. }
  283. err = json.Unmarshal(responseBody, &textResponse)
  284. if err != nil {
  285. return errorWrapper(err, "unmarshal_response_body_failed", http.StatusOK)
  286. }
  287. if textResponse.Error.Type != "" {
  288. return &OpenAIErrorWithStatusCode{
  289. OpenAIError: textResponse.Error,
  290. StatusCode: resp.StatusCode,
  291. }
  292. }
  293. // Reset response body
  294. resp.Body = io.NopCloser(bytes.NewBuffer(responseBody))
  295. }
  296. // We shouldn't set the header before we parse the response body, because the parse part may fail.
  297. // And then we will have to send an error response, but in this case, the header has already been set.
  298. // So the client will be confused by the response.
  299. // For example, Postman will report error, and we cannot check the response at all.
  300. for k, v := range resp.Header {
  301. c.Writer.Header().Set(k, v[0])
  302. }
  303. c.Writer.WriteHeader(resp.StatusCode)
  304. _, err = io.Copy(c.Writer, resp.Body)
  305. if err != nil {
  306. return errorWrapper(err, "copy_response_body_failed", http.StatusOK)
  307. }
  308. err = resp.Body.Close()
  309. if err != nil {
  310. return errorWrapper(err, "close_response_body_failed", http.StatusOK)
  311. }
  312. return nil
  313. }
  314. }
  315. func RelayNotImplemented(c *gin.Context) {
  316. err := OpenAIError{
  317. Message: "API not implemented",
  318. Type: "one_api_error",
  319. Param: "",
  320. Code: "api_not_implemented",
  321. }
  322. c.JSON(http.StatusOK, gin.H{
  323. "error": err,
  324. })
  325. }