Popularity js-tiktoken Transformers.js Tokenizers.js gpt-tokenizer tiktoken @anthropic-ai/tokenizer GPT-3-Encoder FAQ Popularity js-tiktoken has the most monthly downloads in this comparison, at 49.4M .
Libraries and code examples Provides a JavaScript port of the tiktoken tokenizer for OpenAI models.
Downloads / mo 49.4M
Stars 1.1K
Last release 1.0.21
License MIT $ npm install js-tiktoken@1.0.21 Copy
import { getEncoding } from "js-tiktoken";
const tokenizer = getEncoding("o200k_base");
console.log(tokenizer.encode("Hello world"));
js-tiktoken examples From open-source projects on GitHub export async function getEncoding(encoding: TiktokenEncoding) {
if (!(encoding in cache)) {
cache[encoding] = caller
.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`)
.then((res) => res.json())
.then((data) => new Tiktoken(data))
.catch((e) => {
delete cache[encoding];
throw e;
});
}
return await cache[encoding];
}
Show full example Loads pretrained model tokenizers and formats model-specific chat prompts.
Downloads / mo 19.1M
Stars 16.4K
Last release 4.3.2
License Apache-2.0 Strengths Loads tokenizers by model ID . AutoTokenizer selects an implementation from tokenizer_config.json. Applies model-specific chat templates . Render roles and control tokens in the model’s prompt format. Limitations Tool formatting depends on templates . Tools have no effect when templates lack function-calling support. Requires pretrained tokenizer files . Loading fails when required tokenizer files are missing. From open-source projects on GitHub
export function renderTextChatTemplate(
tokenizer: TextGenerationPipeline["tokenizer"],
messages: readonly { role: string; content: string }[],
options: TextChatTemplateOptions,
): string {
const source: unknown = tokenizer.get_chat_template();
const chatTemplate = typeof source === "string" ? source.replace(GENERATION_STATEMENT, "") : undefined;
const templateOptions: {
chat_template?: string;
add_generation_prompt: boolean;
tokenize: false;
enable_thinking: boolean;
} = {
...(chatTemplate === undefined ? {} : { chat_template: chatTemplate }),
add_generation_prompt: options.addGenerationPrompt,
tokenize: false,
enable_thinking: options.enableThinking,
};
return tokenizer.apply_chat_template([...messages], templateOptions);
}
Show full example Implements common model tokenizers in pure JavaScript and TypeScript.
Downloads / mo 15.4M
Stars 62
Last release 0.2.0
License Apache-2.0 $ npm install @huggingface/tokenizers@0.2.0 Copy
import { Tokenizer } from "@huggingface/tokenizers";
const base = "https://huggingface.co/HuggingFaceTB/SmolLM3-3B/resolve/main";
const json = await fetch(`${base}/tokenizer.json`).then(response => response.json());
const config = await fetch(`${base}/tokenizer_config.json`).then(response => response.json());
const tokenizer = new Tokenizer(json, config);
console.log(tokenizer.encode("Hello world").ids);
Tokenizers.js examples From open-source projects on GitHub const tokenizeAndTruncate = (tokenizer: HFTokenizer): string => {
const encoded = tokenizer.encode(text);
const rawIds: ArrayLike<number | bigint> = encoded.ids;
const ids = Array.from(rawIds as ArrayLike<number>).map(Number);
if (ids.length <= maxTokens) {
return text;
}
const truncatedIds = ids.slice(0, maxTokens);
return tokenizer.decode(truncatedIds, { skip_special_tokens: true });
};
Show full example Encodes and decodes model text with a pure-JavaScript byte-pair tokenizer.
Downloads / mo 10.6M
Stars 862
Last release 4.1.2
License MIT Strengths Checks budgets before full encoding . Check text or chat limits without encoding the entire input. Updates counts after text edits . Track appended text and edits with an incremental counter. Limitations Reserved tokens require explicit permission . Configure allowedSpecial when reserved token strings should be accepted. Incremental edits can rescan text . Long words or whitespace runs can require rescanning a large region. $ npm install gpt-tokenizer@4.1.2 Copy
import { encode, decode } from "gpt-tokenizer";
const ids = encode("Hello world");
console.log(ids, decode(ids));
gpt-tokenizer examples From open-source projects on GitHub function countToolCallFunctionTokens(
toolCallFunction: { name?: string; arguments?: string } | undefined,
): number {
if (!toolCallFunction) {
return 0;
}
let tokenCount = 0;
tokenCount += encode(toolCallFunction.name ?? "").length + 10; // Function name and structure overhead
tokenCount += encode(toolCallFunction.arguments ?? "").length; // Arguments
return tokenCount;
}
Show full example Provides JavaScript and WASM bindings to OpenAI-model byte-pair tokenizers.
Downloads / mo 8.7M
Stars 1.1K
Last release 1.0.22
License MIT Strengths Maps models to their encodings . Resolve a model tokenizer with encoding_for_model. Loads individual encoding tables . Use tiktoken/lite to avoid loading every encoder at once. Limitations Encoders need explicit cleanup . Call free() when an encoder is no longer needed. Vite requires extra build plugins . Add WASM and top-level-await plugins when bundling with Vite. $ npm install tiktoken@1.0.22 Copy
import { get_encoding } from "tiktoken";
const tokenizer = get_encoding("o200k_base");
console.log(tokenizer.encode("Hello world"));
tokenizer.free();
tiktoken examples From open-source projects on GitHub export function textTokensForEncodingId(text: string, encodingId: string, debugFrom: string): Array<UITokenChunk> | null {
// The library shall have been preloaded - if not, attempt to start its loading and return null to indicate we're not ready to count
if (!get_encoding) {
if (!informTheUser) {
console.warn('textTokensForEncodingId: Tiktoken library is not yet loaded, loading now...');
informTheUser = true;
}
void preloadTiktokenLibrary().catch(() => {}); // preload without waiting; swallow rejection (already logged, falls back to approximate counting) to avoid an unhandled-rejection report
return null;
}
if (!(encodingId in tokenizerCache)) {
try {
tokenizerCache[encodingId] = get_encoding(encodingId as TiktokenEncoding);
} catch (e) {
console.error(`textTokensForEncodingId: Error initializing tokenizer "${encodingId}": ${e}`);
return null;
}
}
try {
const tokens = tokenizerCache[encodingId]?.encode(text, 'all', []) || new Uint32Array();
if (DEBUG_TOKEN_COUNT)
console.log(`textTokensForEncodingId: ${debugFrom}, ${encodingId}, "${text.slice(0, 10)}": ${tokens.length}`);
// for every token create an object {t:token, b: bytes}
const tokenDetails: UITokenChunk[] = [];
for (let i = 0; i < tokens.length; i++) {
const bytesForToken = tokenizerCache[encodingId].decode_single_token_bytes(tokens[i]);
const stringForToken = String.fromCharCode(...bytesForToken);
tokenDetails.push({
token: tokens[i],
chunk: stringForToken,
bytes: bytesForToken.join(', '),
});
}
return tokenDetails;
} catch (e) {
console.error(`textTokensForEncodingId: Error tokenizing "${text.slice(0, 10)}..." with tokenizer '${encodingId}': ${e}`);
return null;
}
}
Show full example Tokenizes text for Claude models.
Downloads / mo 1.4M
Stars 108
Last release 0.0.4
License Apache-2.0 $ npm install @anthropic-ai/tokenizer@0.0.4 Copy
import { countTokens } from "@anthropic-ai/tokenizer";
console.log(countTokens("Hello world"));
Implements the original GPT-2/GPT-3 text encoder and decoder in JavaScript.
Downloads / mo 640.1K
Stars 722
Last release 1.1.4
License MIT Strengths Fits legacy GPT-2/3 workflows . Encode text and decode token IDs for those model families. Exposes individual decoded token pieces . Decode token IDs separately when inspecting a sequence. Limitations Targets legacy GPT-2/3 encodings . Match the model tokenizer before relying on context-budget estimates. $ npm install gpt-3-encoder@1.1.4 Copy
const { encode, decode } = require("gpt-3-encoder");
const ids = encode("Hello world");
console.log(ids, decode(ids));
GPT-3-Encoder examples From open-source projects on GitHub const chunkEssay = async (essay: PGEssay) => {
const { title, url, date, thanks, content, ...chunklessSection } = essay;
let essayTextChunks = [];
if (encode(content).length > CHUNK_SIZE) {
const split = content.split(". ");
let chunkText = "";
for (let i = 0; i < split.length; i++) {
const sentence = split[i];
const sentenceTokenLength = encode(sentence);
const chunkTextTokenLength = encode(chunkText).length;
if (chunkTextTokenLength + sentenceTokenLength.length > CHUNK_SIZE) {
essayTextChunks.push(chunkText);
chunkText = "";
}
if (sentence[sentence.length - 1].match(/[a-z0-9]/i)) {
chunkText += sentence + ". ";
} else {
chunkText += sentence + " ";
}
}
essayTextChunks.push(chunkText.trim());
} else {
essayTextChunks.push(content.trim());
}
const essayChunks = essayTextChunks.map((text) => {
const trimmedText = text.trim();
const chunk: PGChunk = {
essay_title: title,
essay_url: url,
essay_date: date,
essay_thanks: thanks,
content: trimmedText,
content_length: trimmedText.length,
content_tokens: encode(trimmedText).length,
embedding: []
};
return chunk;
});
if (essayChunks.length > 1) {
for (let i = 0; i < essayChunks.length; i++) {
const chunk = essayChunks[i];
const prevChunk = essayChunks[i - 1];
if (chunk.content_tokens < 100 && prevChunk) {
prevChunk.content += " " + chunk.content;
prevChunk.content_length += chunk.content_length;
prevChunk.content_tokens += chunk.content_tokens;
essayChunks.splice(i, 1);
i--;
}
}
}
const chunkedSection: PGEssay = {
...essay,
chunks: essayChunks
};
return chunkedSection;
};
Show full example For coding agents
Found your tokenizer library? Help your agent use it. Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.
Claude Code Cursor Codex VS Code Devin Devin Desktop Gemini CLI OpenCode
Run in your terminal
claude plugin install exa@claude-plugins-official Copy Add to ~/.cursor/mcp.json
{
"mcpServers": {
"exa": {
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy Open in your browser, then install the Exa plugin
https://chatgpt.com/plugins/exa Copy Add to .vscode/mcp.json
{
"servers": {
"exa": {
"type": "http",
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy In Devin, open Customize, then MCPs, and add a custom HTTP server with this URL
https://mcp.exa.ai/mcp Copy Add to ~/.config/devin/mcp_config.json
{
"mcpServers": {
"exa": {
"serverUrl": "https://mcp.exa.ai/mcp"
}
}
} Copy Add to ~/.gemini/settings.json
{
"mcpServers": {
"exa": {
"httpUrl": "https://mcp.exa.ai/mcp"
}
}
} Copy Add to opencode.json
{
"mcp": {
"exa": {
"type": "remote",
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy