Skip to main content
Language models have a token limit. You should not exceed the token limit. When you split your text into chunks it is therefore a good idea to count the number of tokens. There are many tokenizers. When you count tokens in your text you should use the same tokenizer as used in the language model.

js-tiktoken

js-tiktoken is a JavaScript vesrion of the BPE tokenizer created by OpenAI.
We can use tiktoken to estimate tokens used using TokenTextSplitter. It will probably be more accurate for OpenAI models.
  1. How the text is split: by character passed in.
  2. How the chunk size is measured: by tiktoken tokenizer.
To split with a TokenTextSplitter and then merge chunks with tiktoken, pass in an encodingName (e.g. cl100k_base) when initializing the TokenTextSplitter. Note that splits from this method can be larger than the chunk size measured by the tiktoken tokenizer.