2023-04-23 10:24:11 +00:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
2023-04-25 12:27:53 +00:00
|
|
|
"bufio"
|
2023-04-28 08:58:55 +00:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2023-04-23 10:24:11 +00:00
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-04-28 10:36:17 +00:00
|
|
|
"github.com/pkoukk/tiktoken-go"
|
2023-04-23 10:24:11 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"one-api/common"
|
2023-04-26 02:45:34 +00:00
|
|
|
"one-api/model"
|
2023-04-25 12:27:53 +00:00
|
|
|
"strings"
|
2023-04-23 10:24:11 +00:00
|
|
|
)
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type Message struct {
|
|
|
|
Role string `json:"role"`
|
|
|
|
Content string `json:"content"`
|
|
|
|
}
|
|
|
|
|
2023-05-15 02:48:52 +00:00
|
|
|
type ChatRequest struct {
|
2023-05-16 08:22:25 +00:00
|
|
|
Model string `json:"model"`
|
|
|
|
Messages []Message `json:"messages"`
|
|
|
|
MaxTokens int `json:"max_tokens"`
|
2023-05-15 02:48:52 +00:00
|
|
|
}
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type TextRequest struct {
|
2023-05-16 08:18:35 +00:00
|
|
|
Model string `json:"model"`
|
|
|
|
Messages []Message `json:"messages"`
|
|
|
|
Prompt string `json:"prompt"`
|
|
|
|
MaxTokens int `json:"max_tokens"`
|
2023-04-28 08:58:55 +00:00
|
|
|
//Stream bool `json:"stream"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type Usage struct {
|
|
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
|
|
CompletionTokens int `json:"completion_tokens"`
|
|
|
|
TotalTokens int `json:"total_tokens"`
|
|
|
|
}
|
|
|
|
|
2023-05-15 02:48:52 +00:00
|
|
|
type OpenAIError struct {
|
|
|
|
Message string `json:"message"`
|
|
|
|
Type string `json:"type"`
|
|
|
|
Param string `json:"param"`
|
|
|
|
Code string `json:"code"`
|
|
|
|
}
|
|
|
|
|
2023-05-18 03:11:15 +00:00
|
|
|
type OpenAIErrorWithStatusCode struct {
|
|
|
|
OpenAIError
|
|
|
|
StatusCode int `json:"status_code"`
|
|
|
|
}
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type TextResponse struct {
|
|
|
|
Usage `json:"usage"`
|
2023-05-15 02:48:52 +00:00
|
|
|
Error OpenAIError `json:"error"`
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type StreamResponse struct {
|
|
|
|
Choices []struct {
|
|
|
|
Delta struct {
|
|
|
|
Content string `json:"content"`
|
|
|
|
} `json:"delta"`
|
|
|
|
FinishReason string `json:"finish_reason"`
|
|
|
|
} `json:"choices"`
|
|
|
|
}
|
|
|
|
|
2023-04-28 10:36:17 +00:00
|
|
|
var tokenEncoder, _ = tiktoken.GetEncoding("cl100k_base")
|
|
|
|
|
|
|
|
func countToken(text string) int {
|
|
|
|
token := tokenEncoder.Encode(text, nil, nil)
|
|
|
|
return len(token)
|
|
|
|
}
|
|
|
|
|
2023-04-23 10:24:11 +00:00
|
|
|
func Relay(c *gin.Context) {
|
2023-04-28 09:11:57 +00:00
|
|
|
err := relayHelper(c)
|
|
|
|
if err != nil {
|
2023-05-18 07:27:15 +00:00
|
|
|
if err.StatusCode == http.StatusTooManyRequests {
|
|
|
|
err.OpenAIError.Message = "负载已满,请稍后再试,或升级账户以提升服务质量。"
|
|
|
|
}
|
2023-05-18 03:11:15 +00:00
|
|
|
c.JSON(err.StatusCode, gin.H{
|
|
|
|
"error": err.OpenAIError,
|
2023-04-28 09:11:57 +00:00
|
|
|
})
|
2023-05-17 12:20:48 +00:00
|
|
|
channelId := c.GetInt("channel_id")
|
2023-05-18 03:11:15 +00:00
|
|
|
common.SysError(fmt.Sprintf("Relay error (channel #%d): %s", channelId, err.Message))
|
|
|
|
if err.Type != "invalid_request_error" && err.StatusCode != http.StatusTooManyRequests &&
|
|
|
|
common.AutomaticDisableChannelEnabled {
|
2023-05-15 09:34:09 +00:00
|
|
|
channelId := c.GetInt("channel_id")
|
|
|
|
channelName := c.GetString("channel_name")
|
2023-05-18 03:11:15 +00:00
|
|
|
disableChannel(channelId, channelName, err.Message)
|
2023-05-15 09:34:09 +00:00
|
|
|
}
|
2023-04-28 09:11:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-18 03:11:15 +00:00
|
|
|
func errorWrapper(err error, code string, statusCode int) *OpenAIErrorWithStatusCode {
|
|
|
|
openAIError := OpenAIError{
|
|
|
|
Message: err.Error(),
|
|
|
|
Type: "one_api_error",
|
|
|
|
Code: code,
|
|
|
|
}
|
|
|
|
return &OpenAIErrorWithStatusCode{
|
|
|
|
OpenAIError: openAIError,
|
|
|
|
StatusCode: statusCode,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func relayHelper(c *gin.Context) *OpenAIErrorWithStatusCode {
|
2023-04-23 10:24:11 +00:00
|
|
|
channelType := c.GetInt("channel")
|
2023-04-26 02:45:34 +00:00
|
|
|
tokenId := c.GetInt("token_id")
|
2023-04-28 08:58:55 +00:00
|
|
|
consumeQuota := c.GetBool("consume_quota")
|
2023-04-28 10:36:17 +00:00
|
|
|
var textRequest TextRequest
|
2023-05-13 03:36:36 +00:00
|
|
|
if consumeQuota || channelType == common.ChannelTypeAzure {
|
2023-04-28 10:16:59 +00:00
|
|
|
requestBody, err := io.ReadAll(c.Request.Body)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "read_request_body_failed", http.StatusBadRequest)
|
2023-04-28 10:16:59 +00:00
|
|
|
}
|
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "close_request_body_failed", http.StatusBadRequest)
|
2023-04-28 10:16:59 +00:00
|
|
|
}
|
|
|
|
err = json.Unmarshal(requestBody, &textRequest)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "unmarshal_request_body_failed", http.StatusBadRequest)
|
2023-04-28 10:16:59 +00:00
|
|
|
}
|
|
|
|
// Reset request body
|
|
|
|
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
2023-05-13 03:36:36 +00:00
|
|
|
baseURL := common.ChannelBaseURLs[channelType]
|
2023-04-26 02:45:34 +00:00
|
|
|
requestURL := c.Request.URL.String()
|
2023-05-13 03:36:36 +00:00
|
|
|
if channelType == common.ChannelTypeCustom {
|
|
|
|
baseURL = c.GetString("base_url")
|
|
|
|
}
|
|
|
|
fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
|
|
|
|
if channelType == common.ChannelTypeAzure {
|
|
|
|
// https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
|
2023-05-13 03:41:57 +00:00
|
|
|
query := c.Request.URL.Query()
|
2023-05-14 01:39:42 +00:00
|
|
|
apiVersion := query.Get("api-version")
|
|
|
|
if apiVersion == "" {
|
|
|
|
apiVersion = c.GetString("api_version")
|
2023-05-13 03:41:57 +00:00
|
|
|
}
|
2023-05-14 01:39:42 +00:00
|
|
|
requestURL := strings.Split(requestURL, "?")[0]
|
|
|
|
requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
|
2023-05-13 03:36:36 +00:00
|
|
|
baseURL = c.GetString("base_url")
|
|
|
|
task := strings.TrimPrefix(requestURL, "/v1/")
|
|
|
|
model_ := textRequest.Model
|
2023-05-13 04:24:49 +00:00
|
|
|
model_ = strings.Replace(model_, ".", "", -1)
|
2023-05-15 07:48:18 +00:00
|
|
|
// https://github.com/songquanpeng/one-api/issues/67
|
|
|
|
model_ = strings.TrimSuffix(model_, "-0301")
|
|
|
|
model_ = strings.TrimSuffix(model_, "-0314")
|
2023-05-13 03:36:36 +00:00
|
|
|
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/%s", baseURL, model_, task)
|
|
|
|
}
|
2023-05-16 08:18:35 +00:00
|
|
|
var promptText string
|
|
|
|
for _, message := range textRequest.Messages {
|
|
|
|
promptText += fmt.Sprintf("%s: %s\n", message.Role, message.Content)
|
|
|
|
}
|
|
|
|
promptTokens := countToken(promptText) + 3
|
|
|
|
preConsumedTokens := common.PreConsumedQuota
|
|
|
|
if textRequest.MaxTokens != 0 {
|
|
|
|
preConsumedTokens = promptTokens + textRequest.MaxTokens
|
|
|
|
}
|
2023-05-16 05:57:01 +00:00
|
|
|
ratio := common.GetModelRatio(textRequest.Model)
|
2023-05-16 08:18:35 +00:00
|
|
|
preConsumedQuota := int(float64(preConsumedTokens) * ratio)
|
2023-05-16 05:29:22 +00:00
|
|
|
if consumeQuota {
|
|
|
|
err := model.PreConsumeTokenQuota(tokenId, preConsumedQuota)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "pre_consume_token_quota_failed", http.StatusOK)
|
2023-05-16 05:29:22 +00:00
|
|
|
}
|
|
|
|
}
|
2023-05-13 03:36:36 +00:00
|
|
|
req, err := http.NewRequest(c.Request.Method, fullRequestURL, c.Request.Body)
|
2023-04-23 10:24:11 +00:00
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "new_request_failed", http.StatusOK)
|
2023-04-28 09:11:57 +00:00
|
|
|
}
|
2023-05-13 03:36:36 +00:00
|
|
|
if channelType == common.ChannelTypeAzure {
|
|
|
|
key := c.Request.Header.Get("Authorization")
|
|
|
|
key = strings.TrimPrefix(key, "Bearer ")
|
|
|
|
req.Header.Set("api-key", key)
|
|
|
|
} else {
|
|
|
|
req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
|
|
|
|
}
|
2023-04-25 02:47:25 +00:00
|
|
|
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
2023-04-25 12:27:53 +00:00
|
|
|
req.Header.Set("Accept", c.Request.Header.Get("Accept"))
|
|
|
|
req.Header.Set("Connection", c.Request.Header.Get("Connection"))
|
2023-04-23 10:24:11 +00:00
|
|
|
client := &http.Client{}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "do_request_failed", http.StatusOK)
|
2023-04-23 10:24:11 +00:00
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
err = req.Body.Close()
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "close_request_body_failed", http.StatusOK)
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
2023-04-29 06:49:10 +00:00
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "close_request_body_failed", http.StatusOK)
|
2023-04-29 06:49:10 +00:00
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
var textResponse TextResponse
|
2023-05-17 12:10:09 +00:00
|
|
|
isStream := strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream")
|
2023-04-28 08:58:55 +00:00
|
|
|
var streamResponseText string
|
2023-04-26 02:45:34 +00:00
|
|
|
|
|
|
|
defer func() {
|
2023-04-28 08:58:55 +00:00
|
|
|
if consumeQuota {
|
|
|
|
quota := 0
|
2023-05-11 12:59:35 +00:00
|
|
|
usingGPT4 := strings.HasPrefix(textRequest.Model, "gpt-4")
|
|
|
|
completionRatio := 1
|
|
|
|
if usingGPT4 {
|
|
|
|
completionRatio = 2
|
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
if isStream {
|
2023-05-11 12:59:35 +00:00
|
|
|
completionText := fmt.Sprintf("%s: %s\n", "assistant", streamResponseText)
|
2023-05-16 08:18:35 +00:00
|
|
|
quota = promptTokens + countToken(completionText)*completionRatio
|
2023-04-28 11:16:37 +00:00
|
|
|
} else {
|
2023-05-11 12:59:35 +00:00
|
|
|
quota = textResponse.Usage.PromptTokens + textResponse.Usage.CompletionTokens*completionRatio
|
2023-04-28 11:16:37 +00:00
|
|
|
}
|
|
|
|
quota = int(float64(quota) * ratio)
|
2023-05-16 05:29:22 +00:00
|
|
|
quotaDelta := quota - preConsumedQuota
|
|
|
|
err := model.PostConsumeTokenQuota(tokenId, quotaDelta)
|
2023-04-26 02:45:34 +00:00
|
|
|
if err != nil {
|
2023-04-28 08:58:55 +00:00
|
|
|
common.SysError("Error consuming token remain quota: " + err.Error())
|
2023-04-26 02:45:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2023-04-28 08:58:55 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
if isStream {
|
|
|
|
scanner := bufio.NewScanner(resp.Body)
|
|
|
|
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
|
|
|
if atEOF && len(data) == 0 {
|
|
|
|
return 0, nil, nil
|
|
|
|
}
|
2023-04-25 12:27:53 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
if i := strings.Index(string(data), "\n\n"); i >= 0 {
|
|
|
|
return i + 2, data[0:i], nil
|
|
|
|
}
|
2023-04-25 12:27:53 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
if atEOF {
|
|
|
|
return len(data), data, nil
|
|
|
|
}
|
2023-04-25 12:27:53 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
return 0, nil, nil
|
|
|
|
})
|
|
|
|
dataChan := make(chan string)
|
|
|
|
stopChan := make(chan bool)
|
|
|
|
go func() {
|
|
|
|
for scanner.Scan() {
|
|
|
|
data := scanner.Text()
|
|
|
|
dataChan <- data
|
2023-04-28 08:58:55 +00:00
|
|
|
data = data[6:]
|
2023-05-14 01:39:42 +00:00
|
|
|
if !strings.HasPrefix(data, "[DONE]") {
|
2023-04-28 08:58:55 +00:00
|
|
|
var streamResponse StreamResponse
|
|
|
|
err = json.Unmarshal([]byte(data), &streamResponse)
|
|
|
|
if err != nil {
|
|
|
|
common.SysError("Error unmarshalling stream response: " + err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for _, choice := range streamResponse.Choices {
|
|
|
|
streamResponseText += choice.Delta.Content
|
|
|
|
}
|
|
|
|
}
|
2023-04-25 12:45:50 +00:00
|
|
|
}
|
2023-04-25 13:50:57 +00:00
|
|
|
stopChan <- true
|
|
|
|
}()
|
|
|
|
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
|
|
|
c.Writer.Header().Set("Cache-Control", "no-cache")
|
|
|
|
c.Writer.Header().Set("Connection", "keep-alive")
|
|
|
|
c.Writer.Header().Set("Transfer-Encoding", "chunked")
|
|
|
|
c.Stream(func(w io.Writer) bool {
|
|
|
|
select {
|
|
|
|
case data := <-dataChan:
|
2023-05-14 01:39:42 +00:00
|
|
|
if strings.HasPrefix(data, "data: [DONE]") {
|
2023-05-14 04:53:03 +00:00
|
|
|
data = data[:12]
|
2023-05-14 01:39:42 +00:00
|
|
|
}
|
2023-04-25 13:50:57 +00:00
|
|
|
c.Render(-1, common.CustomEvent{Data: data})
|
|
|
|
return true
|
|
|
|
case <-stopChan:
|
2023-04-25 12:45:50 +00:00
|
|
|
return false
|
2023-04-25 12:27:53 +00:00
|
|
|
}
|
2023-04-25 13:50:57 +00:00
|
|
|
})
|
2023-04-28 09:11:57 +00:00
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "close_response_body_failed", http.StatusOK)
|
2023-04-28 09:11:57 +00:00
|
|
|
}
|
|
|
|
return nil
|
2023-04-25 13:50:57 +00:00
|
|
|
} else {
|
2023-04-28 10:16:59 +00:00
|
|
|
if consumeQuota {
|
|
|
|
responseBody, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "read_response_body_failed", http.StatusOK)
|
2023-04-28 10:16:59 +00:00
|
|
|
}
|
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "close_response_body_failed", http.StatusOK)
|
2023-04-28 10:16:59 +00:00
|
|
|
}
|
|
|
|
err = json.Unmarshal(responseBody, &textResponse)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "unmarshal_response_body_failed", http.StatusOK)
|
2023-04-28 10:16:59 +00:00
|
|
|
}
|
2023-05-15 09:34:09 +00:00
|
|
|
if textResponse.Error.Type != "" {
|
2023-05-18 03:11:15 +00:00
|
|
|
return &OpenAIErrorWithStatusCode{
|
|
|
|
OpenAIError: textResponse.Error,
|
|
|
|
StatusCode: resp.StatusCode,
|
|
|
|
}
|
2023-05-15 09:34:09 +00:00
|
|
|
}
|
2023-04-28 10:16:59 +00:00
|
|
|
// Reset response body
|
|
|
|
resp.Body = io.NopCloser(bytes.NewBuffer(responseBody))
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
2023-05-18 03:11:15 +00:00
|
|
|
// We shouldn't set the header before we parse the response body, because the parse part may fail.
|
|
|
|
// And then we will have to send an error response, but in this case, the header has already been set.
|
|
|
|
// So the client will be confused by the response.
|
|
|
|
// For example, Postman will report error, and we cannot check the response at all.
|
|
|
|
for k, v := range resp.Header {
|
|
|
|
c.Writer.Header().Set(k, v[0])
|
|
|
|
}
|
|
|
|
c.Writer.WriteHeader(resp.StatusCode)
|
2023-04-25 13:50:57 +00:00
|
|
|
_, err = io.Copy(c.Writer, resp.Body)
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "copy_response_body_failed", http.StatusOK)
|
2023-04-28 09:11:57 +00:00
|
|
|
}
|
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
2023-05-18 03:11:15 +00:00
|
|
|
return errorWrapper(err, "close_response_body_failed", http.StatusOK)
|
2023-04-25 12:27:53 +00:00
|
|
|
}
|
2023-04-28 09:11:57 +00:00
|
|
|
return nil
|
2023-04-25 13:50:57 +00:00
|
|
|
}
|
2023-04-23 10:24:11 +00:00
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
|
|
|
|
func RelayNotImplemented(c *gin.Context) {
|
2023-05-18 03:11:15 +00:00
|
|
|
err := OpenAIError{
|
|
|
|
Message: "API not implemented",
|
|
|
|
Type: "one_api_error",
|
|
|
|
Param: "",
|
|
|
|
Code: "api_not_implemented",
|
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
c.JSON(http.StatusOK, gin.H{
|
2023-05-18 03:11:15 +00:00
|
|
|
"error": err,
|
2023-04-28 08:58:55 +00:00
|
|
|
})
|
|
|
|
}
|