(text: string | null | undefined)
| 90 | * heuristic. Never throws. |
| 91 | */ |
| 92 | export function countTokens(text: string | null | undefined): number { |
| 93 | if (!text) return 0; |
| 94 | if (encoder) { |
| 95 | try { |
| 96 | return encoder(text).length; |
| 97 | } catch (err) { |
| 98 | if (!warnedEncoderFailed) { |
| 99 | warnedEncoderFailed = true; |
| 100 | logger.debug('tokenizer encoder failed; falling back to heuristic', { err }); |
| 101 | } |
| 102 | /* fall through */ |
| 103 | } |
| 104 | } |
| 105 | return heuristicTokens(text); |
| 106 | } |
| 107 | |
| 108 | /** Count tokens for an arbitrary JSON-serializable value (tool args, etc.). */ |
| 109 | export function countTokensJson(value: unknown): number { |
no test coverage detected