relay.go 12 KB

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