MCPcopy Create free account
hub / github.com/Zoo-Code-Org/Zoo-Code / countTokens

Function countTokens

src/utils/countTokens.ts:13–45  ·  view source on GitHub ↗
(
	content: Anthropic.Messages.ContentBlockParam[],
	{ useWorker = true }: CountTokensOptions = {},
)

Source from the content-addressed store, hash-verified

11}
12
13export 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}

Callers 2

countTokensFunction · 0.90
processBufferFunction · 0.90

Calls 3

tiktokenFunction · 0.90
parseMethod · 0.80
errorMethod · 0.65

Tested by

no test coverage detected