(content: Anthropic.Messages.ContentBlockParam[])
| 53 | } |
| 54 | |
| 55 | export async function tiktoken(content: Anthropic.Messages.ContentBlockParam[]): Promise<number> { |
| 56 | if (content.length === 0) { |
| 57 | return 0 |
| 58 | } |
| 59 | |
| 60 | let totalTokens = 0 |
| 61 | |
| 62 | // Lazily create and cache the encoder if it doesn't exist. |
| 63 | if (!encoder) { |
| 64 | encoder = new Tiktoken(o200kBase.bpe_ranks, o200kBase.special_tokens, o200kBase.pat_str) |
| 65 | } |
| 66 | |
| 67 | // Process each content block using the cached encoder. |
| 68 | for (const block of content) { |
| 69 | if (block.type === "text") { |
| 70 | const text = block.text || "" |
| 71 | |
| 72 | if (text.length > 0) { |
| 73 | const tokens = encoder.encode(text, undefined, []) |
| 74 | totalTokens += tokens.length |
| 75 | } |
| 76 | } else if (block.type === "image") { |
| 77 | // For images, calculate based on data size. |
| 78 | const imageSource = block.source |
| 79 | |
| 80 | if (imageSource && typeof imageSource === "object" && "data" in imageSource) { |
| 81 | const base64Data = imageSource.data as string |
| 82 | totalTokens += Math.ceil(Math.sqrt(base64Data.length)) |
| 83 | } else { |
| 84 | totalTokens += 300 // Conservative estimate for unknown images |
| 85 | } |
| 86 | } else if (block.type === "tool_use") { |
| 87 | // Serialize tool_use block to text and count tokens |
| 88 | const serialized = serializeToolUse(block as Anthropic.Messages.ToolUseBlockParam) |
| 89 | if (serialized.length > 0) { |
| 90 | const tokens = encoder.encode(serialized, undefined, []) |
| 91 | totalTokens += tokens.length |
| 92 | } |
| 93 | } else if (block.type === "tool_result") { |
| 94 | // Serialize tool_result block to text and count tokens |
| 95 | const serialized = serializeToolResult(block as Anthropic.Messages.ToolResultBlockParam) |
| 96 | if (serialized.length > 0) { |
| 97 | const tokens = encoder.encode(serialized, undefined, []) |
| 98 | totalTokens += tokens.length |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // Add a fudge factor to account for the fact that tiktoken is not always |
| 104 | // accurate. |
| 105 | return Math.ceil(totalTokens * TOKEN_FUDGE_FACTOR) |
| 106 | } |
no test coverage detected