token_counter.go 19 KB

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