(
content: Anthropic.Messages.ContentBlockParam[],
{ useWorker = true }: CountTokensOptions = {},
)
| 11 | } |
| 12 | |
| 13 | export async function countTokens( |
| 14 | content: Anthropic.Messages.ContentBlockParam[], |
| 15 | { useWorker = true }: CountTokensOptions = {}, |
| 16 | ): Promise<number> { |
| 17 | // Lazily create the worker pool if it doesn't exist. |
| 18 | if (useWorker && typeof pool === "undefined") { |
| 19 | pool = workerpool.pool(__dirname + "/workers/countTokens.js", { |
| 20 | maxWorkers: 1, |
| 21 | maxQueueSize: 10, |
| 22 | }) |
| 23 | } |
| 24 | |
| 25 | // If the worker pool doesn't exist or the caller doesn't want to use it |
| 26 | // then, use the non-worker implementation. |
| 27 | if (!useWorker || !pool) { |
| 28 | return tiktoken(content) |
| 29 | } |
| 30 | |
| 31 | try { |
| 32 | const data = await pool.exec("countTokens", [content]) |
| 33 | const result = countTokensResultSchema.parse(data) |
| 34 | |
| 35 | if (!result.success) { |
| 36 | throw new Error(result.error) |
| 37 | } |
| 38 | |
| 39 | return result.count |
| 40 | } catch (error) { |
| 41 | pool = null |
| 42 | console.error(error) |
| 43 | return tiktoken(content) |
| 44 | } |
| 45 | } |
no test coverage detected