* 使用tiktoken进行精准token计数 * @param {string} text - 要计数的文本 * @param {string} model - 模型名称,默认为gpt-3.5-turbo * @returns {number} 精确的token数量
(text, model = 'gpt-3.5-turbo')
| 12 | * @returns {number} 精确的token数量 |
| 13 | */ |
| 14 | function countTokens(text, model = 'gpt-3.5-turbo') { |
| 15 | if (!text || typeof text !== 'string') return 0 |
| 16 | |
| 17 | const encoding = tiktoken.encoding_for_model(model) |
| 18 | const tokens = encoding.encode(text) |
| 19 | encoding.free() // 释放内存 |
| 20 | return tokens.length |
| 21 | } |
| 22 | |
| 23 | |
| 24 |
no outgoing calls
no test coverage detected