(text: string)
| 6 | const TOKEN_COUNT_CACHE = new LRUCache<string, number>(1000) |
| 7 | |
| 8 | export 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 | |
| 30 | export function countTokensJson(text: string | object): number { |
| 31 | return countTokens(JSON.stringify(text)) |
no test coverage detected