Text Splitters
Relevant source files
The following files were used as context for generating this wiki page: - [libs/text-splitters/langchain_text_splitters/base.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/langchain_text_splitters/base.py) - [libs/text-splitters/langchain_text_splitters/character.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/langchain_text_splitters/character.py) - [libs/text-splitters/langchain_text_splitters/markdown.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/langchain_text_splitters/markdown.py) - [libs/text-splitters/langchain_text_splitters/python.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/langchain_text_splitters/python.py) - [libs/text-splitters/langchain_text_splitters/html.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/langchain_text_splitters/html.py) - [libs/text-splitters/langchain_text_splitters/__init__.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/langchain_text_splitters/__init__.py) - [libs/text-splitters/tests/unit_tests/test_text_splitters.py](https://github.com/langchain-ai/langchain/blob/HEAD/libs/text-splitters/tests/unit_tests/test_text_splitters.py)Text Splitters are utilities designed to break down large pieces of text into smaller, semantically meaningful chunks. This is a crucial preprocessing step in many LLM applications, especially for Retrieval Augmented Generation (RAG), where long documents must be split before being embedded and stored in a vector database. The langchain-text-splitters package provides a variety of splitters tailored for different text formats, from plain text to structured documents and source code.
The core idea is to split text while trying to keep related pieces of text together. The main classes are designed to be simple to use but flexible enough to handle complex splitting logic. The primary output of a text splitter is a list of Document objects, each containing a chunk of text and associated metadata.
Core Concepts and Architecture
The text splitting architecture is centered around the TextSplitter base class, which provides a standard interface for all character-based splitters. However, some specialized splitters, like MarkdownHeaderTextSplitter and HTMLHeaderTextSplitter, do not inherit from this base class but follow a similar interface.
Sources: libs/text-splitters/langchain_text_splitters/init.py:7-12
Class Hierarchy
The following diagram illustrates the class hierarchy for the main text splitters. Most general-purpose splitters inherit from TextSplitter, which itself is a BaseDocumentTransformer. Specialized format-aware splitters may implement the splitting logic independently.
This diagram shows the inheritance structure of key Text Splitter classes.
Sources: libs/text-splitters/langchain_text_splitters/base.py, libs/text-splitters/langchain_text_splitters/character.py, libs/text-splitters/langchain_text_splitters/markdown.py, libs/text-splitters/langchain_text_splitters/html.py
The Splitting Process
The general process for splitting text using a TextSplitter subclass involves several steps:
- Split by Separator: The input text is initially split into smaller pieces based on a specified separator (or a list of separators).
- Merge Splits: The small pieces are then merged back together into chunks that are smaller than
chunk_size. The merging process respects thechunk_overlapto maintain context between chunks. - Create Documents: Finally, the text chunks are converted into
langchain_core.documents.Documentobjects. Metadata from the original document can be preserved, and new metadata, such asstart_index, can be added.
This flow is illustrated below:
This flowchart shows the generic data flow for a TextSplitter.
Sources: libs/text-splitters/langchain_text_splitters/character.py:129-142, libs/text-splitters/langchain_text_splitters/character.py:202-214
General Purpose Splitters
CharacterTextSplitter
This is a basic text splitter that splits text based on a single character separator and measures chunk length by the number of characters.
Key Parameters:
| Parameter | Type | Description | Default |
|---|---|---|---|
chunk_size | int | The maximum size of a chunk (measured in characters). | 1000 |
chunk_overlap | int | The number of characters to overlap between chunks. | 200 |
separator | str | The string or character to split on. | "\n\n" |
keep_separator | bool | Whether to keep the separator in the chunks. | True |
is_separator_regex | bool | Whether the separator is a regular expression. | False |
add_start_index | bool | If True, adds the start index of the chunk in the original text to the metadata. | False |
An error is raised if chunk_overlap is larger than chunk_size.
Sources: libs/text-splitters/langchain_text_splitters/character.py:18-40, libs/text-splitters/tests/unit_tests/test_text_splitters.py:204-206
RecursiveCharacterTextSplitter
This is the recommended and most commonly used text splitter. It extends CharacterTextSplitter by attempting to split text using a list of separators in order. It tries to split on the first separator (e.g., "\n\n") and if the resulting chunks are still too large, it moves to the next separator (e.g., "\n"), and so on. This recursive approach helps to keep semantically related chunks together as much as possible.
Key Parameters:
| Parameter | Type | Description | Default |
|---|---|---|---|
separators | Optional[List[str]] | A list of separators to try recursively. | ["\n\n", "\n", " ", ""] |
keep_separator | Union[bool, Literal["start", "end"]] | Whether/where to keep separators. Can be True, False, "start", or "end". | True |
chunk_size | int | Maximum size of chunks. | 1000 |
chunk_overlap | int | Overlap in characters between chunks. | 200 |
The keep_separator parameter offers fine-grained control. For example, keep_separator="end" will place the separator at the end of the chunk it was split from.
Sources: libs/text-splitters/langchain_text_splitters/character.py:230-251, libs/text-splitters/tests/unit_tests/test_text_splitters.py:170-191
Specialized Splitters
Language-Specific Splitters
RecursiveCharacterTextSplitter includes a factory method from_language that creates a splitter with a predefined set of separators suitable for a specific programming language. This is particularly useful for splitting source code.
# libs/text-splitters/langchain_text_splitters/character.py:253-260
@classmethod
def from_language(
cls, language: Language, **kwargs: Any
) -> RecursiveCharacterTextSplitter:
"""Create a new TextSplitter for a specific language."""
separators = cls.get_separators_for_language(language)
return cls(separators=separators, **kwargs)
Supported languages are defined in the Language enum and include Python, Ruby, Go, Java, JavaScript, and many others. For example, the PythonCodeTextSplitter is a RecursiveCharacterTextSplitter pre-configured with Python-specific separators like \nclass , \ndef , \n\tdef , and \n\n.
Sources: libs/text-splitters/langchain_text_splitters/python.py:11-20, libs/text-splitters/langchain_text_splitters/base.py:16-101, libs/text-splitters/tests/unit_tests/test_text_splitters.py:408-425
MarkdownHeaderTextSplitter
This splitter is designed specifically for Markdown files. It splits the text based on header levels (e.g., #, ##) and associates the content chunks with the corresponding headers in the metadata. This is useful for preserving the document's structure.
Key Features:
- Header-based Splitting: Splits content under different headers into separate documents.
- Hierarchical Metadata: Metadata for each chunk includes all parent headers.
- Code Block Handling: Correctly handles fenced code blocks, preventing them from being misinterpreted as headers.
- Custom Headers: Supports custom header patterns beyond standard Markdown
#syntax (e.g.,**Header**). - Configuration: Can be configured to strip headers from content or keep them.
The splitter processes the document line by line, maintaining a stack of current headers to build the metadata for each chunk.
Sequence diagram illustrating the logic of MarkdownHeaderTextSplitter.
Sources: libs/text-splitters/langchain_text_splitters/markdown.py:20-155, libs/text-splitters/tests/unit_tests/test_text_splitters.py:1003-1031
HTMLHeaderTextSplitter
Similar to its Markdown counterpart, HTMLHeaderTextSplitter splits HTML documents based on header tags (<h1>, <h2>, etc.). It traverses the DOM tree and creates documents for text content, associating them with the headers they fall under.
Key Features:
- DOM Traversal: Uses
BeautifulSoupto parse and traverse the HTML structure. - Hierarchical Metadata: Captures the nested structure of headers in the metadata.
- Flexible Output: Can return each HTML element as a separate document or aggregate content under common headers.
Sources: libs/text-splitters/langchain_text_splitters/html.py:40-148, libs/text-splitters/tests/unit_tests/test_text_splitters.py:1718-1815
HTMLSemanticPreservingSplitter
This is an advanced HTML splitter that aims to preserve the semantic structure of the content. It splits by headers but also handles complex elements like tables and lists. If a resulting chunk is still too large, it uses a RecursiveCharacterTextSplitter for further subdivision.
Key Features:
- Semantic Preservation: Keeps elements like
<table>and<ul>intact. - Link and Media Handling: Can convert
<a>,<img>,<video>, and<audio>tags into Markdown-style links. - Recursive Splitting: Falls back to
RecursiveCharacterTextSplitterfor large content chunks. - Tag Filtering: Supports allowlists and denylists for HTML tags.
Sources: libs/text-splitters/langchain_text_splitters/html.py:461-604, libs/text-splitters/tests/unit_tests/test_text_splitters.py:2311-2332
Usage and Document Creation
All splitters ultimately aim to produce a list of Document objects. The create_documents method is a key part of this process.
# libs/text-splitters/langchain_text_splitters/base.py:159-181
def create_documents(
self, texts: list[str], metadatas: Optional[list[dict]] = None
) -> list[Document]:
"""Create documents from a list of texts."""
_metadatas = metadatas or [{}] * len(texts)
documents = []
for i, text in enumerate(texts):
start_index = 0
for chunk in self.split_text(text):
metadata = copy.deepcopy(_metadatas[i])
if self._add_start_index:
index = text.find(chunk, start_index)
if index == -1:
# Handle cases where the chunk is not found, possibly due to
# separator removal or other modifications.
# For now, we'll just not add the start_index.
pass
else:
metadata["start_index"] = index
start_index = index + len(chunk)
new_doc = Document(page_content=chunk, metadata=metadata)
documents.append(new_doc)
return documents
This method iterates through input texts, splits each one, and creates Document objects. It handles the deep copying of metadata to ensure that documents created from the same source text do not share mutable metadata objects. It also supports adding the start_index of each chunk to the metadata, which can be useful for referencing the original source.
Sources: libs/text-splitters/langchain_text_splitters/base.py:159-181, libs/text-splitters/tests/unit_tests/test_text_splitters.py:256-271
Conclusion
Text Splitters are a fundamental component in the LangChain ecosystem for preparing data for use with large language models. The library offers a range of splitters, from simple character-based ones to sophisticated, structure-aware splitters for formats like Markdown and HTML. The RecursiveCharacterTextSplitter is the recommended default for its ability to intelligently handle text by trying multiple separators, while specialized splitters provide powerful tools for preserving the semantic structure of complex documents and source code.