MCPcopy Index your code
hub / github.com/CodebuffAI/codebuff / countTokens

Function countTokens

packages/agent-runtime/src/util/token-counter.ts:8–28  ·  view source on GitHub ↗
(text: string)

Source from the content-addressed store, hash-verified

6const TOKEN_COUNT_CACHE = new LRUCache<string, number>(1000)
7
8export function countTokens(text: string): number {
9 try {
10 const cached = TOKEN_COUNT_CACHE.get(text)
11 if (cached !== undefined) {
12 return cached
13 }
14 const count = Math.floor(
15 encode(text, { allowedSpecial: 'all' }).length *
16 ANTHROPIC_TOKEN_FUDGE_FACTOR,
17 )
18
19 if (text.length > 100) {
20 // Cache only if the text is long enough to be worth it.
21 TOKEN_COUNT_CACHE.set(text, count)
22 }
23 return count
24 } catch (e) {
25 console.error('Error counting tokens', e)
26 return Math.ceil(text.length / 3)
27 }
28}
29
30export function countTokensJson(text: string | object): number {
31 return countTokens(JSON.stringify(text))

Callers 5

getSearchSystemPromptFunction · 0.90
countTokensJsonFunction · 0.85
countTokensForFilesFunction · 0.85

Calls 2

setMethod · 0.80
getMethod · 0.65

Tested by

no test coverage detected