2024-02-29 01:08:18 +08:00
|
|
|
|
package service
|
2023-05-19 09:41:26 +08:00
|
|
|
|
|
|
|
|
|
|
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"
|
2024-05-15 14:18:15 +08:00
|
|
|
|
"github.com/linux-do/tiktoken-go"
|
2023-11-17 20:32:11 +08:00
|
|
|
|
"image"
|
|
|
|
|
|
"log"
|
|
|
|
|
|
"math"
|
2023-05-19 09:41:26 +08:00
|
|
|
|
"one-api/common"
|
2024-02-29 01:08:18 +08:00
|
|
|
|
"one-api/dto"
|
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-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")
|
2024-05-15 16:32:00 +08:00
|
|
|
|
gpt4oTokenEncoder, err := tiktoken.EncodingForModel("gpt-4o")
|
2023-09-29 17:56:11 +08:00
|
|
|
|
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
|
|
|
|
}
|
2024-03-23 17:19:29 +08:00
|
|
|
|
for model, _ := range common.DefaultModelRatio {
|
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") {
|
2024-05-15 16:32:00 +08:00
|
|
|
|
if strings.HasPrefix(model, "gpt-4o") {
|
|
|
|
|
|
tokenEncoderMap[model] = gpt4oTokenEncoder
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tokenEncoderMap[model] = gpt4TokenEncoder
|
|
|
|
|
|
}
|
2023-09-29 17:56:11 +08:00
|
|
|
|
} 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))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-02-29 01:08:18 +08:00
|
|
|
|
func getImageToken(imageUrl *dto.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"))
|
2024-03-08 18:25:57 +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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-04-23 23:01:06 +08:00
|
|
|
|
func CountTokenChatRequest(request dto.GeneralOpenAIRequest, model string, checkSensitive bool) (int, error, bool) {
|
|
|
|
|
|
tkm := 0
|
|
|
|
|
|
msgTokens, err, b := CountTokenMessages(request.Messages, model, checkSensitive)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err, b
|
|
|
|
|
|
}
|
|
|
|
|
|
tkm += msgTokens
|
|
|
|
|
|
if request.Tools != nil {
|
|
|
|
|
|
toolsData, _ := json.Marshal(request.Tools)
|
|
|
|
|
|
var openaiTools []dto.OpenAITools
|
|
|
|
|
|
err := json.Unmarshal(toolsData, &openaiTools)
|
|
|
|
|
|
if err != nil {
|
2024-04-23 23:51:27 +08:00
|
|
|
|
return 0, errors.New(fmt.Sprintf("count_tools_token_fail: %s", err.Error())), false
|
2024-04-23 23:01:06 +08:00
|
|
|
|
}
|
|
|
|
|
|
countStr := ""
|
|
|
|
|
|
for _, tool := range openaiTools {
|
|
|
|
|
|
countStr = tool.Function.Name
|
|
|
|
|
|
if tool.Function.Description != "" {
|
|
|
|
|
|
countStr += tool.Function.Description
|
|
|
|
|
|
}
|
|
|
|
|
|
if tool.Function.Parameters != nil {
|
|
|
|
|
|
countStr += fmt.Sprintf("%v", tool.Function.Parameters)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
toolTokens, err, _ := CountTokenInput(countStr, model, false)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return 0, err, false
|
|
|
|
|
|
}
|
|
|
|
|
|
tkm += 8
|
|
|
|
|
|
tkm += toolTokens
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return tkm, nil, false
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-03-20 20:36:55 +08:00
|
|
|
|
func CountTokenMessages(messages []dto.Message, model string, checkSensitive bool) (int, error, bool) {
|
2023-11-17 18:24:37 +08:00
|
|
|
|
//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)
|
2024-01-31 01:41:38 +08:00
|
|
|
|
if len(message.Content) > 0 {
|
2024-04-23 23:51:27 +08:00
|
|
|
|
if message.IsStringContent() {
|
|
|
|
|
|
stringContent := message.StringContent()
|
|
|
|
|
|
if checkSensitive {
|
|
|
|
|
|
contains, words := SensitiveWordContains(stringContent)
|
|
|
|
|
|
if contains {
|
|
|
|
|
|
err := fmt.Errorf("message contains sensitive words: [%s]", strings.Join(words, ", "))
|
|
|
|
|
|
return 0, err, true
|
2024-01-31 01:41:38 +08:00
|
|
|
|
}
|
2023-11-17 18:24:37 +08:00
|
|
|
|
}
|
2024-04-23 23:51:27 +08:00
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, stringContent)
|
|
|
|
|
|
if message.Name != nil {
|
|
|
|
|
|
tokenNum += tokensPerName
|
|
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, *message.Name)
|
|
|
|
|
|
}
|
2024-01-31 01:41:38 +08:00
|
|
|
|
} else {
|
2024-04-23 23:51:27 +08:00
|
|
|
|
var err error
|
|
|
|
|
|
arrayContent := message.ParseContent()
|
2024-01-31 01:41:38 +08:00
|
|
|
|
for _, m := range arrayContent {
|
|
|
|
|
|
if m.Type == "image_url" {
|
|
|
|
|
|
var imageTokenNum int
|
2024-02-29 18:31:03 +08:00
|
|
|
|
if model == "glm-4v" {
|
|
|
|
|
|
imageTokenNum = 1047
|
2023-12-18 23:44:47 +08:00
|
|
|
|
} else {
|
2024-04-24 14:44:24 +08:00
|
|
|
|
imageUrl := m.ImageUrl.(dto.MessageImageUrl)
|
|
|
|
|
|
imageTokenNum, err = getImageToken(&imageUrl)
|
2024-02-29 18:31:03 +08:00
|
|
|
|
if err != nil {
|
2024-03-20 20:36:55 +08:00
|
|
|
|
return 0, err, false
|
2024-01-31 01:41:38 +08:00
|
|
|
|
}
|
2023-12-18 23:44:47 +08:00
|
|
|
|
}
|
2024-01-31 01:41:38 +08:00
|
|
|
|
tokenNum += imageTokenNum
|
|
|
|
|
|
log.Printf("image token num: %d", imageTokenNum)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tokenNum += getTokenNum(tokenEncoder, m.Text)
|
|
|
|
|
|
}
|
2023-11-17 18:24:37 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
tokenNum += 3 // Every reply is primed with <|start|>assistant<|message|>
|
2024-03-20 20:36:55 +08:00
|
|
|
|
return tokenNum, nil, false
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2024-03-20 20:36:55 +08:00
|
|
|
|
func CountTokenInput(input any, model string, check bool) (int, error, bool) {
|
2023-12-26 23:49:43 +08:00
|
|
|
|
switch v := input.(type) {
|
2023-06-12 16:11:57 +08:00
|
|
|
|
case string:
|
2024-03-20 17:07:42 +08:00
|
|
|
|
return CountTokenText(v, model, check)
|
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
|
|
|
|
|
|
}
|
2024-03-20 17:07:42 +08:00
|
|
|
|
return CountTokenText(text, model, check)
|
2023-06-12 16:11:57 +08:00
|
|
|
|
}
|
2024-03-26 18:49:53 +08:00
|
|
|
|
return CountTokenInput(fmt.Sprintf("%v", input), model, check)
|
2023-06-12 16:11:57 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2024-04-22 16:35:56 +08:00
|
|
|
|
func CountTokenStreamChoices(messages []dto.ChatCompletionsStreamResponseChoice, model string) int {
|
|
|
|
|
|
tokens := 0
|
|
|
|
|
|
for _, message := range messages {
|
2024-04-26 02:56:35 +08:00
|
|
|
|
tkm, _, _ := CountTokenInput(message.Delta.GetContentString(), model, false)
|
2024-04-22 16:35:56 +08:00
|
|
|
|
tokens += tkm
|
|
|
|
|
|
if message.Delta.ToolCalls != nil {
|
|
|
|
|
|
for _, tool := range message.Delta.ToolCalls {
|
|
|
|
|
|
tkm, _, _ := CountTokenInput(tool.Function.Name, model, false)
|
|
|
|
|
|
tokens += tkm
|
|
|
|
|
|
tkm, _, _ = CountTokenInput(tool.Function.Arguments, model, false)
|
|
|
|
|
|
tokens += tkm
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return tokens
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-03-20 20:36:55 +08:00
|
|
|
|
func CountAudioToken(text string, model string, check bool) (int, error, bool) {
|
2023-11-15 21:05:14 +08:00
|
|
|
|
if strings.HasPrefix(model, "tts") {
|
2024-03-20 20:36:55 +08:00
|
|
|
|
contains, words := SensitiveWordContains(text)
|
|
|
|
|
|
if contains {
|
|
|
|
|
|
return utf8.RuneCountInString(text), fmt.Errorf("input contains sensitive words: [%s]", strings.Join(words, ",")), true
|
|
|
|
|
|
}
|
|
|
|
|
|
return utf8.RuneCountInString(text), nil, false
|
2023-11-15 21:05:14 +08:00
|
|
|
|
} else {
|
2024-03-20 17:07:42 +08:00
|
|
|
|
return CountTokenText(text, model, check)
|
2023-11-15 21:05:14 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-03-20 17:07:42 +08:00
|
|
|
|
// CountTokenText 统计文本的token数量,仅当文本包含敏感词,返回错误,同时返回token数量
|
2024-03-20 20:36:55 +08:00
|
|
|
|
func CountTokenText(text string, model string, check bool) (int, error, bool) {
|
2024-03-20 17:07:42 +08:00
|
|
|
|
var err error
|
2024-03-20 20:36:55 +08:00
|
|
|
|
var trigger bool
|
2024-03-20 17:07:42 +08:00
|
|
|
|
if check {
|
|
|
|
|
|
contains, words := SensitiveWordContains(text)
|
|
|
|
|
|
if contains {
|
|
|
|
|
|
err = fmt.Errorf("input contains sensitive words: [%s]", strings.Join(words, ","))
|
2024-03-20 20:36:55 +08:00
|
|
|
|
trigger = true
|
2024-03-20 17:07:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2023-05-19 09:41:26 +08:00
|
|
|
|
tokenEncoder := getTokenEncoder(model)
|
2024-03-20 20:36:55 +08:00
|
|
|
|
return getTokenNum(tokenEncoder, text), err, trigger
|
2023-05-19 09:41:26 +08:00
|
|
|
|
}
|