Split text into semantic chunks, up to a desired chunk size. Supports calculating length by characters and tokens, and is callable from Rust and Python.
Actively maintained. Last release 8 days ago, commits in 26 of the last 26 weeks. A safe choice.
pip install semantic-text-splittersemantic-text-splitter
Large language models (LLMs) can be used for many tasks, but often have a limited context size that can be smaller than documents you might want to use. To use documents of larger length, you often have to split your text into chunks to fit within this context size.
This crate provides methods for splitting longer pieces of text into smaller chunks, aiming to maximize a desired chunk size, but still splitting at semantically sensible boundaries whenever possible.
Get Started
By Number of Characters
from semantic_text_splitter import TextSplitter
# Maximum number of characters in a chunk
max_characters = 1000
# Optionally can also have the splitter not trim whitespace for you
splitter = TextSplitter(max_characters)
# splitter = TextSplitter(max_characters, trim=False)
chunks = splitter.chunks("your document text")
Using a Range for Chunk Capacity
You also have the option of specifying your chunk capacity as a range.
Once a chunk has reached a length that falls within the range it will be returned.
It is always possible that a chunk may be returned that is less than the start value, as adding the next piece of text may have made it larger than the end capacity.
from semantic_text_splitter import TextSplitter
# Maximum number of characters in a chunk. Will fill up the
# chunk until it is somewhere in this range.
splitter = TextSplitter((200,1000))
chunks = splitter.chunks("your document text")
Using a Hugging Face Tokenizer
from semantic_text_splitter import TextSplitter
from tokenizers import Tokenizer
# Maximum number of tokens in a chunk
max_tokens = 1000
tokenizer = Tokenizer.from_pretrained("bert-base-uncased")
# If your tokenizer has truncation enabled, disable it before passing it to
# the splitter. Otherwise chunk sizes can be capped by the tokenizer's
# truncation limit.
tokenizer.no_truncation()
splitter = TextSplitter.from_huggingface_tokenizer(tokenizer, max_tokens)
chunks = splitter.chunks("your document text")
Using a Tiktoken Tokenizer
from semantic_text_splitter import TextSplitter
# Maximum number of tokens in a chunk
max_tokens = 1000
splitter = TextSplitter.from_tiktoken_model("gpt-3.5-turbo", max_tokens)
chunks = splitter.chunks("your document text")