openai-gpt-token-counter
Version:
Count the number of OpenAI tokens in a string. Supports all OpenAI Text models including GPT-5, GPT-4, GPT-3.5-turbo, and specialized models
50 lines (40 loc) • 1.94 kB
JavaScript
/**
* Count tokens in chat messages
* @param {Array<{role: string, content: string, name?: string}>} messages - Array of chat messages
* @param {string} model - Model name (e.g., "gpt-5", "gpt-5-mini", "gpt-5-nano")
* @returns {number} Number of tokens
*/
const tiktoken = require("tiktoken");
const encoding_for_model = tiktoken.encoding_for_model;
const encoder_cache = {};
function getChatGPTEncoding(messages = [], model = "gpt-3.5-turbo") {
if(!Array.isArray(messages)) throw new Error('Please pass an array of messages in valid format to the chat function. Refer to the documentation for help ( https://www.npmjs.com/package/openai-gpt-token-counter )');
const isGpt3 = model.startsWith("gpt-3.5");
let encoder = encoder_cache[model];
if (!encoder) {
encoder = encoding_for_model(model, {
"<|im_start|>": 100264,
"<|im_end|>": 100265,
"<|im_sep|>": 100266,
});
encoder_cache[model] = encoder;
}
const msgSep = isGpt3 ? "\n" : "";
const roleSep = isGpt3 ? "\n" : "<|im_sep|>";
const serialized = [
messages
.map(({ name, role, content }) => {
return `<|im_start|>${name || role}${roleSep}${content}<|im_end|>`;
})
.join(msgSep),
"<|im_start|>assistant",
].join(msgSep);
let encoded = encoder.encode(serialized, "all");
return encoded.length;
}
function deprecatedFunction() {
throw new Error('Warning: The usage of this module has changed. Please use .chat or .text methods instead of calling the module as a function. Refer to the documentation for examples ( https://www.npmjs.com/package/openai-gpt-token-counter )');
}
deprecatedFunction.chat = getChatGPTEncoding;
deprecatedFunction.text = (text, model=null) => require('./Encoder.js').encode(text).length;
module.exports = deprecatedFunction;