2023-05-19 09:41:26 +08:00
|
|
|
|
package controller
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2023-08-26 12:37:45 +08:00
|
|
|
|
"encoding/json"
|
2023-11-17 20:32:11 +08:00
|
|
|
|
"errors"
|
2023-05-19 09:41:26 +08:00
|
|
|
|
"fmt"
|
2023-08-12 21:55:18 +08:00
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-05-19 09:41:26 +08:00
|
|
|
|
"github.com/pkoukk/tiktoken-go"
|
2023-11-17 20:32:11 +08:00
|
|
|
|
"image"
|
|
|
|
|
|
_ "image/gif"
|
|
|
|
|
|
_ "image/jpeg"
|
|
|
|
|
|
_ "image/png"
|
2023-08-26 12:37:45 +08:00
|
|
|
|
"io"
|
2023-11-17 20:32:11 +08:00
|
|
|
|
"log"
|
|
|
|
|
|
"math"
|
2023-08-26 12:05:18 +08:00
|
|
|
|
"net/http"
|
2023-05-19 09:41:26 +08:00
|
|
|
|
"one-api/common"
|
2023-08-26 12:37:45 +08:00
|
|
|
|
"strconv"
|
2023-09-29 17:56:11 +08:00
|
|
|
|
"strings"
|
2023-11-15 21:05:14 +08:00
|
|
|
|
"unicode/utf8"
|
2023-05-19 09:41:26 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2023-08-12 11:04:53 +08:00
|
|
|
|
var stopFinishReason = "stop"
|
|
|
|
|
|
|
2023-09-29 17:56:11 +08:00
|
|
|
|
// tokenEncoderMap won't grow after initialization
|
2023-05-19 09:41:26 +08:00
|
|
|
|
var tokenEncoderMap = map[string]*tiktoken.Tiktoken{}
|
2023-09-29 17:56:11 +08:00
|
|
|
|
var defaultTokenEncoder *tiktoken.Tiktoken
|
2023-05-19 09:41:26 +08:00
|
|
|
|
|
2023-08-26 13:02:02 +08:00
|
|
|
|
func InitTokenEncoders() {
|
|
|
|
|
|
common.SysLog("initializing token encoders")
|
2023-09-29 17:56:11 +08:00
|
|
|
|
gpt35TokenEncoder, err := tiktoken.EncodingForModel("gpt-3.5-turbo")
|
2023-08-26 13:02:02 +08:00
|
|
|
|
if err != nil {
|
2023-09-29 17:56:11 +08:00
|
|
|
|
common.FatalLog(fmt.Sprintf("failed to get gpt-3.5-turbo token encoder: %s", err.Error()))
|
|
|
|
|
|
}
|
|
|
|
|
|
defaultTokenEncoder = gpt35TokenEncoder
|
|
|
|
|
|
gpt4TokenEncoder, err := tiktoken.EncodingForModel("gpt-4")
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
common.FatalLog(fmt.Sprintf("failed to get gpt-4 token encoder: %s", err.Error()))
|
2023-08-26 13:02:02 +08:00
|
|
|
|
}
|
|
|
|
|
|
for model, _ := range common.ModelRatio {
|
2023-09-29 17:56:11 +08:00
|
|
|
|
if strings.HasPrefix(model, "gpt-3.5") {
|
|
|
|
|
|
tokenEncoderMap[model] = gpt35TokenEncoder
|
|
|
|
|
|
} else if strings.HasPrefix(model, "gpt-4") {
|
|
|
|
|
|
tokenEncoderMap[model] = gpt4TokenEncoder
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tokenEncoderMap[model] = nil
|
2023-08-26 13:02:02 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
common.SysLog("token encoders initialized")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-05-19 09:41:26 +08:00
|
|
|
|
func getTokenEncoder(model string) *tiktoken.Tiktoken {
|
2023-09-29 17:56:11 +08:00
|
|
|
|
tokenEncoder, ok := tokenEncoderMap[model]
|
|
|
|
|
|
if ok && tokenEncoder != nil {
|
2023-05-19 09:41:26 +08:00
|
|
|
|
return tokenEncoder
|
|
|
|
|
|
}
|
2023-09-29 17:56:11 +08:00
|
|
|
|
if ok {
|
|
|
|
|
|
tokenEncoder, err := tiktoken.EncodingForModel(model)
|
2023-05-21 11:11:19 +08:00
|
|
|
|
if err != nil {
|
2023-09-29 17:56:11 +08:00
|
|
|
|
common.SysError(fmt.Sprintf("failed to get token encoder for model %s: %s, using encoder for gpt-3.5-turbo", model, err.Error()))
|
|
|
|
|
|
tokenEncoder = defaultTokenEncoder
|
2023-05-21 11:11:19 +08:00
|
|
|
|
}
|
2023-09-29 17:56:11 +08:00
|
|
|
|
tokenEncoderMap[model] = tokenEncoder
|
|
|
|
|
|
return tokenEncoder
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
2023-09-29 17:56:11 +08:00
|
|
|
|
return defaultTokenEncoder
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2023-07-04 19:54:13 +08:00
|
|
|
|
func getTokenNum(tokenEncoder *tiktoken.Tiktoken, text string) int {
|
|
|
|
|
|
return len(tokenEncoder.Encode(text, nil, nil))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-12-01 01:29:13 +08:00
|
|
|
|
func getImageToken(imageUrl *MessageImageUrl) (int, error) {
|
2023-11-17 20:32:11 +08:00
|
|
|
|
if imageUrl.Detail == "low" {
|
|
|
|
|
|
return 85, nil
|
|
|
|
|
|
}
|
2023-11-19 18:59:35 +08:00
|
|
|
|
var config image.Config
|
|
|
|
|
|
var err error
|
2023-12-27 16:32:54 +08:00
|
|
|
|
var format string
|
2023-11-19 18:59:35 +08:00
|
|
|
|
if strings.HasPrefix(imageUrl.Url, "http") {
|
|
|
|
|
|
common.SysLog(fmt.Sprintf("downloading image: %s", imageUrl.Url))
|
2023-12-27 16:32:54 +08:00
|
|
|
|
config, format, err = common.DecodeUrlImageData(imageUrl.Url)
|
2023-11-19 18:59:35 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
common.SysLog(fmt.Sprintf("decoding image"))
|
2023-12-27 16:32:54 +08:00
|
|
|
|
config, format, err = common.DecodeBase64ImageData(imageUrl.Url)
|
2023-11-19 18:59:35 +08:00
|
|
|
|
}
|
2023-11-17 20:32:11 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if config.Width == 0 || config.Height == 0 {
|
2023-11-19 18:59:35 +08:00
|
|
|
|
return 0, errors.New(fmt.Sprintf("fail to decode image config: %s", imageUrl.Url))
|
2023-11-17 20:32:11 +08:00
|
|
|
|
}
|
2023-12-01 01:29:13 +08:00
|
|
|
|
// TODO: 适配官方auto计费
|
2023-11-17 20:32:11 +08:00
|
|
|
|
if config.Width < 512 && config.Height < 512 {
|
|
|
|
|
|
if imageUrl.Detail == "auto" || imageUrl.Detail == "" {
|
2023-12-01 01:29:13 +08:00
|
|
|
|
// 如果图片尺寸小于512,强制使用low
|
|
|
|
|
|
imageUrl.Detail = "low"
|
2023-11-17 20:32:11 +08:00
|
|
|
|
return 85, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
shortSide := config.Width
|
|
|
|
|
|
otherSide := config.Height
|
2023-12-27 16:32:54 +08:00
|
|
|
|
log.Printf("format: %s, width: %d, height: %d", format, config.Width, config.Height)
|
2023-11-17 20:32:11 +08:00
|
|
|
|
// 缩放倍数
|
|
|
|
|
|
scale := 1.0
|
|
|
|
|
|
if config.Height < shortSide {
|
|
|
|
|
|
shortSide = config.Height
|
|
|
|
|
|
otherSide = config.Width
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 将最小变的尺寸缩小到768以下,如果大于768,则缩放到768
|
|
|
|
|
|
if shortSide > 768 {
|
|
|
|
|
|
scale = float64(shortSide) / 768
|
|
|
|
|
|
shortSide = 768
|
|
|
|
|
|
}
|
|
|
|
|
|
// 将另一边按照相同的比例缩小,向上取整
|
|
|
|
|
|
otherSide = int(math.Ceil(float64(otherSide) / scale))
|
|
|
|
|
|
log.Printf("shortSide: %d, otherSide: %d, scale: %f", shortSide, otherSide, scale)
|
|
|
|
|
|
// 计算图片的token数量(边的长度除以512,向上取整)
|
|
|
|
|
|
tiles := (shortSide + 511) / 512 * ((otherSide + 511) / 512)
|
|
|
|
|
|
log.Printf("tiles: %d", tiles)
|
|
|
|
|
|
return tiles*170 + 85, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-11-17 18:24:37 +08:00
|
|
|
|
func countTokenMessages(messages []Message, model string) (int, error) {
|
|
|
|
|
|
//recover when panic
|
2023-05-19 09:41:26 +08:00
|
|
|
|
tokenEncoder := getTokenEncoder(model)
|
|
|
|
|
|
// Reference:
|
|
|
|
|
|
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
|
|
|
|
|
|
// https://github.com/pkoukk/tiktoken-go/issues/6
|
|
|
|
|
|
//
|
|
|
|
|
|
// Every message follows <|start|>{role/name}\n{content}<|end|>\n
|
|
|
|
|
|
var tokensPerMessage int
|
|
|
|
|
|
var tokensPerName int
|
2023-07-03 09:42:34 +08:00
|
|
|
|
if model == "gpt-3.5-turbo-0301" {
|
2023-05-19 09:41:26 +08:00
|
|
|
|
tokensPerMessage = 4
|
|
|
|
|
|
tokensPerName = -1 // If there's a name, the role is omitted
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tokensPerMessage = 3
|
|
|
|
|
|
tokensPerName = 1
|
|
|
|
|
|
}
|
|
|
|
|
|
tokenNum := 0
|
|
|
|
|
|
for _, message := range messages {
|
|
|
|
|
|
tokenNum += tokensPerMessage
|
2023-07-04 19:54:13 +08:00
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, message.Role)
|
2023-11-17 18:24:37 +08:00
|
|
|
|
var arrayContent []MediaMessage
|
|
|
|
|
|
if err := json.Unmarshal(message.Content, &arrayContent); err != nil {
|
|
|
|
|
|
|
|
|
|
|
|
var stringContent string
|
|
|
|
|
|
if err := json.Unmarshal(message.Content, &stringContent); err != nil {
|
|
|
|
|
|
return 0, err
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, stringContent)
|
|
|
|
|
|
if message.Name != nil {
|
|
|
|
|
|
tokenNum += tokensPerName
|
|
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, *message.Name)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
for _, m := range arrayContent {
|
|
|
|
|
|
if m.Type == "image_url" {
|
2023-12-18 23:44:47 +08:00
|
|
|
|
var imageTokenNum int
|
|
|
|
|
|
if str, ok := m.ImageUrl.(string); ok {
|
|
|
|
|
|
imageTokenNum, err = getImageToken(&MessageImageUrl{Url: str, Detail: "auto"})
|
|
|
|
|
|
} else {
|
|
|
|
|
|
imageUrlMap := m.ImageUrl.(map[string]interface{})
|
|
|
|
|
|
detail, ok := imageUrlMap["detail"]
|
|
|
|
|
|
if ok {
|
|
|
|
|
|
imageUrlMap["detail"] = detail.(string)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
imageUrlMap["detail"] = "auto"
|
|
|
|
|
|
}
|
|
|
|
|
|
imageUrl := MessageImageUrl{
|
|
|
|
|
|
Url: imageUrlMap["url"].(string),
|
|
|
|
|
|
Detail: imageUrlMap["detail"].(string),
|
|
|
|
|
|
}
|
|
|
|
|
|
imageTokenNum, err = getImageToken(&imageUrl)
|
|
|
|
|
|
}
|
2023-11-17 20:32:11 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err
|
|
|
|
|
|
}
|
2023-12-18 23:44:47 +08:00
|
|
|
|
|
2023-11-17 20:32:11 +08:00
|
|
|
|
tokenNum += imageTokenNum
|
|
|
|
|
|
log.Printf("image token num: %d", imageTokenNum)
|
2023-11-17 18:24:37 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, m.Text)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
tokenNum += 3 // Every reply is primed with <|start|>assistant<|message|>
|
2023-11-17 18:24:37 +08:00
|
|
|
|
return tokenNum, nil
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2023-06-12 16:11:57 +08:00
|
|
|
|
func countTokenInput(input any, model string) int {
|
2023-12-26 23:49:43 +08:00
|
|
|
|
switch v := input.(type) {
|
2023-06-12 16:11:57 +08:00
|
|
|
|
case string:
|
2023-12-26 23:49:43 +08:00
|
|
|
|
return countTokenText(v, model)
|
2023-06-12 16:11:57 +08:00
|
|
|
|
case []string:
|
|
|
|
|
|
text := ""
|
2023-12-26 23:49:43 +08:00
|
|
|
|
for _, s := range v {
|
2023-06-12 16:11:57 +08:00
|
|
|
|
text += s
|
|
|
|
|
|
}
|
|
|
|
|
|
return countTokenText(text, model)
|
|
|
|
|
|
}
|
|
|
|
|
|
return 0
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-11-15 21:05:14 +08:00
|
|
|
|
func countAudioToken(text string, model string) int {
|
|
|
|
|
|
if strings.HasPrefix(model, "tts") {
|
|
|
|
|
|
return utf8.RuneCountInString(text)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return countTokenText(text, model)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2023-05-19 09:41:26 +08:00
|
|
|
|
func countTokenText(text string, model string) int {
|
|
|
|
|
|
tokenEncoder := getTokenEncoder(model)
|
2023-07-04 19:54:13 +08:00
|
|
|
|
return getTokenNum(tokenEncoder, text)
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
2023-06-19 10:28:55 +08:00
|
|
|
|
|
|
|
|
|
|
func errorWrapper(err error, code string, statusCode int) *OpenAIErrorWithStatusCode {
|
2023-09-27 01:02:45 +08:00
|
|
|
|
text := err.Error()
|
|
|
|
|
|
// 定义一个正则表达式匹配URL
|
2023-11-11 01:55:19 +08:00
|
|
|
|
if strings.Contains(text, "Post") {
|
2023-12-01 01:29:13 +08:00
|
|
|
|
common.SysLog(fmt.Sprintf("error: %s", text))
|
2023-11-11 01:55:19 +08:00
|
|
|
|
text = "请求上游地址失败"
|
2023-09-15 17:50:54 +08:00
|
|
|
|
}
|
2023-09-27 01:02:45 +08:00
|
|
|
|
//避免暴露内部错误
|
|
|
|
|
|
|
2023-06-19 10:28:55 +08:00
|
|
|
|
openAIError := OpenAIError{
|
2023-09-27 01:02:45 +08:00
|
|
|
|
Message: text,
|
2023-12-01 01:29:13 +08:00
|
|
|
|
Type: "new_api_error",
|
2023-06-19 10:28:55 +08:00
|
|
|
|
Code: code,
|
|
|
|
|
|
}
|
|
|
|
|
|
return &OpenAIErrorWithStatusCode{
|
|
|
|
|
|
OpenAIError: openAIError,
|
|
|
|
|
|
StatusCode: statusCode,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2023-07-22 18:15:30 +08:00
|
|
|
|
|
2023-08-26 12:05:18 +08:00
|
|
|
|
func shouldDisableChannel(err *OpenAIError, statusCode int) bool {
|
2023-07-22 18:15:30 +08:00
|
|
|
|
if !common.AutomaticDisableChannelEnabled {
|
|
|
|
|
|
return false
|
|
|
|
|
|
}
|
|
|
|
|
|
if err == nil {
|
|
|
|
|
|
return false
|
|
|
|
|
|
}
|
2023-10-10 11:18:29 +08:00
|
|
|
|
if statusCode == http.StatusUnauthorized {
|
2023-08-26 12:05:18 +08:00
|
|
|
|
return true
|
|
|
|
|
|
}
|
2023-12-05 17:11:37 +08:00
|
|
|
|
if err.Type == "insufficient_quota" || err.Code == "invalid_api_key" || err.Code == "account_deactivated" || err.Code == "billing_not_active" {
|
2023-07-22 18:15:30 +08:00
|
|
|
|
return true
|
|
|
|
|
|
}
|
|
|
|
|
|
return false
|
|
|
|
|
|
}
|
2023-08-12 21:55:18 +08:00
|
|
|
|
|
|
|
|
|
|
func setEventStreamHeaders(c *gin.Context) {
|
|
|
|
|
|
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.Writer.Header().Set("X-Accel-Buffering", "no")
|
|
|
|
|
|
}
|
2023-08-26 12:37:45 +08:00
|
|
|
|
|
|
|
|
|
|
func relayErrorHandler(resp *http.Response) (openAIErrorWithStatusCode *OpenAIErrorWithStatusCode) {
|
|
|
|
|
|
openAIErrorWithStatusCode = &OpenAIErrorWithStatusCode{
|
|
|
|
|
|
StatusCode: resp.StatusCode,
|
|
|
|
|
|
OpenAIError: OpenAIError{
|
|
|
|
|
|
Message: fmt.Sprintf("bad response status code %d", resp.StatusCode),
|
2023-09-17 11:30:20 +08:00
|
|
|
|
Type: "upstream_error",
|
2023-08-26 12:37:45 +08:00
|
|
|
|
Code: "bad_response_status_code",
|
|
|
|
|
|
Param: strconv.Itoa(resp.StatusCode),
|
|
|
|
|
|
},
|
|
|
|
|
|
}
|
|
|
|
|
|
responseBody, err := io.ReadAll(resp.Body)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
err = resp.Body.Close()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
var textResponse TextResponse
|
|
|
|
|
|
err = json.Unmarshal(responseBody, &textResponse)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
openAIErrorWithStatusCode.OpenAIError = textResponse.Error
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
2023-10-22 17:50:52 +08:00
|
|
|
|
|
|
|
|
|
|
func getFullRequestURL(baseURL string, requestURL string, channelType int) string {
|
|
|
|
|
|
fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
|
|
|
|
|
|
if channelType == common.ChannelTypeOpenAI {
|
|
|
|
|
|
if strings.HasPrefix(baseURL, "https://gateway.ai.cloudflare.com") {
|
|
|
|
|
|
fullRequestURL = fmt.Sprintf("%s%s", baseURL, strings.TrimPrefix(requestURL, "/v1"))
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return fullRequestURL
|
|
|
|
|
|
}
|
2024-01-09 15:46:45 +08:00
|
|
|
|
|
|
|
|
|
|
func GetAPIVersion(c *gin.Context) string {
|
|
|
|
|
|
query := c.Request.URL.Query()
|
|
|
|
|
|
apiVersion := query.Get("api-version")
|
|
|
|
|
|
if apiVersion == "" {
|
|
|
|
|
|
apiVersion = c.GetString("api_version")
|
|
|
|
|
|
}
|
|
|
|
|
|
return apiVersion
|
|
|
|
|
|
}
|