2023-06-19 02:28:55 +00:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2023-06-25 02:25:33 +00:00
|
|
|
"errors"
|
2023-06-19 02:28:55 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"one-api/common"
|
|
|
|
"one-api/model"
|
|
|
|
"strings"
|
2023-07-15 04:03:23 +00:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-06-19 02:28:55 +00:00
|
|
|
)
|
|
|
|
|
2023-07-22 08:18:03 +00:00
|
|
|
const (
|
|
|
|
APITypeOpenAI = iota
|
|
|
|
APITypeClaude
|
|
|
|
APITypePaLM
|
2023-07-22 15:24:09 +00:00
|
|
|
APITypeBaidu
|
2023-07-22 08:18:03 +00:00
|
|
|
)
|
|
|
|
|
2023-06-19 07:00:22 +00:00
|
|
|
func relayTextHelper(c *gin.Context, relayMode int) *OpenAIErrorWithStatusCode {
|
2023-06-19 02:28:55 +00:00
|
|
|
channelType := c.GetInt("channel")
|
|
|
|
tokenId := c.GetInt("token_id")
|
2023-06-21 09:26:26 +00:00
|
|
|
userId := c.GetInt("id")
|
2023-06-19 02:28:55 +00:00
|
|
|
consumeQuota := c.GetBool("consume_quota")
|
|
|
|
group := c.GetString("group")
|
|
|
|
var textRequest GeneralOpenAIRequest
|
|
|
|
if consumeQuota || channelType == common.ChannelTypeAzure || channelType == common.ChannelTypePaLM {
|
|
|
|
err := common.UnmarshalBodyReusable(c, &textRequest)
|
|
|
|
if err != nil {
|
|
|
|
return errorWrapper(err, "bind_request_body_failed", http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
}
|
2023-06-25 03:46:23 +00:00
|
|
|
if relayMode == RelayModeModerations && textRequest.Model == "" {
|
2023-06-19 02:28:55 +00:00
|
|
|
textRequest.Model = "text-moderation-latest"
|
|
|
|
}
|
2023-07-15 04:03:23 +00:00
|
|
|
if relayMode == RelayModeEmbeddings && textRequest.Model == "" {
|
|
|
|
textRequest.Model = c.Param("model")
|
|
|
|
}
|
2023-06-25 02:25:33 +00:00
|
|
|
// request validation
|
|
|
|
if textRequest.Model == "" {
|
|
|
|
return errorWrapper(errors.New("model is required"), "required_field_missing", http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
switch relayMode {
|
|
|
|
case RelayModeCompletions:
|
|
|
|
if textRequest.Prompt == "" {
|
2023-06-25 03:46:23 +00:00
|
|
|
return errorWrapper(errors.New("field prompt is required"), "required_field_missing", http.StatusBadRequest)
|
2023-06-25 02:25:33 +00:00
|
|
|
}
|
|
|
|
case RelayModeChatCompletions:
|
2023-06-25 03:46:23 +00:00
|
|
|
if textRequest.Messages == nil || len(textRequest.Messages) == 0 {
|
|
|
|
return errorWrapper(errors.New("field messages is required"), "required_field_missing", http.StatusBadRequest)
|
2023-06-25 02:25:33 +00:00
|
|
|
}
|
|
|
|
case RelayModeEmbeddings:
|
2023-06-25 03:46:23 +00:00
|
|
|
case RelayModeModerations:
|
2023-06-25 02:25:33 +00:00
|
|
|
if textRequest.Input == "" {
|
2023-06-25 03:46:23 +00:00
|
|
|
return errorWrapper(errors.New("field input is required"), "required_field_missing", http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
case RelayModeEdits:
|
|
|
|
if textRequest.Instruction == "" {
|
|
|
|
return errorWrapper(errors.New("field instruction is required"), "required_field_missing", http.StatusBadRequest)
|
2023-06-25 02:25:33 +00:00
|
|
|
}
|
|
|
|
}
|
2023-06-27 05:42:45 +00:00
|
|
|
// map model name
|
|
|
|
modelMapping := c.GetString("model_mapping")
|
|
|
|
isModelMapped := false
|
|
|
|
if modelMapping != "" {
|
|
|
|
modelMap := make(map[string]string)
|
|
|
|
err := json.Unmarshal([]byte(modelMapping), &modelMap)
|
|
|
|
if err != nil {
|
|
|
|
return errorWrapper(err, "unmarshal_model_mapping_failed", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
if modelMap[textRequest.Model] != "" {
|
|
|
|
textRequest.Model = modelMap[textRequest.Model]
|
|
|
|
isModelMapped = true
|
|
|
|
}
|
|
|
|
}
|
2023-07-22 08:18:03 +00:00
|
|
|
apiType := APITypeOpenAI
|
|
|
|
if strings.HasPrefix(textRequest.Model, "claude") {
|
|
|
|
apiType = APITypeClaude
|
2023-07-22 15:24:09 +00:00
|
|
|
} else if strings.HasPrefix(textRequest.Model, "ERNIE") {
|
|
|
|
apiType = APITypeBaidu
|
2023-07-22 08:18:03 +00:00
|
|
|
}
|
2023-06-19 02:28:55 +00:00
|
|
|
baseURL := common.ChannelBaseURLs[channelType]
|
|
|
|
requestURL := c.Request.URL.String()
|
2023-06-20 14:32:56 +00:00
|
|
|
if c.GetString("base_url") != "" {
|
2023-06-19 02:28:55 +00:00
|
|
|
baseURL = c.GetString("base_url")
|
|
|
|
}
|
|
|
|
fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
|
2023-07-22 08:18:03 +00:00
|
|
|
switch apiType {
|
|
|
|
case APITypeOpenAI:
|
|
|
|
if channelType == common.ChannelTypeAzure {
|
|
|
|
// https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
|
|
|
|
query := c.Request.URL.Query()
|
|
|
|
apiVersion := query.Get("api-version")
|
|
|
|
if apiVersion == "" {
|
|
|
|
apiVersion = c.GetString("api_version")
|
|
|
|
}
|
|
|
|
requestURL := strings.Split(requestURL, "?")[0]
|
|
|
|
requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
|
|
|
|
baseURL = c.GetString("base_url")
|
|
|
|
task := strings.TrimPrefix(requestURL, "/v1/")
|
|
|
|
model_ := textRequest.Model
|
|
|
|
model_ = strings.Replace(model_, ".", "", -1)
|
|
|
|
// https://github.com/songquanpeng/one-api/issues/67
|
|
|
|
model_ = strings.TrimSuffix(model_, "-0301")
|
|
|
|
model_ = strings.TrimSuffix(model_, "-0314")
|
|
|
|
model_ = strings.TrimSuffix(model_, "-0613")
|
|
|
|
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/%s", baseURL, model_, task)
|
|
|
|
}
|
|
|
|
case APITypeClaude:
|
|
|
|
fullRequestURL = "https://api.anthropic.com/v1/complete"
|
|
|
|
if baseURL != "" {
|
|
|
|
fullRequestURL = fmt.Sprintf("%s/v1/complete", baseURL)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-22 15:24:09 +00:00
|
|
|
case APITypeBaidu:
|
|
|
|
switch textRequest.Model {
|
|
|
|
case "ERNIE-Bot":
|
|
|
|
fullRequestURL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
|
|
|
|
case "ERNIE-Bot-turbo":
|
|
|
|
fullRequestURL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant"
|
|
|
|
case "BLOOMZ-7B":
|
|
|
|
fullRequestURL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/bloomz_7b1"
|
|
|
|
}
|
|
|
|
apiKey := c.Request.Header.Get("Authorization")
|
|
|
|
apiKey = strings.TrimPrefix(apiKey, "Bearer ")
|
|
|
|
fullRequestURL += "?access_token=" + apiKey // TODO: access token expire in 30 days
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
var promptTokens int
|
2023-06-24 07:28:11 +00:00
|
|
|
var completionTokens int
|
2023-06-19 02:28:55 +00:00
|
|
|
switch relayMode {
|
|
|
|
case RelayModeChatCompletions:
|
|
|
|
promptTokens = countTokenMessages(textRequest.Messages, textRequest.Model)
|
|
|
|
case RelayModeCompletions:
|
|
|
|
promptTokens = countTokenInput(textRequest.Prompt, textRequest.Model)
|
2023-06-25 03:46:23 +00:00
|
|
|
case RelayModeModerations:
|
2023-06-19 02:28:55 +00:00
|
|
|
promptTokens = countTokenInput(textRequest.Input, textRequest.Model)
|
|
|
|
}
|
|
|
|
preConsumedTokens := common.PreConsumedQuota
|
|
|
|
if textRequest.MaxTokens != 0 {
|
|
|
|
preConsumedTokens = promptTokens + textRequest.MaxTokens
|
|
|
|
}
|
|
|
|
modelRatio := common.GetModelRatio(textRequest.Model)
|
|
|
|
groupRatio := common.GetGroupRatio(group)
|
|
|
|
ratio := modelRatio * groupRatio
|
|
|
|
preConsumedQuota := int(float64(preConsumedTokens) * ratio)
|
2023-06-21 09:26:26 +00:00
|
|
|
userQuota, err := model.CacheGetUserQuota(userId)
|
|
|
|
if err != nil {
|
2023-06-23 14:59:44 +00:00
|
|
|
return errorWrapper(err, "get_user_quota_failed", http.StatusInternalServerError)
|
2023-06-21 09:26:26 +00:00
|
|
|
}
|
|
|
|
if userQuota > 10*preConsumedQuota {
|
|
|
|
// in this case, we do not pre-consume quota
|
|
|
|
// because the user has enough quota
|
|
|
|
preConsumedQuota = 0
|
|
|
|
}
|
|
|
|
if consumeQuota && preConsumedQuota > 0 {
|
2023-06-19 02:28:55 +00:00
|
|
|
err := model.PreConsumeTokenQuota(tokenId, preConsumedQuota)
|
|
|
|
if err != nil {
|
2023-06-23 14:59:44 +00:00
|
|
|
return errorWrapper(err, "pre_consume_token_quota_failed", http.StatusForbidden)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
}
|
2023-06-27 05:42:45 +00:00
|
|
|
var requestBody io.Reader
|
|
|
|
if isModelMapped {
|
|
|
|
jsonStr, err := json.Marshal(textRequest)
|
|
|
|
if err != nil {
|
|
|
|
return errorWrapper(err, "marshal_text_request_failed", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
requestBody = bytes.NewBuffer(jsonStr)
|
|
|
|
} else {
|
|
|
|
requestBody = c.Request.Body
|
|
|
|
}
|
2023-07-22 08:18:03 +00:00
|
|
|
switch apiType {
|
|
|
|
case APITypeClaude:
|
2023-07-22 09:12:13 +00:00
|
|
|
claudeRequest := requestOpenAI2Claude(textRequest)
|
2023-07-22 08:18:03 +00:00
|
|
|
jsonStr, err := json.Marshal(claudeRequest)
|
|
|
|
if err != nil {
|
|
|
|
return errorWrapper(err, "marshal_text_request_failed", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
requestBody = bytes.NewBuffer(jsonStr)
|
2023-07-22 15:24:09 +00:00
|
|
|
case APITypeBaidu:
|
|
|
|
baiduRequest := requestOpenAI2Baidu(textRequest)
|
|
|
|
jsonStr, err := json.Marshal(baiduRequest)
|
|
|
|
if err != nil {
|
|
|
|
return errorWrapper(err, "marshal_text_request_failed", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
requestBody = bytes.NewBuffer(jsonStr)
|
2023-07-22 08:18:03 +00:00
|
|
|
}
|
2023-06-27 05:42:45 +00:00
|
|
|
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
|
2023-06-19 02:28:55 +00:00
|
|
|
if err != nil {
|
2023-06-23 14:59:44 +00:00
|
|
|
return errorWrapper(err, "new_request_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-22 08:18:03 +00:00
|
|
|
apiKey := c.Request.Header.Get("Authorization")
|
|
|
|
apiKey = strings.TrimPrefix(apiKey, "Bearer ")
|
|
|
|
switch apiType {
|
|
|
|
case APITypeOpenAI:
|
|
|
|
if channelType == common.ChannelTypeAzure {
|
|
|
|
req.Header.Set("api-key", apiKey)
|
|
|
|
} else {
|
|
|
|
req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
|
|
|
|
}
|
|
|
|
case APITypeClaude:
|
|
|
|
req.Header.Set("x-api-key", apiKey)
|
|
|
|
anthropicVersion := c.Request.Header.Get("anthropic-version")
|
|
|
|
if anthropicVersion == "" {
|
|
|
|
anthropicVersion = "2023-06-01"
|
|
|
|
}
|
|
|
|
req.Header.Set("anthropic-version", anthropicVersion)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
|
|
|
req.Header.Set("Accept", c.Request.Header.Get("Accept"))
|
2023-07-04 13:24:49 +00:00
|
|
|
//req.Header.Set("Connection", c.Request.Header.Get("Connection"))
|
2023-06-19 02:28:55 +00:00
|
|
|
client := &http.Client{}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
2023-06-23 14:59:44 +00:00
|
|
|
return errorWrapper(err, "do_request_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
err = req.Body.Close()
|
|
|
|
if err != nil {
|
2023-06-23 14:59:44 +00:00
|
|
|
return errorWrapper(err, "close_request_body_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
2023-06-23 14:59:44 +00:00
|
|
|
return errorWrapper(err, "close_request_body_failed", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
var textResponse TextResponse
|
|
|
|
isStream := strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream")
|
|
|
|
var streamResponseText string
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if consumeQuota {
|
|
|
|
quota := 0
|
2023-06-25 03:46:23 +00:00
|
|
|
completionRatio := 1.0
|
|
|
|
if strings.HasPrefix(textRequest.Model, "gpt-3.5") {
|
|
|
|
completionRatio = 1.333333
|
|
|
|
}
|
2023-06-19 02:28:55 +00:00
|
|
|
if strings.HasPrefix(textRequest.Model, "gpt-4") {
|
|
|
|
completionRatio = 2
|
|
|
|
}
|
2023-07-22 15:24:09 +00:00
|
|
|
if isStream && apiType != APITypeBaidu {
|
2023-06-24 07:28:11 +00:00
|
|
|
completionTokens = countTokenText(streamResponseText, textRequest.Model)
|
2023-06-19 02:28:55 +00:00
|
|
|
} else {
|
2023-06-24 07:28:11 +00:00
|
|
|
promptTokens = textResponse.Usage.PromptTokens
|
|
|
|
completionTokens = textResponse.Usage.CompletionTokens
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-06-24 07:28:11 +00:00
|
|
|
quota = promptTokens + int(float64(completionTokens)*completionRatio)
|
2023-06-19 02:28:55 +00:00
|
|
|
quota = int(float64(quota) * ratio)
|
|
|
|
if ratio != 0 && quota <= 0 {
|
|
|
|
quota = 1
|
|
|
|
}
|
2023-06-25 01:56:03 +00:00
|
|
|
totalTokens := promptTokens + completionTokens
|
|
|
|
if totalTokens == 0 {
|
|
|
|
// in this case, must be some error happened
|
|
|
|
// we cannot just return, because we may have to return the pre-consumed quota
|
|
|
|
quota = 0
|
|
|
|
}
|
2023-06-19 02:28:55 +00:00
|
|
|
quotaDelta := quota - preConsumedQuota
|
|
|
|
err := model.PostConsumeTokenQuota(tokenId, quotaDelta)
|
|
|
|
if err != nil {
|
2023-06-22 02:59:01 +00:00
|
|
|
common.SysError("error consuming token remain quota: " + err.Error())
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-06-27 11:22:58 +00:00
|
|
|
err = model.CacheUpdateUserQuota(userId)
|
|
|
|
if err != nil {
|
|
|
|
common.SysError("error update user quota cache: " + err.Error())
|
|
|
|
}
|
2023-06-25 01:59:58 +00:00
|
|
|
if quota != 0 {
|
|
|
|
tokenName := c.GetString("token_name")
|
2023-06-25 12:29:42 +00:00
|
|
|
logContent := fmt.Sprintf("模型倍率 %.2f,分组倍率 %.2f", modelRatio, groupRatio)
|
2023-06-25 01:59:58 +00:00
|
|
|
model.RecordConsumeLog(userId, promptTokens, completionTokens, textRequest.Model, tokenName, quota, logContent)
|
|
|
|
model.UpdateUserUsedQuotaAndRequestCount(userId, quota)
|
|
|
|
channelId := c.GetInt("channel_id")
|
|
|
|
model.UpdateChannelUsedQuota(channelId, quota)
|
|
|
|
}
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
}()
|
2023-07-22 08:18:03 +00:00
|
|
|
switch apiType {
|
|
|
|
case APITypeOpenAI:
|
|
|
|
if isStream {
|
2023-07-22 09:48:45 +00:00
|
|
|
err, responseText := openaiStreamHandler(c, resp, relayMode)
|
2023-07-22 08:18:03 +00:00
|
|
|
if err != nil {
|
2023-07-22 09:48:45 +00:00
|
|
|
return err
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-22 09:48:45 +00:00
|
|
|
streamResponseText = responseText
|
2023-07-22 08:18:03 +00:00
|
|
|
return nil
|
|
|
|
} else {
|
2023-07-22 09:48:45 +00:00
|
|
|
err, usage := openaiHandler(c, resp, consumeQuota)
|
2023-07-22 08:18:03 +00:00
|
|
|
if err != nil {
|
2023-07-22 09:48:45 +00:00
|
|
|
return err
|
2023-07-22 08:18:03 +00:00
|
|
|
}
|
2023-07-22 09:48:45 +00:00
|
|
|
textResponse.Usage = *usage
|
2023-07-22 08:18:03 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
case APITypeClaude:
|
|
|
|
if isStream {
|
2023-07-22 09:36:40 +00:00
|
|
|
err, responseText := claudeStreamHandler(c, resp)
|
2023-07-22 08:18:03 +00:00
|
|
|
if err != nil {
|
2023-07-22 09:36:40 +00:00
|
|
|
return err
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-22 09:36:40 +00:00
|
|
|
streamResponseText = responseText
|
2023-07-22 08:18:03 +00:00
|
|
|
return nil
|
|
|
|
} else {
|
2023-07-22 09:36:40 +00:00
|
|
|
err, usage := claudeHandler(c, resp, promptTokens, textRequest.Model)
|
2023-06-19 02:28:55 +00:00
|
|
|
if err != nil {
|
2023-07-22 09:36:40 +00:00
|
|
|
return err
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-22 09:36:40 +00:00
|
|
|
textResponse.Usage = *usage
|
2023-07-22 08:18:03 +00:00
|
|
|
return nil
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
2023-07-22 15:24:09 +00:00
|
|
|
case APITypeBaidu:
|
|
|
|
if isStream {
|
|
|
|
err, usage := baiduStreamHandler(c, resp)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
textResponse.Usage = *usage
|
|
|
|
return nil
|
|
|
|
} else {
|
|
|
|
err, usage := baiduHandler(c, resp)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
textResponse.Usage = *usage
|
|
|
|
return nil
|
|
|
|
}
|
2023-07-22 08:18:03 +00:00
|
|
|
default:
|
|
|
|
return errorWrapper(errors.New("unknown api type"), "unknown_api_type", http.StatusInternalServerError)
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
}
|