token_counter.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "image"
  7. _ "image/gif"
  8. _ "image/jpeg"
  9. _ "image/png"
  10. "log"
  11. "math"
  12. "strings"
  13. "sync"
  14. "unicode/utf8"
  15. "github.com/QuantumNous/new-api/common"
  16. "github.com/QuantumNous/new-api/constant"
  17. "github.com/QuantumNous/new-api/dto"
  18. relaycommon "github.com/QuantumNous/new-api/relay/common"
  19. "github.com/QuantumNous/new-api/types"
  20. "github.com/gin-gonic/gin"
  21. "github.com/tiktoken-go/tokenizer"
  22. "github.com/tiktoken-go/tokenizer/codec"
  23. )
  24. // tokenEncoderMap won't grow after initialization
  25. var defaultTokenEncoder tokenizer.Codec
  26. // tokenEncoderMap is used to store token encoders for different models
  27. var tokenEncoderMap = make(map[string]tokenizer.Codec)
  28. // tokenEncoderMutex protects tokenEncoderMap for concurrent access
  29. var tokenEncoderMutex sync.RWMutex
  30. func InitTokenEncoders() {
  31. common.SysLog("initializing token encoders")
  32. defaultTokenEncoder = codec.NewCl100kBase()
  33. common.SysLog("token encoders initialized")
  34. }
  35. func getTokenEncoder(model string) tokenizer.Codec {
  36. // First, try to get the encoder from cache with read lock
  37. tokenEncoderMutex.RLock()
  38. if encoder, exists := tokenEncoderMap[model]; exists {
  39. tokenEncoderMutex.RUnlock()
  40. return encoder
  41. }
  42. tokenEncoderMutex.RUnlock()
  43. // If not in cache, create new encoder with write lock
  44. tokenEncoderMutex.Lock()
  45. defer tokenEncoderMutex.Unlock()
  46. // Double-check if another goroutine already created the encoder
  47. if encoder, exists := tokenEncoderMap[model]; exists {
  48. return encoder
  49. }
  50. // Create new encoder
  51. modelCodec, err := tokenizer.ForModel(tokenizer.Model(model))
  52. if err != nil {
  53. // Cache the default encoder for this model to avoid repeated failures
  54. tokenEncoderMap[model] = defaultTokenEncoder
  55. return defaultTokenEncoder
  56. }
  57. // Cache the new encoder
  58. tokenEncoderMap[model] = modelCodec
  59. return modelCodec
  60. }
  61. func getTokenNum(tokenEncoder tokenizer.Codec, text string) int {
  62. if text == "" {
  63. return 0
  64. }
  65. tkm, _ := tokenEncoder.Count(text)
  66. return tkm
  67. }
  68. func getImageToken(fileMeta *types.FileMeta, model string, stream bool) (int, error) {
  69. if fileMeta == nil {
  70. return 0, fmt.Errorf("image_url_is_nil")
  71. }
  72. // Defaults for 4o/4.1/4.5 family unless overridden below
  73. baseTokens := 85
  74. tileTokens := 170
  75. // Model classification
  76. lowerModel := strings.ToLower(model)
  77. // Special cases from existing behavior
  78. if strings.HasPrefix(lowerModel, "glm-4") {
  79. return 1047, nil
  80. }
  81. // Patch-based models (32x32 patches, capped at 1536, with multiplier)
  82. isPatchBased := false
  83. multiplier := 1.0
  84. switch {
  85. case strings.Contains(lowerModel, "gpt-4.1-mini"):
  86. isPatchBased = true
  87. multiplier = 1.62
  88. case strings.Contains(lowerModel, "gpt-4.1-nano"):
  89. isPatchBased = true
  90. multiplier = 2.46
  91. case strings.HasPrefix(lowerModel, "o4-mini"):
  92. isPatchBased = true
  93. multiplier = 1.72
  94. case strings.HasPrefix(lowerModel, "gpt-5-mini"):
  95. isPatchBased = true
  96. multiplier = 1.62
  97. case strings.HasPrefix(lowerModel, "gpt-5-nano"):
  98. isPatchBased = true
  99. multiplier = 2.46
  100. }
  101. // Tile-based model tokens and bases per doc
  102. if !isPatchBased {
  103. if strings.HasPrefix(lowerModel, "gpt-4o-mini") {
  104. baseTokens = 2833
  105. tileTokens = 5667
  106. } else if strings.HasPrefix(lowerModel, "gpt-5-chat-latest") || (strings.HasPrefix(lowerModel, "gpt-5") && !strings.Contains(lowerModel, "mini") && !strings.Contains(lowerModel, "nano")) {
  107. baseTokens = 70
  108. tileTokens = 140
  109. } else if strings.HasPrefix(lowerModel, "o1") || strings.HasPrefix(lowerModel, "o3") || strings.HasPrefix(lowerModel, "o1-pro") {
  110. baseTokens = 75
  111. tileTokens = 150
  112. } else if strings.Contains(lowerModel, "computer-use-preview") {
  113. baseTokens = 65
  114. tileTokens = 129
  115. } else if strings.Contains(lowerModel, "4.1") || strings.Contains(lowerModel, "4o") || strings.Contains(lowerModel, "4.5") {
  116. baseTokens = 85
  117. tileTokens = 170
  118. }
  119. }
  120. // Respect existing feature flags/short-circuits
  121. if fileMeta.Detail == "low" && !isPatchBased {
  122. return baseTokens, nil
  123. }
  124. if !constant.GetMediaTokenNotStream && !stream {
  125. return 3 * baseTokens, nil
  126. }
  127. // Normalize detail
  128. if fileMeta.Detail == "auto" || fileMeta.Detail == "" {
  129. fileMeta.Detail = "high"
  130. }
  131. // Whether to count image tokens at all
  132. if !constant.GetMediaToken {
  133. return 3 * baseTokens, nil
  134. }
  135. // Decode image to get dimensions
  136. var config image.Config
  137. var err error
  138. var format string
  139. var b64str string
  140. if fileMeta.ParsedData != nil {
  141. config, format, b64str, err = DecodeBase64ImageData(fileMeta.ParsedData.Base64Data)
  142. } else {
  143. if strings.HasPrefix(fileMeta.OriginData, "http") {
  144. config, format, err = DecodeUrlImageData(fileMeta.OriginData)
  145. } else {
  146. common.SysLog(fmt.Sprintf("decoding image"))
  147. config, format, b64str, err = DecodeBase64ImageData(fileMeta.OriginData)
  148. }
  149. fileMeta.MimeType = format
  150. }
  151. if err != nil {
  152. return 0, err
  153. }
  154. if config.Width == 0 || config.Height == 0 {
  155. // not an image
  156. if format != "" && b64str != "" {
  157. // file type
  158. return 3 * baseTokens, nil
  159. }
  160. return 0, errors.New(fmt.Sprintf("fail to decode base64 config: %s", fileMeta.OriginData))
  161. }
  162. width := config.Width
  163. height := config.Height
  164. log.Printf("format: %s, width: %d, height: %d", format, width, height)
  165. if isPatchBased {
  166. // 32x32 patch-based calculation with 1536 cap and model multiplier
  167. ceilDiv := func(a, b int) int { return (a + b - 1) / b }
  168. rawPatchesW := ceilDiv(width, 32)
  169. rawPatchesH := ceilDiv(height, 32)
  170. rawPatches := rawPatchesW * rawPatchesH
  171. if rawPatches > 1536 {
  172. // scale down
  173. area := float64(width * height)
  174. r := math.Sqrt(float64(32*32*1536) / area)
  175. wScaled := float64(width) * r
  176. hScaled := float64(height) * r
  177. // adjust to fit whole number of patches after scaling
  178. adjW := math.Floor(wScaled/32.0) / (wScaled / 32.0)
  179. adjH := math.Floor(hScaled/32.0) / (hScaled / 32.0)
  180. adj := math.Min(adjW, adjH)
  181. if !math.IsNaN(adj) && adj > 0 {
  182. r = r * adj
  183. }
  184. wScaled = float64(width) * r
  185. hScaled = float64(height) * r
  186. patchesW := math.Ceil(wScaled / 32.0)
  187. patchesH := math.Ceil(hScaled / 32.0)
  188. imageTokens := int(patchesW * patchesH)
  189. if imageTokens > 1536 {
  190. imageTokens = 1536
  191. }
  192. return int(math.Round(float64(imageTokens) * multiplier)), nil
  193. }
  194. // below cap
  195. imageTokens := rawPatches
  196. return int(math.Round(float64(imageTokens) * multiplier)), nil
  197. }
  198. // Tile-based calculation for 4o/4.1/4.5/o1/o3/etc.
  199. // Step 1: fit within 2048x2048 square
  200. maxSide := math.Max(float64(width), float64(height))
  201. fitScale := 1.0
  202. if maxSide > 2048 {
  203. fitScale = maxSide / 2048.0
  204. }
  205. fitW := int(math.Round(float64(width) / fitScale))
  206. fitH := int(math.Round(float64(height) / fitScale))
  207. // Step 2: scale so that shortest side is exactly 768
  208. minSide := math.Min(float64(fitW), float64(fitH))
  209. if minSide == 0 {
  210. return baseTokens, nil
  211. }
  212. shortScale := 768.0 / minSide
  213. finalW := int(math.Round(float64(fitW) * shortScale))
  214. finalH := int(math.Round(float64(fitH) * shortScale))
  215. // Count 512px tiles
  216. tilesW := (finalW + 512 - 1) / 512
  217. tilesH := (finalH + 512 - 1) / 512
  218. tiles := tilesW * tilesH
  219. if common.DebugEnabled {
  220. log.Printf("scaled to: %dx%d, tiles: %d", finalW, finalH, tiles)
  221. }
  222. return tiles*tileTokens + baseTokens, nil
  223. }
  224. func CountRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *relaycommon.RelayInfo) (int, error) {
  225. if !constant.GetMediaToken {
  226. return 0, nil
  227. }
  228. if !constant.GetMediaTokenNotStream && !info.IsStream {
  229. return 0, nil
  230. }
  231. if info.RelayFormat == types.RelayFormatOpenAIRealtime {
  232. return 0, nil
  233. }
  234. if meta == nil {
  235. return 0, errors.New("token count meta is nil")
  236. }
  237. model := common.GetContextKeyString(c, constant.ContextKeyOriginalModel)
  238. tkm := 0
  239. if meta.TokenType == types.TokenTypeTextNumber {
  240. tkm += utf8.RuneCountInString(meta.CombineText)
  241. } else {
  242. tkm += CountTextToken(meta.CombineText, model)
  243. }
  244. if info.RelayFormat == types.RelayFormatOpenAI {
  245. tkm += meta.ToolsCount * 8
  246. tkm += meta.MessagesCount * 3 // 每条消息的格式化token数量
  247. tkm += meta.NameCount * 3
  248. tkm += 3
  249. }
  250. shouldFetchFiles := true
  251. if info.RelayFormat == types.RelayFormatGemini {
  252. shouldFetchFiles = false
  253. }
  254. if shouldFetchFiles {
  255. for _, file := range meta.Files {
  256. if strings.HasPrefix(file.OriginData, "http") {
  257. mineType, err := GetFileTypeFromUrl(c, file.OriginData, "token_counter")
  258. if err != nil {
  259. return 0, fmt.Errorf("error getting file base64 from url: %v", err)
  260. }
  261. if strings.HasPrefix(mineType, "image/") {
  262. file.FileType = types.FileTypeImage
  263. } else if strings.HasPrefix(mineType, "video/") {
  264. file.FileType = types.FileTypeVideo
  265. } else if strings.HasPrefix(mineType, "audio/") {
  266. file.FileType = types.FileTypeAudio
  267. } else {
  268. file.FileType = types.FileTypeFile
  269. }
  270. file.MimeType = mineType
  271. } else if strings.HasPrefix(file.OriginData, "data:") {
  272. // get mime type from base64 header
  273. parts := strings.SplitN(file.OriginData, ",", 2)
  274. if len(parts) >= 1 {
  275. header := parts[0]
  276. // Extract mime type from "data:mime/type;base64" format
  277. if strings.Contains(header, ":") && strings.Contains(header, ";") {
  278. mimeStart := strings.Index(header, ":") + 1
  279. mimeEnd := strings.Index(header, ";")
  280. if mimeStart < mimeEnd {
  281. mineType := header[mimeStart:mimeEnd]
  282. if strings.HasPrefix(mineType, "image/") {
  283. file.FileType = types.FileTypeImage
  284. } else if strings.HasPrefix(mineType, "video/") {
  285. file.FileType = types.FileTypeVideo
  286. } else if strings.HasPrefix(mineType, "audio/") {
  287. file.FileType = types.FileTypeAudio
  288. } else {
  289. file.FileType = types.FileTypeFile
  290. }
  291. file.MimeType = mineType
  292. }
  293. }
  294. }
  295. }
  296. }
  297. }
  298. for i, file := range meta.Files {
  299. switch file.FileType {
  300. case types.FileTypeImage:
  301. if info.RelayFormat == types.RelayFormatGemini {
  302. tkm += 256
  303. } else {
  304. token, err := getImageToken(file, model, info.IsStream)
  305. if err != nil {
  306. return 0, fmt.Errorf("error counting image token, media index[%d], original data[%s], err: %v", i, file.OriginData, err)
  307. }
  308. tkm += token
  309. }
  310. case types.FileTypeAudio:
  311. tkm += 256
  312. case types.FileTypeVideo:
  313. tkm += 4096 * 2
  314. case types.FileTypeFile:
  315. tkm += 4096
  316. default:
  317. tkm += 4096 // Default case for unknown file types
  318. }
  319. }
  320. common.SetContextKey(c, constant.ContextKeyPromptTokens, tkm)
  321. return tkm, nil
  322. }
  323. func CountTokenClaudeRequest(request dto.ClaudeRequest, model string) (int, error) {
  324. tkm := 0
  325. // Count tokens in messages
  326. msgTokens, err := CountTokenClaudeMessages(request.Messages, model, request.Stream)
  327. if err != nil {
  328. return 0, err
  329. }
  330. tkm += msgTokens
  331. // Count tokens in system message
  332. if request.System != "" {
  333. systemTokens := CountTokenInput(request.System, model)
  334. tkm += systemTokens
  335. }
  336. if request.Tools != nil {
  337. // check is array
  338. if tools, ok := request.Tools.([]any); ok {
  339. if len(tools) > 0 {
  340. parsedTools, err1 := common.Any2Type[[]dto.Tool](request.Tools)
  341. if err1 != nil {
  342. return 0, fmt.Errorf("tools: Input should be a valid list: %v", err)
  343. }
  344. toolTokens, err2 := CountTokenClaudeTools(parsedTools, model)
  345. if err2 != nil {
  346. return 0, fmt.Errorf("tools: %v", err)
  347. }
  348. tkm += toolTokens
  349. }
  350. } else {
  351. return 0, errors.New("tools: Input should be a valid list")
  352. }
  353. }
  354. return tkm, nil
  355. }
  356. func CountTokenClaudeMessages(messages []dto.ClaudeMessage, model string, stream bool) (int, error) {
  357. tokenEncoder := getTokenEncoder(model)
  358. tokenNum := 0
  359. for _, message := range messages {
  360. // Count tokens for role
  361. tokenNum += getTokenNum(tokenEncoder, message.Role)
  362. if message.IsStringContent() {
  363. tokenNum += getTokenNum(tokenEncoder, message.GetStringContent())
  364. } else {
  365. content, err := message.ParseContent()
  366. if err != nil {
  367. return 0, err
  368. }
  369. for _, mediaMessage := range content {
  370. switch mediaMessage.Type {
  371. case "text":
  372. tokenNum += getTokenNum(tokenEncoder, mediaMessage.GetText())
  373. case "image":
  374. //imageTokenNum, err := getClaudeImageToken(mediaMsg.Source, model, stream)
  375. //if err != nil {
  376. // return 0, err
  377. //}
  378. tokenNum += 1000
  379. case "tool_use":
  380. if mediaMessage.Input != nil {
  381. tokenNum += getTokenNum(tokenEncoder, mediaMessage.Name)
  382. inputJSON, _ := json.Marshal(mediaMessage.Input)
  383. tokenNum += getTokenNum(tokenEncoder, string(inputJSON))
  384. }
  385. case "tool_result":
  386. if mediaMessage.Content != nil {
  387. contentJSON, _ := json.Marshal(mediaMessage.Content)
  388. tokenNum += getTokenNum(tokenEncoder, string(contentJSON))
  389. }
  390. }
  391. }
  392. }
  393. }
  394. // Add a constant for message formatting (this may need adjustment based on Claude's exact formatting)
  395. tokenNum += len(messages) * 2 // Assuming 2 tokens per message for formatting
  396. return tokenNum, nil
  397. }
  398. func CountTokenClaudeTools(tools []dto.Tool, model string) (int, error) {
  399. tokenEncoder := getTokenEncoder(model)
  400. tokenNum := 0
  401. for _, tool := range tools {
  402. tokenNum += getTokenNum(tokenEncoder, tool.Name)
  403. tokenNum += getTokenNum(tokenEncoder, tool.Description)
  404. schemaJSON, err := json.Marshal(tool.InputSchema)
  405. if err != nil {
  406. return 0, errors.New(fmt.Sprintf("marshal_tool_schema_fail: %s", err.Error()))
  407. }
  408. tokenNum += getTokenNum(tokenEncoder, string(schemaJSON))
  409. }
  410. // Add a constant for tool formatting (this may need adjustment based on Claude's exact formatting)
  411. tokenNum += len(tools) * 3 // Assuming 3 tokens per tool for formatting
  412. return tokenNum, nil
  413. }
  414. func CountTokenRealtime(info *relaycommon.RelayInfo, request dto.RealtimeEvent, model string) (int, int, error) {
  415. audioToken := 0
  416. textToken := 0
  417. switch request.Type {
  418. case dto.RealtimeEventTypeSessionUpdate:
  419. if request.Session != nil {
  420. msgTokens := CountTextToken(request.Session.Instructions, model)
  421. textToken += msgTokens
  422. }
  423. case dto.RealtimeEventResponseAudioDelta:
  424. // count audio token
  425. atk, err := CountAudioTokenOutput(request.Delta, info.OutputAudioFormat)
  426. if err != nil {
  427. return 0, 0, fmt.Errorf("error counting audio token: %v", err)
  428. }
  429. audioToken += atk
  430. case dto.RealtimeEventResponseAudioTranscriptionDelta, dto.RealtimeEventResponseFunctionCallArgumentsDelta:
  431. // count text token
  432. tkm := CountTextToken(request.Delta, model)
  433. textToken += tkm
  434. case dto.RealtimeEventInputAudioBufferAppend:
  435. // count audio token
  436. atk, err := CountAudioTokenInput(request.Audio, info.InputAudioFormat)
  437. if err != nil {
  438. return 0, 0, fmt.Errorf("error counting audio token: %v", err)
  439. }
  440. audioToken += atk
  441. case dto.RealtimeEventConversationItemCreated:
  442. if request.Item != nil {
  443. switch request.Item.Type {
  444. case "message":
  445. for _, content := range request.Item.Content {
  446. if content.Type == "input_text" {
  447. tokens := CountTextToken(content.Text, model)
  448. textToken += tokens
  449. }
  450. }
  451. }
  452. }
  453. case dto.RealtimeEventTypeResponseDone:
  454. // count tools token
  455. if !info.IsFirstRequest {
  456. if info.RealtimeTools != nil && len(info.RealtimeTools) > 0 {
  457. for _, tool := range info.RealtimeTools {
  458. toolTokens := CountTokenInput(tool, model)
  459. textToken += 8
  460. textToken += toolTokens
  461. }
  462. }
  463. }
  464. }
  465. return textToken, audioToken, nil
  466. }
  467. func CountTokenInput(input any, model string) int {
  468. switch v := input.(type) {
  469. case string:
  470. return CountTextToken(v, model)
  471. case []string:
  472. text := ""
  473. for _, s := range v {
  474. text += s
  475. }
  476. return CountTextToken(text, model)
  477. case []interface{}:
  478. text := ""
  479. for _, item := range v {
  480. text += fmt.Sprintf("%v", item)
  481. }
  482. return CountTextToken(text, model)
  483. }
  484. return CountTokenInput(fmt.Sprintf("%v", input), model)
  485. }
  486. func CountTokenStreamChoices(messages []dto.ChatCompletionsStreamResponseChoice, model string) int {
  487. tokens := 0
  488. for _, message := range messages {
  489. tkm := CountTokenInput(message.Delta.GetContentString(), model)
  490. tokens += tkm
  491. if message.Delta.ToolCalls != nil {
  492. for _, tool := range message.Delta.ToolCalls {
  493. tkm := CountTokenInput(tool.Function.Name, model)
  494. tokens += tkm
  495. tkm = CountTokenInput(tool.Function.Arguments, model)
  496. tokens += tkm
  497. }
  498. }
  499. }
  500. return tokens
  501. }
  502. func CountTTSToken(text string, model string) int {
  503. if strings.HasPrefix(model, "tts") {
  504. return utf8.RuneCountInString(text)
  505. } else {
  506. return CountTextToken(text, model)
  507. }
  508. }
  509. func CountAudioTokenInput(audioBase64 string, audioFormat string) (int, error) {
  510. if audioBase64 == "" {
  511. return 0, nil
  512. }
  513. duration, err := parseAudio(audioBase64, audioFormat)
  514. if err != nil {
  515. return 0, err
  516. }
  517. return int(duration / 60 * 100 / 0.06), nil
  518. }
  519. func CountAudioTokenOutput(audioBase64 string, audioFormat string) (int, error) {
  520. if audioBase64 == "" {
  521. return 0, nil
  522. }
  523. duration, err := parseAudio(audioBase64, audioFormat)
  524. if err != nil {
  525. return 0, err
  526. }
  527. return int(duration / 60 * 200 / 0.24), nil
  528. }
  529. //func CountAudioToken(sec float64, audioType string) {
  530. // if audioType == "input" {
  531. //
  532. // }
  533. //}
  534. // CountTextToken 统计文本的token数量,仅当文本包含敏感词,返回错误,同时返回token数量
  535. func CountTextToken(text string, model string) int {
  536. if text == "" {
  537. return 0
  538. }
  539. tokenEncoder := getTokenEncoder(model)
  540. return getTokenNum(tokenEncoder, text)
  541. }