js-tiktoken is a pure JavaScript port of OpenAI's tiktoken library, providing a BPE (Byte Pair Encoding) tokenizer primarily for use with OpenAI's models. Currently at version 1.0.21, the library undergoes frequent patch releases, mainly to incorporate new OpenAI models and their corresponding tokenizer configurations. Its key differentiators include being a pure JavaScript implementation, making it suitable for web browsers, edge environments, and Node.js applications where Python dependencies are not feasible. It also offers a "lite" mode, allowing developers to load only specific encoding ranks to significantly reduce bundle size, or to dynamically fetch encoding data from a CDN, addressing concerns about the full library's potentially large footprint.
npm install js-tiktokenVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to obtain an encoding using both `getEncoding` for a specific scheme and `encodingForModel` for a model name, then encode and decode text, verifying the round trip. Includes error handling for unknown models.
For web applications or environments with strict bundle size limits, use the `js-tiktoken/lite` import path and load encoding ranks manually from `js-tiktoken/ranks/...` or dynamically fetch them from a CDN. Example: `import { Tiktoken } from 'js-tiktoken/lite'; import o200k_base from 'js-tiktoken/ranks/o200k_base'; const enc = new Tiktoken(o200k_base);`Migrate projects to use native ESM imports (`import ... from '...'`) for optimal compatibility, tree-shaking benefits, and future-proofing. If strictly bound to CommonJS, consider dynamic `import()` or ensure your build setup correctly handles ESM-to-CJS conversion.
Always refer to the official OpenAI documentation or `js-tiktoken`'s source for the exact and up-to-date list of supported model names. Implement error handling (e.g., `try...catch`) around calls to `encodingForModel` to gracefully manage unknown model names.
Ensure your build tool is configured to process and include static JSON files. For example, in Webpack, you might need a `json-loader`. Alternatively, fetch the rank data dynamically from a CDN as outlined in the `js-tiktoken/lite` documentation example.
Use native ESM imports: `import { getEncoding } from 'js-tiktoken';`. If you must use CommonJS, ensure you are correctly accessing the named export, potentially via `const { getEncoding } = require('js-tiktoken');` though full ESM compatibility is recommended.Verify the exact spelling and casing of the model name. Consult the `js-tiktoken` documentation or the underlying `tiktoken` library's list of supported models, as these are frequently updated with new OpenAI releases. Consider adding a `try...catch` block to handle cases where a model name might become deprecated or is not yet supported.
No dependency data recorded yet.