Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python tokenizer libraries split text into the tokens a language model reads and map each token to an integer ID. A subword tokenizer trains its vocabulary from text rather than splitting only on spaces and punctuation. These libraries let apps and AI agents count tokens before a model call.
Popularity
tiktoken has the most monthly downloads in this comparison, at 223.6M.
def __init__(
self,
encoding_name: str = "gpt2",
model_name: str | None = None,
allowed_special: Literal["all"] | AbstractSet[str] | None = None,
disallowed_special: Literal["all"] | Collection[str] = "all",
**kwargs: Any,
) -> None:
"""Create a new `TokenTextSplitter`.
Args:
encoding_name: The name of the tiktoken encoding to use.
model_name: The name of the model to use.
If provided, this will override the `encoding_name`.
allowed_special: Special tokens that are allowed during encoding.
disallowed_special: Special tokens that are disallowed during encoding.
Raises:
ImportError: If the tiktoken package is not installed.
"""
if allowed_special is None:
allowed_special = set[str]()
super().__init__(**kwargs)
try:
tiktoken = cast("Any", _import_tiktoken())
except ImportError as err:
msg = (
"Could not import tiktoken python package. "
"This is needed in order to for TokenTextSplitter. "
"Please install it with `pip install tiktoken`."
)
raise ImportError(msg) from err
if model_name is not None:
enc = tiktoken.encoding_for_model(model_name)
else:
enc = tiktoken.get_encoding(encoding_name)
self._tokenizer = enc
self._allowed_special = allowed_special
self._disallowed_special = disallowed_special
Tokenizers
Provides configurable tokenization pipelines and vocabulary training through Rust-backed Python bindings.
Downloads / mo
216.8M
Stars
11.3K
Last release
0.23.3
License
Apache-2.0
Strengths
Trains a custom vocabulary.Train from files or an iterator of text.
Tracks tokens to original text.Use offsets to recover the input span behind each token.
Limitations
Decoding needs a matching decoder.Configure the decoder to handle the vocabulary’s subword markers.
@classmethod
def from_huggingface_tokenizer(
cls, tokenizer: PreTrainedTokenizerBase, **kwargs: Any
) -> TextSplitter:
"""Text splitter that uses Hugging Face tokenizer to count length.
Args:
tokenizer: The Hugging Face tokenizer to use.
Returns:
An instance of `TextSplitter` using the Hugging Face tokenizer for length
calculation.
"""
pretrained_tokenizer_base = _import_pretrained_tokenizer_base()
if not isinstance(tokenizer, pretrained_tokenizer_base):
msg = "Tokenizer received was not an instance of PreTrainedTokenizerBase"
raise ValueError(msg) # noqa: TRY004
def _huggingface_tokenizer_length(text: str) -> int:
return len(tokenizer.tokenize(text))
return cls(length_function=_huggingface_tokenizer_length, **kwargs)
def tokenize(self, text, include_punc=True):
"""Return a list of word tokens.
:param text: string of text.
:param include_punc: (optional) whether to
include punctuation as separate tokens. Default to True.
"""
tokens = nltk.tokenize.word_tokenize(text)
if include_punc:
return tokens
else:
# Return each word token # Strips punctuation unless the word comes from a contraction # e.g. "Let's" => ["Let", "'s"] # e.g. "Can't" => ["Ca", "n't"] # e.g. "home." => ['home'] return [
word if word.startswith("'") else strip_punc(word, all=False)
for word in tokens
if strip_punc(word, all=False)
]
SentencePiece
Trains and applies subword tokenization directly to raw text.
Downloads / mo
29.8M
Stars
12.2K
Last release
0.2.3
License
Apache-2.0
Strengths
Trains directly from raw text.Train a vocabulary without a language-specific word splitter.
Supports sampled segmentations.Sample different subword splits while preparing training text.
Limitations
Normalization can change whitespace.Check the model’s whitespace rules before assuming exact text reconstruction.
import sentencepiece as spm
processor = spm.SentencePieceProcessor(model_file='test/botchan_en_unigram_1000.model')
print(processor.encode('This is a test'))
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
features = model.preprocess(['Hello world'])
print(features)
def __init__(
self,
chunk_overlap: int = 50,
model_name: str = "sentence-transformers/all-mpnet-base-v2",
tokens_per_chunk: int | None = None,
model_kwargs: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
"""Create a new `TextSplitter`.
Args:
chunk_overlap: The number of tokens to overlap between chunks.
model_name: The name of the sentence transformer model to use.
tokens_per_chunk: The number of tokens per chunk.
If `None`, uses the maximum tokens allowed by the model.
model_kwargs: Additional parameters for model initialization.
Parameters of sentence_transformers.SentenceTransformer can be used.
Raises:
ImportError: If the `sentence_transformers` package is not installed.
ValueError: If `tokens_per_chunk` exceeds the model's maximum token limit.
"""
super().__init__(**kwargs, chunk_overlap=chunk_overlap)
try:
sentence_transformers = cast("Any", import_module("sentence_transformers"))
sentence_transformer_cls = sentence_transformers.SentenceTransformer
except ImportError as err:
msg = (
"Could not import sentence_transformers python package. "
"This is needed in order to use SentenceTransformersTokenTextSplitter. "
"Please install it with `pip install sentence-transformers`."
)
raise ImportError(msg) from err
self.model_name = model_name
self._model = sentence_transformer_cls(self.model_name, **(model_kwargs or {}))
self.tokenizer = self._model.tokenizer
self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk)
def cut(self, sentence, cut_all=False, use_hmm=True):
"""
The method used to cut the text to tokens.
Args:
sentence(str): The text that needs to be cut.
cut_all(bool, optional): Whether to use the full mode. If True,
using full mode that gets all the possible words from the
sentence, which is fast but not accurate. If False, using
accurate mode that attempts to cut the sentence into the most
accurate segmentations, which is suitable for text analysis.
Default: False.
use_hmm(bool, optional): Whether to use the HMM model. Default: True.
Returns:
list[str]: A list of tokens.
Example:
.. code-block:: python
from paddlenlp.data import Vocab, JiebaTokenizer
# The vocab file. The sample file can be downloaded firstly. # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt vocab_file_path = './senta_word_dict.txt'
# Initialize the Vocab vocab = Vocab.load_vocabulary(
vocab_file_path,
unk_token='[UNK]',
pad_token='[PAD]')
tokenizer = JiebaTokenizer(vocab)
tokens = tokenizer.cut('我爱你中国')
print(tokens)
# ['我爱你', '中国'] """
return self.tokenizer.lcut(sentence, cut_all, use_hmm)
FAQ
tiktoken suits counting and encoding tokens for OpenAI models. Tokenizers and SentencePiece suit training a custom vocabulary. Transformers suits loading the tokenizer that matches a specific model.
tiktoken encodes and decodes text with byte-pair tokenization for OpenAI models. It can select the encoding for a given model name.
SentencePiece trains and applies subword tokenization directly on raw sentences.