The Complete Reference Guide to
langchain_text_splitters
Architecture, Class Reference, Chunking Strategies, and Production Patterns
for RAG Engineers
AI Engineering Reference Series
2026
Contents
Table of Contents
3
1. Introduction
1.1 What is langchain_text_splitters . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 Why Text Splitting Matters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3 Where This Package Sits in a RAG Pipeline . . . . . . . . . . . . . . . . . . . . .
4
4
4
4
2. Package Architecture
2.1 Module Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Core Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Inheritance Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4 Design Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5 Internal Workflow (RecursiveCharacterTextSplitter) . . . . . . . . . . . . . . . .
5
5
5
5
6
7
3. The Chunking Problem — Theory First
8
4. Core Base Classes
9
4.1 TextSplitter (Abstract Base Class) . . . . . . . . . . . . . . . . . . . . . . . . .
9
4.2 Language (Enum) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.3 Tokenizer (dataclass) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5. Complete Class Reference
5.1 CharacterTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2 RecursiveCharacterTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . .
5.3 TokenTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.4 SentenceTransformersTokenTextSplitter . . . . . . . . . . . . . . . . . . . . . .
5.5 Markdown Splitters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.6 HTML Splitters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.7 LatexTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.8 Code Splitters: PythonCodeTextSplitter and Language-Based Splitting . . . . . .
5.9 NLTKTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.10 SpacyTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.11 KonlpyTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.12 RecursiveJsonSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.13 JSFrameworkTextSplitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
12
12
13
16
17
18
19
22
22
23
23
24
24
26
6. Comparison Tables
6.1 Feature Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2 Performance Comparison (Qualitative) . . . . . . . . . . . . . . . . . . . . . . . .
6.3 Use-Case Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
27
27
27
28
7. Chunking Strategy Deep Dive
7.1 Fixed Chunking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2 Recursive Chunking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.3 Semantic Chunking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.4 Token-Based Chunking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5 Structure-Aware Chunking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29
29
29
29
29
29
8. Production Recipes
8.1 PDF Ingestion Pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.2 RAG Application (Hybrid Structure + Length) . . . . . . . . . . . . . . . . . . . .
8.3 Chatbot Ingestion (Multi-Format Router) . . . . . . . . . . . . . . . . . . . . . .
8.4 Knowledge Management System — Preserving Tables . . . . . . . . . . . . . . .
8.5 Enterprise Search over Codebase + Metadata (CPMPulse_v2-style) . . . . . . . .
31
31
31
31
32
32
9. Troubleshooting Guide
9.1 Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.2 Debugging Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.3 Performance Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.4 Memory Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.5 Token Overflow Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.6 Chunk Overlap Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
33
33
33
33
34
34
34
10. Interview Questions & Answers
Beginner Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Intermediate Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Advanced Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Architect Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
35
35
35
35
36
11. Best Practices, Anti-Patterns & Cheatsheet
11.1 Best Practices Checklist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.2 Production Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.3 Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.4 Anti-Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.5 Summary Cheatsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.6 Quick Reference — Default Parameter Values . . . . . . . . . . . . . . . . . . .
37
37
37
37
37
38
38
2
Table of Contents
1. Introduction
2. Package Architecture
3. The Chunking Problem — Theory First
4. Core Base Classes
5. Complete Class Reference
• CharacterTextSplitter
• RecursiveCharacterTextSplitter
• TokenTextSplitter
• SentenceTransformersTokenTextSplitter
• MarkdownTextSplitter
• MarkdownHeaderTextSplitter
• ExperimentalMarkdownSyntaxTextSplitter
• HTMLHeaderTextSplitter
• HTMLSectionSplitter
• HTMLSemanticPreservingSplitter
• LatexTextSplitter
• PythonCodeTextSplitter / Language-Aware Splitting
• NLTKTextSplitter
• SpacyTextSplitter
• KonlpyTextSplitter
• RecursiveJsonSplitter
• JSFrameworkTextSplitter
6. Comparison Tables
7. Chunking Strategy Deep Dive
8. Production Recipes (PDF, RAG, Chatbot, Enterprise Search)
9. Troubleshooting Guide
10. Interview Questions & Answers
11. Best Practices, Anti-Patterns & Cheatsheet
3
1. Introduction
1.1 What is langchain_text_splitters
langchain_text_splitters is an independently versioned Python package (libs/textsplitters/ inside the LangChain monorepo) that provides utilities for breaking large pieces
of text — or structured formats like HTML, Markdown, JSON, and source code — into smaller,
model-friendly chunks. It ships as a lightweight package with no heavy ML dependencies
by default; optional splitters (NLTK, spaCy, sentence-transformers, tiktoken) pull in extra
dependencies only when you install their extras.
At its core, the package answers one deceptively simple question every LLM application eventually has to solve:
“I have more text than fits in a context window or makes sense in a single embedding
— how do I cut it up without destroying its meaning?”
1.2 Why Text Splitting Matters
Every downstream LLM capability depends on how well you’ve chunked your source data:
• RAG systems — Retrieval quality is bounded by chunk quality. A chunk that mixes two
unrelated ideas will never be a precise retrieval hit for either.
• Embedding generation — Embedding models have a maximum sequence length. Text
beyond that limit gets silently truncated by many APIs, quietly destroying information
you thought was indexed.
• Vector databases — Storage, indexing cost, and query latency all scale with the number
and size of chunks. Poor chunking inflates infrastructure cost for no retrieval benefit.
• Semantic search — Search relevance depends on each vector representing one coherent “unit of meaning.” Splitting mid-sentence or mid-table destroys that coherence.
• Knowledge bases — Chunk boundaries often become citation boundaries; users expect
a retrieved chunk to be a complete, quotable thought.
• LLM context management — Even models with huge context windows have degrading
attention over long contexts (“lost in the middle”). Precise, relevant, appropriately-sized
chunks outperform dumping entire documents into the prompt.
1.3 Where This Package Sits in a RAG Pipeline
┌──────────────┐
┌──────────────────┐
┌───────────────┐
┌───────────────┐
│ Document
│──▶│ Text Splitter
│──▶│
Embedding
│──▶│ Vector Store │
│ Loader
│
│ (this package)
│
│
Model
│
│ (Chroma, PG, │
│ (PDF, HTML, │
│ chunk_size,
│
│
│
│ Pinecone...) │
│ DOCX, etc.) │
│ chunk_overlap
│
│
│
│
│
└──────────────┘
└──────────────────┘
└───────────────┘
└───────────────┘
│
▼
┌───────────────────┐
│ Retriever → LLM
│
│ (RAG answer)
│
└───────────────────┘
Text splitters sit immediately after document loading and immediately before embedding.
They are not part of the LCEL (LangChain Expression Language) Runnable chain execution
model — they are a preprocessing utility you call once, ahead of time, as part of your ingestion
pipeline.
4
2. Package Architecture
2.1 Module Layout
langchain_text_splitters/
├── __init__.py
# Public exports
├── base.py
# TextSplitter (ABC), TokenTextSplitter, Language, Tokenizer
├── character.py
# CharacterTextSplitter, RecursiveCharacterTextSplitter
├── html.py
# HTMLHeaderTextSplitter, HTMLSectionSplitter,
│
#
HTMLSemanticPreservingSplitter
├── markdown.py
# MarkdownHeaderTextSplitter, MarkdownTextSplitter,
│
#
ExperimentalMarkdownSyntaxTextSplitter
├── sentence_transformers.py
# SentenceTransformersTokenTextSplitter
├── json.py
# RecursiveJsonSplitter
├── jsx.py
# JSFrameworkTextSplitter
├── nltk.py
# NLTKTextSplitter
├── spacy.py
# SpacyTextSplitter
├── konlpy.py
# KonlpyTextSplitter (Korean)
├── python.py
# PythonCodeTextSplitter
└── latex.py
# LatexTextSplitter
2.2 Core Concepts
Concept
Meaning
Chunk
A contiguous piece of text (or a Document)
produced by a splitter.
The target maximum length of a chunk,
measured in whatever unit the
length_function returns (characters by
default, tokens if configured).
The number of units of text repeated
between consecutive chunks, used to
preserve context across a chunk boundary.
A callable, default len, used to measure
chunk size. Can be swapped for a
tokenizer-based counter.
An ordered list of strings a recursive splitter
tries, from “most semantically meaningful”
(e.g., "\n\n") down to “most desperate” (e.g.,
"", i.e., character-by-character).
Controls whether the separator itself is kept
in the resulting chunk, and if so, whether it’s
attached to the start or end of the chunk.
A LangChain Core object (page_content +
metadata) — many splitter methods operate
on/return Document objects rather than raw
strings so metadata survives the split.
chunk_size
chunk_overlap
length_function
Separator hierarchy
keep_separator
Document
2.3 Inheritance Hierarchy
┌────────────────────────┐
│ BaseDocumentTransformer │
5
(langchain_core.documents)
└────────────┬────────────┘
│
┌────────────▼────────────┐
│
TextSplitter (ABC) │ base.py
│ - split_text() [abstract]
│ - create_documents()
│ - split_documents()
│ - transform_documents()
│ - from_huggingface_tokenizer()
│ - from_tiktoken_encoder()
└──┬───────────┬────────────┬────────────────┐
│
│
│
│
┌────────────▼──┐ ┌─────▼──────┐ ┌───▼────────┐ ┌─────▼────────────┐
│CharacterText │ │TokenText
│ │NLTKText
│ │SpacyTextSplitter │
│Splitter
│ │Splitter
│ │Splitter
│ └───────────────────┘
└───────┬───────┘ └────────────┘ └────────────┘
│
┌─────────────▼──────────────┐
│ RecursiveCharacterText
│
│ Splitter
│
│ (+ from_language() factory)│
└─────────────┬────────────────────────────────┐
│
│
┌──────────▼─────────┐
┌─────────▼────────┐
│ MarkdownTextSplitter│
│PythonCodeText
│
│ (preset separators) │
│Splitter (preset) │
└──────────────────────┘
└────────────────────┘
Independent / interface-compatible but NOT inheriting TextSplitter directly:
MarkdownHeaderTextSplitter, ExperimentalMarkdownSyntaxTextSplitter,
HTMLHeaderTextSplitter, HTMLSectionSplitter, RecursiveJsonSplitter
→ these implement their own split_text()/split() and largely extend
BaseDocumentTransformer rather than TextSplitter, because they split
on structural boundaries, not length.
HTMLSemanticPreservingSplitter → extends BaseDocumentTransformer directly.
2.4 Design Philosophy
1. Separator-first, length-bounded. Most splitters try to cut at natural, meaningpreserving boundaries first (paragraph → sentence → word → character) and only fall
back to a harder cut when nothing else keeps the chunk under chunk_size.
2. Structure-aware where possible. For formats with explicit structure (Markdown headers, HTML tags, JSON nesting, source code syntax), the package prefers splitting on that
structure rather than blindly on character count.
3. Metadata propagation. Structural splitters (Markdown/HTML header splitters) attach
the header hierarchy as Document.metadata, so a downstream retriever can filter or display “Chapter 3 > Section 2” alongside a chunk.
4. Swappable length measurement. Because chunk_size is measured by an injectable
length_function, you can measure in characters (fast, no dependency) or in actual model
tokens (accurate, requires tiktoken or a HuggingFace tokenizer) without changing splitter logic.
5. Small core, optional heavy dependencies. NLTK, spaCy, and sentence-transformersbased splitters are optional installs — the base package stays light for services that don’t
6
need them.
2.5 Internal Workflow (RecursiveCharacterTextSplitter)
split_text(text)
│
▼
Take separators = ["\n\n", "\n", " ", ""] (default)
│
▼
For the first separator S in the list:
│
├─ Does S appear in `text`? ──No──▶ try next separator
│
│Yes
│
▼
│ Split `text` on S → list of fragments
│
│
│
▼
│ Greedily merge fragments into chunks ≤ chunk_size,
│ re-adding `chunk_overlap` units of trailing context
│ from the previous chunk to the next
│
│
│
▼
│ Any fragment STILL bigger than chunk_size? ──Yes──▶ recurse into
│
│
that fragment
│
│No
with the
│
▼
REMAINING
│ Return merged chunks
separator list
▼
Return final flat list[str]
7
3. The Chunking Problem — Theory First
Before touching classes, it helps to understand the five families of chunking strategy this
package implements, because every class below is really just one strategy wearing a specific
format-aware costume.
Package Classes That
Implement It
Strategy
Core Idea
Fixed-size chunking
Cut every N
characters/tokens, optionally
with overlap, ignoring
structure.
Try a hierarchy of separators,
falling back to smaller units
only where needed.
Split at the format’s own
structural boundaries
(headers, tags, JSON keys,
code blocks) and attach
structure as metadata.
Recursive chunking
Structure-aware chunking
Linguistically-aware
chunking
Token-based /
model-aware chunking
Use a real
sentence/tokenizer model
(not regex heuristics) to find
true sentence boundaries.
Measure and cut by actual
model tokens rather than
characters, so chunks map
precisely to context-window
budget or embedding-model
limits.
CharacterTextSplitter
(single separator),
TokenTextSplitter
RecursiveCharacterTextSplitter
and its language/markdown
presets
MarkdownHeaderTextSplitter,
HTMLHeaderTextSplitter,
HTMLSectionSplitter,
HTMLSemanticPreservingSplitter,
RecursiveJsonSplitter,
JSFrameworkTextSplitter,
language-mode RecursiveCharacterTextSplitter
NLTKTextSplitter,
SpacyTextSplitter,
KonlpyTextSplitter
TokenTextSplitter,
SentenceTransformersTokenTextSplitter,
.from_tiktoken_encoder() /
.from_huggingface_tokenizer()
factory constructors on any
splitter
Note that semantic chunking (grouping by embedding similarity rather than syntax) is not
implemented in langchain_text_splitters itself — it lives in langchain_experimental.text_splitter.Seman
It’s covered in section 7.3 for completeness since it’s commonly compared against this package.
8
4. Core Base Classes
4.1 TextSplitter (Abstract Base Class)
Module: langchain_text_splitters.base Inherits: BaseDocumentTransformer, ABC
Purpose
The interface every length-based splitter implements. You will almost never instantiate
TextSplitter directly — you subclass it (or use a subclass LangChain ships) — but its
methods are the ones you call on every splitter in this package, so it’s worth knowing cold.
Constructor Parameters
Parameter
Type
Default
Meaning
chunk_size
int
4000
chunk_overlap
int
200
length_function
Callable[[str],
int]
len
keep_separator
bool \| Literal["start","end"]
False
add_start_index
bool
False
strip_whitespace
bool
True
Maximum size of a
chunk, as measured
by length_function.
Number of units
repeated between
consecutive chunks.
Function used to
measure a string’s
“size.”
Whether/where to
keep the separator in
output chunks.
If True, adds a
start_index key to
each Document’s
metadata recording
its offset in the
original text.
Strips
leading/trailing
whitespace from
each chunk.
Key Methods
split_text(text: str) -> List[str] (abstract — every subclass must implement)
• Returns: a flat list of chunk strings.
• Raises: implementation-specific; base class raises NotImplementedError if unimplemented.
• Common mistake: calling this on a Document object instead of a raw string — it expects
str.
create_documents(texts:
List[Document]
List[str],
metadatas:
Optional[List[dict]]
=
None)
->
• Splits each string in texts, wraps every resulting chunk in a Document, and copies the corresponding metadatas[i] dict onto every chunk produced from texts[i] (so all chunks
from one source document share the same base metadata, e.g., source filename).
9
• Complexity: O(total characters) for character-based splitters; O(n log n) is not applicable since the algorithm is linear-scan based, not comparison-based.
split_documents(documents: Iterable[Document]) -> List[Document]
• Convenience wrapper that extracts page_content + metadata from a list of Documents
and calls create_documents for you. This is the method you use 95% of the time in
a real pipeline, since document loaders already hand you Document objects.
transform_documents(documents: Sequence[Document], **kwargs) -> Sequence[Document]
• Implements the BaseDocumentTransformer interface so a splitter can be dropped into any
LangChain pipeline stage expecting a document transformer (e.g., an indexing pipeline).
Internally calls split_documents.
from_huggingface_tokenizer(tokenizer, **kwargs) -> TextSplitter
• Classmethod. Swaps length_function for one that counts tokens using a HuggingFace
PreTrainedTokenizerBase. Use when your embedding model shares a tokenizer with a
HF model (e.g., BGE, E5 embedding families).
from_tiktoken_encoder(encoding_name="gpt2", model=None, allowed_special=..., disallowed_special=..., **kwargs) -> TextSplitter
• Classmethod. Swaps length_function for a tiktoken-based token counter. This is
the correct way to size chunks against OpenAI-family models — character count
is a poor proxy for token count (roughly 4 characters/token in English, but this varies
significantly by language and by code vs. prose).
Internal Behavior
create_documents and split_documents are not overridden by most subclasses — subclasses
only implement split_text. This is the core of the design: write the splitting logic once
per format, and get document-wrapping, metadata propagation, and the BaseDocumentTransformer interface for free.
Advantages / Limitations
Advantages: consistent interface across 15+ splitter types; token-aware sizing via two factory methods without rewriting splitting logic; automatic metadata propagation.
Limitations: the abstract class itself does nothing — if you’re debugging “why doesn’t my
splitter work,” the bug is always in the concrete subclass’s split_text, never in base.py.
Best Practices
• Always call split_documents, not split_text + manual Document wrapping, when working with loader output — you’ll lose metadata otherwise.
• Prefer from_tiktoken_encoder over guessing a character-based chunk_size when your
downstream model is token-billed or token-limited.
10
4.2 Language (Enum)
Module: langchain_text_splitters.base
An enum of ~30 programming/markup languages (PYTHON, JS, TS, JAVA, GO, RUST, PHP, MARKDOWN, HTML, LATEX, PROTO, RST, RUBY, SWIFT, SCALA, KOTLIN, CSHARP, COBOL, SOL, CSHARP, HASKELL,
ELIXIR, POWERSHELL, VISUALBASIC6, and others). Used exclusively as an argument to RecursiveCharacterTextSplitter.from_language(language=Language.PYTHON, ...), which selects a language-appropriate separator list (e.g., splitting Python on class, def, \n\tdef before falling back to blank lines).
4.3 Tokenizer (dataclass)
Module: langchain_text_splitters.base
Internal data structure (chunk_overlap, tokens_per_chunk, decode, encode) used by TokenTextSplitter and the from_tiktoken_encoder/from_huggingface_tokenizer factories to represent an injected tokenizer uniformly. You will rarely construct this yourself.
11
5. Complete Class Reference
5.1 CharacterTextSplitter
Module: character.py | Inherits: TextSplitter
Purpose
The simplest splitter: cut on a single separator string (default "\n\n"), then greedily pack
the resulting fragments into chunks up to chunk_size.
Constructor Parameters
Parameter
Type
Default
Notes
separator
str
"\n\n"
is_separator_regex
bool
False
chunk_size,
chunk_overlap,
length_function,
keep_separator,
add_start_index,
strip_whitespace
(inherited)
(inherited)
The single delimiter
to split on.
Treat separator as a
regex pattern.
Same as
TextSplitter.
When to Use / When Not To
• Use for text with one obviously dominant boundary (e.g., double-newline-separated log
entries, CSV-like records) or as a teaching baseline.
• Avoid for prose or mixed-structure documents — if a fragment between separators exceeds chunk_size, CharacterTextSplitter does not recurse into smaller separators; it
simply emits an oversized chunk (a common source of downstream truncation bugs).
Basic Example
from langchain_text_splitters import CharacterTextSplitter
splitter = CharacterTextSplitter(
separator="\n\n",
chunk_size=200,
chunk_overlap=20,
)
text = "Paragraph one.\n\nParagraph two, a bit longer.\n\nParagraph three."
chunks = splitter.split_text(text)
for c in chunks:
print(repr(c))
Intermediate Example — Token-Aware Sizing
from langchain_text_splitters import CharacterTextSplitter
12
splitter = CharacterTextSplitter.from_tiktoken_encoder(
encoding_name="cl100k_base",
separator="\n\n",
chunk_size=300,
# now measured in TOKENS, not characters
chunk_overlap=30,
)
chunks = splitter.split_text(long_report_text)
print(f"{len(chunks)} token-bounded chunks")
Production-Grade Example
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.document_loaders import DirectoryLoader, TextLoader
loader = DirectoryLoader("./logs", glob="**/*.log", loader_cls=TextLoader)
docs = loader.load()
splitter = CharacterTextSplitter(
separator="\n\n",
chunk_size=1000,
chunk_overlap=100,
add_start_index=True,
# lets you jump back to the exact source offset
)
chunks = splitter.split_documents(docs)
print(f"{len(docs)} files -> {len(chunks)} chunks")
Real-World RAG Example
# Best-fit use case: structured Q&A pairs separated by blank lines
faq_text = open("faq.txt").read()
splitter = CharacterTextSplitter(separator="\n\n", chunk_size=500, chunk_overlap=0)
docs = splitter.create_documents([faq_text], metadatas=[{"source": "faq.txt"}])
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
vectorstore = Chroma.from_documents(docs, OpenAIEmbeddings())
Advantages / Limitations / Best Practices
Advantages: trivial to reason about; fastest splitter in the package; zero surprises for wellstructured input. Limitations: no recursive fallback — oversized fragments pass through
unsplit; single separator can’t represent hierarchical text structure. Best practice: only
reach for this when you’re certain your separator reliably keeps fragments under chunk_size;
otherwise use RecursiveCharacterTextSplitter.
5.2 RecursiveCharacterTextSplitter
Module: character.py | Inherits: TextSplitter
13
Purpose
The default, recommended splitter for most use cases. Tries an ordered list of separators, falling back to smaller ones only for fragments that are still too large — keeping text as
“naturally chunked” as possible while guaranteeing every chunk respects chunk_size.
Constructor Parameters
Parameter
Type
Default
Notes
separators
List[str]
["\n\n", "\n", " ",
""]
is_separator_regex
bool
False
keep_separator
bool \| "start" \|
"end"
True
Ordered from most
to least semantically
meaningful.
Treat entries in
separators as regex.
Note: default differs
from base —
separators are kept
by default here.
Same as base class.
(all other
TextSplitter
params)
Classmethod: from_language(language: Language, **kwargs)
Returns a RecursiveCharacterTextSplitter pre-configured with a separator list appropriate
to language — e.g., for Language.PYTHON: ["\nclass ", "\ndef ", "\n\tdef ", "\n\n",
"\n", " ", ""], so functions and classes are preferred split points over arbitrary blank lines.
Chunking Strategy / Separator Logic
1. Try "\n\n" (paragraph breaks) first.
2. Fragments still over chunk_size are recursively split on "\n" (line breaks).
3. Still too big → split on " " (words).
4. Still too big (e.g., one 10,000-character word with no spaces) → split on "" (raw characters) as a last resort.
Basic Example
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_text(document_text)
print(len(chunks), "chunks")
Intermediate Example — Custom Separator Hierarchy
splitter = RecursiveCharacterTextSplitter(
separators=["\n## ", "\n### ", "\n\n", "\n", " ", ""],
chunk_size=800,
chunk_overlap=100,
)
chunks = splitter.split_text(markdown_like_notes)
14
Production-Grade Example — Language-Aware Code Splitting
from langchain_text_splitters import RecursiveCharacterTextSplitter, Language
python_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.PYTHON, chunk_size=1000, chunk_overlap=100
)
code_docs = python_splitter.create_documents([open("app.py").read()])
Real-World RAG Example
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
loader = PyPDFLoader("policy_manual.pdf")
pages = loader.load()
splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
encoding_name="cl100k_base", chunk_size=512, chunk_overlap=64
)
chunks = splitter.split_documents(pages)
vectorstore = Chroma.from_documents(chunks, OpenAIEmbeddings(), persist_directory="./db")
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
Method Reference (in addition to inherited TextSplitter methods)
split_text(text: str) -> List[str]
• Internal logic: recursive descent through separators; merges fragments greedily using
a sliding-window overlap accumulator.
• Complexity: O(n) per separator level in the worst case, bounded by len(separators)
recursion depth (typically ≤4) → effectively O(n).
• Common mistake: setting chunk_overlap >= chunk_size, which raises a ValueError
at construction time (they’re validated relative to each other).
Advantages / Limitations
Advantages: best general-purpose default; graceful degradation; language presets remove
the guesswork of picking code-aware separators. Limitations: still purely syntactic — it
has no notion of meaning, so it can still separate a sentence from its immediately relevant
conclusion if that’s where the size limit lands, just less often than fixed-size splitting.
Best Practices
• Start here for any new pipeline. Only switch to a structure-aware splitter (Markdown/HTML/JSON) if your source format has strong explicit structure worth preserving
as metadata.
• Pair with from_tiktoken_encoder whenever chunk_size needs to map to an actual
model/context budget.
15
5.3 TokenTextSplitter
Module: base.py | Inherits: TextSplitter
Purpose
Splits text purely by token count using tiktoken, ignoring semantic boundaries entirely. Useful when the only thing that matters is staying under a hard token ceiling (e.g., an embedding
model’s max sequence length), and you’re willing to accept mid-sentence cuts.
Constructor Parameters
Parameter
Type
Default
Notes
encoding_name
str
"gpt2"
model_name
Optional[str]
None
chunk_size
int
4000
chunk_overlap
allowed_special
int
Literal["all"] \|
AbstractSet[str]
200
{}
disallowed_special
Literal["all"] \|
Collection[str]
"all"
tiktoken encoding;
use "cl100k_base"
for GPT-3.5/4-era
models.
If given, resolves the
correct encoding
automatically.
In tokens, not
characters.
In tokens.
Special tokens
allowed to pass
through unescaped.
Special tokens that
raise an error if
encountered.
Basic Example
from langchain_text_splitters import TokenTextSplitter
splitter = TokenTextSplitter(encoding_name="cl100k_base", chunk_size=256, chunk_overlap=32)
chunks = splitter.split_text(long_text)
Production-Grade Example
splitter = TokenTextSplitter(
model_name="gpt-4o-mini",
chunk_size=800,
chunk_overlap=100,
)
docs = splitter.split_documents(loaded_docs)
# Guarantees no chunk exceeds 800 tokens for the embedding call downstream.
Advantages / Limitations
Advantages: exact token budgeting; no risk of an embedding call silently truncating a chunk.
Limitations: zero structural awareness — chunk boundaries can land inside a word (from
16
the tokenizer’s perspective) or mid-sentence, hurting retrieval precision and readability of
returned snippets.
Best Practices
Prefer RecursiveCharacterTextSplitter.from_tiktoken_encoder(...)
for most RAG
pipelines — you get token-accurate sizing and separator-aware splitting. Use TokenTextSplitter directly only when you explicitly want pure token slicing (e.g., pre-chunking
for a summarization map-reduce over arbitrary long text where boundary quality doesn’t
matter).
5.4 SentenceTransformersTokenTextSplitter
Module: sentence_transformers.py | Inherits: TextSplitter
Purpose
Like TokenTextSplitter, but tokenizes using a sentence-transformers model’s own tokenizer
— so chunk_size maps exactly to that embedding model’s token limit (critical for models like
all-MiniLM-L6-v2, whose limit is a comparatively small 256 tokens).
Constructor Parameters
Parameter
Type
Default
Notes
model_name
str
chunk_overlap
int
"sentencetransformers/allmpnet-base-v2"
50
tokens_per_chunk
Optional[int]
None
Any sentencetransformers model
id.
In tokens of the
chosen model’s
tokenizer.
Defaults to the
model’s max
sequence length if
unset.
Example
from langchain_text_splitters import SentenceTransformersTokenTextSplitter
splitter = SentenceTransformersTokenTextSplitter(
model_name="sentence-transformers/all-MiniLM-L6-v2",
chunk_overlap=20,
)
chunks = splitter.split_text(document_text)
# Every chunk is guaranteed to fit the embedding model's 256-token window.
Best Practices
Always use this (or from_huggingface_tokenizer) rather than a generic character-based
chunk_size guess when embedding with an open-source sentence-transformers model
17
on-prem — this is directly applicable to your own on-premises embedding exploration, since
character-to-token ratios vary and a “safe-looking” character limit can still silently overflow
a small model’s token window.
5.5 Markdown Splitters
5.5.1 MarkdownTextSplitter
Module: markdown.py | Inherits: RecursiveCharacterTextSplitter
A thin preset: RecursiveCharacterTextSplitter with a Markdown-appropriate separator list
(headers, code fences, lists, blank lines) baked in. Behaves exactly like RecursiveCharacterTextSplitter otherwise.
from langchain_text_splitters import MarkdownTextSplitter
splitter = MarkdownTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_text(readme_content)
5.5.2 MarkdownHeaderTextSplitter
Module:
markdown.py | Extends:
TextSplitter)
BaseDocumentTransformer-compatible interface (not
Purpose Splits Markdown on header boundaries (#, ##, ###, …) rather than on length,
and attaches the header hierarchy to each chunk’s metadata — enabling “breadcrumb” style
retrieval and display.
Constructor Parameters
Parameter
Type
Default
Notes
headers_to_split_on
List[Tuple[str,
str]]
required
e.g. [("#", "Header
1"), ("##", "Header
2")] — markdown
return_each_line
bool
False
strip_headers
bool
True
symbol → metadata
key.
If True, returns one
Document per line
instead of per
section.
Whether header text
is removed from
page_content (it’s
still available in
metadata).
from langchain_text_splitters import MarkdownHeaderTextSplitter
headers_to_split_on = [("#", "Header 1"), ("##", "Header 2"), ("###", "Header 3")]
splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on)
docs = splitter.split_text(markdown_doc)
18
for d in docs[:3]:
print(d.metadata)
# {'Header 1': 'Introduction', 'Header 2': 'Setup'}
print(d.page_content[:80])
Example
Production Pattern — Two-Stage Split A very common and highly recommended production pattern: split on headers first (structure), then re-split any oversized section with
RecursiveCharacterTextSplitter (length safety net).
from langchain_text_splitters import MarkdownHeaderTextSplitter, RecursiveCharacterTextSplitter
header_splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=[("#", "H1"), ("##", "H2")]
)
sections = header_splitter.split_text(long_markdown)
length_splitter = RecursiveCharacterTextSplitter(chunk_size=600, chunk_overlap=80)
final_chunks = length_splitter.split_documents(sections)
Best Practices / Limitations Best practice: always pair this with a length-bounded second
pass in production — a single Markdown section under one header can still be arbitrarily long.
Limitation: assumes well-formed, consistently-leveled Markdown; skipped header levels or
malformed syntax degrade the metadata hierarchy.
5.5.3 ExperimentalMarkdownSyntaxTextSplitter
Module: markdown.py
A newer, more syntax-aware Markdown splitter (marked experimental — API may change)
that additionally understands code fences, tables, and nested lists better than the header-only
splitter, while retaining the same headers_to_split_on configuration style.
from langchain_text_splitters import ExperimentalMarkdownSyntaxTextSplitter
headers_to_split_on = [("#", "Header 1"), ("##", "Header 2")]
splitter = ExperimentalMarkdownSyntaxTextSplitter(headers_to_split_on=headers_to_split_on)
chunks = splitter.split_text(markdown_doc)
Caution: because this is explicitly labeled experimental by the LangChain team, pin your
langchain_text_splitters version in production if you depend on its exact output shape.
5.6 HTML Splitters
5.6.1 HTMLHeaderTextSplitter
Module: html.py
Purpose The HTML analogue of MarkdownHeaderTextSplitter — splits on <h1>–<h6> tags
and attaches the header path as metadata. Ideal for scraped documentation pages, wikis, and
knowledge-base exports.
19
Constructor Parameters
Parameter
Type
Default
Notes
headers_to_split_on
List[Tuple[str,
str]]
required
e.g., [("h1",
bool
False
"Section"), ("h2",
"Subsection")].
Return one Document
return_each_element
per HTML element
rather than per
section.
from langchain_text_splitters import HTMLHeaderTextSplitter
html_string = """
<html><body>
<h1>CPM Pulse Overview</h1>
<p>Introductory text about the platform.</p>
<h2>Data Model</h2>
<p>Details about the star schema.</p>
</body></html>
"""
splitter = HTMLHeaderTextSplitter(headers_to_split_on=[("h1", "Header 1"), ("h2", "Header 2")])
docs = splitter.split_text(html_string)
for d in docs:
print(d.metadata, "->", d.page_content[:60])
Example
5.6.2 HTMLSectionSplitter
Module: html.py
Splits HTML based on specified tags and font-size heuristics (useful for HTML exported
from Word/PDF conversion tools where semantic <h1>–<h6> tags are absent, but visual heading size is still encoded in inline styles).
from langchain_text_splitters import HTMLSectionSplitter
splitter = HTMLSectionSplitter(headers_to_split_on=[("h1", "Header 1"), ("h2", "Header 2")])
docs = splitter.split_text(exported_html)
5.6.3 HTMLSemanticPreservingSplitter
Module: html.py | Extends: BaseDocumentTransformer
Purpose The most feature-rich HTML splitter — splits by header while explicitly preserving
semantic elements intact (tables, lists, links, images, audio, video) so they are never cut
mid-element, which is a common failure mode of naive HTML chunking that breaks a <table>
across two chunks.
20
Constructor Parameters
Parameter
Type
Default
headers_to_split_on
List[Tuple[str,str]] required
max_chunk_size
int
1000
chunk_overlap
int
0
separators
Optional[List[str]]
None
elements_to_preserve Optional[List[str]]
None
Notes
Same shape as other
HTML splitters.
Length-based ceiling
applied within
sections.
Overlap between
length-bounded
sub-chunks.
Custom fallback
separators for the
length pass.
Tag names (e.g.,
["table","ul","ol"])
preserve_links /
preserve_images /
preserve_videos /
preserve_audio
custom_handlers
bool
False each
Optional[Dict[str,
Callable]]
None
stopword_removal
bool
False
normalize_text
bool
False
allowlist_tags /
Optional[List[str]]
denylist_tags
preserve_parent_metadata
bool
None
keep_separator
True
bool \| "start" \|
"end"
False
never split internally.
Keep the respective
media element
intact/represented.
Custom serialization
function per tag
name.
Optionally strip
stopwords from
output text.
Basic
whitespace/casing
normalization.
Fine-grained tag
inclusion/exclusion.
Carries
parent-element
metadata into child
chunks.
Same semantics as
TextSplitter.
from langchain_text_splitters import HTMLSemanticPreservingSplitter
splitter = HTMLSemanticPreservingSplitter(
headers_to_split_on=[("h1", "Header 1"), ("h2", "Header 2")],
max_chunk_size=800,
elements_to_preserve=["table", "ul", "ol"],
preserve_links=True,
)
docs = splitter.split_text(scraped_docs_page_html)
Example
21
Best Practices This is the right choice whenever your HTML source contains tables you
need intact for a RAG answer to make sense (e.g., pricing tables, spec sheets) — a table
split across two chunks is nearly useless to a retriever and often actively misleading to an
LLM asked to reason over it.
5.7 LatexTextSplitter
Module: latex.py | Inherits: RecursiveCharacterTextSplitter
A preset separator list tuned for LaTeX documents — splits preferentially on \chapter, \section, \subsection, \begin{...} environment boundaries before falling back to blank lines
and characters. Used for academic papers, technical specs authored in LaTeX.
from langchain_text_splitters import LatexTextSplitter
splitter = LatexTextSplitter(chunk_size=1000, chunk_overlap=100)
chunks = splitter.split_text(open("paper.tex").read())
5.8 Code Splitters: PythonCodeTextSplitter and Language-Based Splitting
PythonCodeTextSplitter
Module: python.py | Inherits: RecursiveCharacterTextSplitter
A preset equivalent to RecursiveCharacterTextSplitter.from_language(Language.PYTHON,
...) — splits preferring class/def boundaries.
from langchain_text_splitters import PythonCodeTextSplitter
splitter = PythonCodeTextSplitter(chunk_size=1000, chunk_overlap=150)
chunks = splitter.split_text(open("cpm_pulse_chatbot/rag_pipeline.py").read())
Methods available (inherited/overridden): __init__, split_text, split_documents, create_documents, from_language, from_huggingface_tokenizer, from_tiktoken_encoder,
get_separators_for_language (static — returns the raw separator list for any Language
without constructing a splitter, useful for inspection/debugging).
Other Languages via from_language
Every other supported language (JS, TS, Java, Go, Rust, C#, PHP, Ruby, Kotlin, Scala, Swift,
Proto, SOL, COBOL, Haskell, Elixir, PowerShell, RST, and more) is accessed through the
same RecursiveCharacterTextSplitter.from_language(Language.X, ...) call — there isn’t
a dedicated class per language beyond Python and Markdown/LaTeX, which have their own
convenience presets purely for historical/ergonomic reasons.
from langchain_text_splitters import RecursiveCharacterTextSplitter, Language
js_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.JS, chunk_size=800, chunk_overlap=100
)
22
When to Use / Not Use
Use for any RAG-over-codebase application (code search, code documentation Q&A).
Avoid for minified or auto-generated code with no meaningful structure — falls back to
near-arbitrary character splits with little benefit over RecursiveCharacterTextSplitter
defaults.
5.9 NLTKTextSplitter
Module: nltk.py | Inherits: TextSplitter | Requires: pip install nltk
Purpose
Splits on true sentence boundaries using NLTK’s Punkt sentence tokenizer, rather than a
naive ". " regex — correctly handles abbreviations (“Dr.”, “e.g.”, “U.S.”) that naive splitting
mangles.
Constructor Parameters
Parameter
Type
Default
Notes
separator
str
"\n\n"
language
str
"english"
Separator
re-inserted between
merged sentences.
NLTK language
model to use for
tokenization.
(+ standard
TextSplitter
params)
from langchain_text_splitters import NLTKTextSplitter
splitter = NLTKTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_text(prose_text)
Common mistake: forgetting to run nltk.download("punkt") (or punkt_tab in newer NLTK
versions) before first use — raises a LookupError with a download hint at runtime.
5.10 SpacyTextSplitter
Module: spacy.py | Inherits: TextSplitter | Requires: pip install spacy + a downloaded
model
Purpose
Same goal as NLTKTextSplitter (true sentence-boundary splitting) but backed by spaCy’s
statistical/rule-based pipeline, which tends to be more robust on messy real-world text (mixed
punctuation, informal writing) at the cost of being slower and requiring a downloaded language model.
23
Constructor Parameters
Parameter
Type
Default
Notes
pipeline
max_length
str
int
"en_core_web_sm"
1_000_000
spaCy model name.
spaCy’s own internal
document length cap
— must be raised for
very large
documents.
(+ standard
TextSplitter
params)
from langchain_text_splitters import SpacyTextSplitter
splitter = SpacyTextSplitter(pipeline="en_core_web_sm", chunk_size=500)
chunks = splitter.split_text(prose_text)
NLTK vs. spaCy — When to Choose Which
Choose NLTK for speed and a lighter dependency footprint when text is reasonably clean.
Choose spaCy when accuracy on messy, informal, or domain-specific text matters more than
raw throughput, and you can afford the larger model download and slower per-document
cost.
5.11 KonlpyTextSplitter
Module: konlpy.py | Requires: pip install konlpy
A specialized sentence splitter for Korean text, using the KoNLPy morphological analyzer
instead of whitespace/punctuation heuristics that don’t transfer well to Korean’s agglutinative
grammar. Included for completeness; only relevant if you process Korean-language content.
5.12 RecursiveJsonSplitter
Module: json.py
Purpose
Splits nested JSON while preserving structural validity — every output chunk is itself
valid, parseable JSON (or a valid fragment), never a blindly truncated string that breaks
brace/bracket matching.
Constructor Parameters
24
Parameter
Type
Default
Notes
max_chunk_size
int
2000
min_chunk_size
Optional[int]
Maximum serialized
character length per
chunk.
Small fragments
below this are
merged upward
where possible.
None
(≈max_chunk_size 200)
Key Methods
split_json(json_data: dict, convert_lists: bool = False) -> List[dict] Returns a list
of Python dicts (not yet serialized). convert_lists=True converts JSON arrays into {index:
value} dicts internally so list items can be split independently — useful for very large arrays.
split_text(json_data: dict, convert_lists: bool = False, ensure_ascii: bool = True)
-> List[str] Returns JSON-serialized strings — the version you typically embed.
create_documents(texts: List[dict], ...) -> List[Document]
base class, but texts here is a list of JSON dicts, not raw strings.
Same semantics as the
Example
from langchain_text_splitters import RecursiveJsonSplitter
import requests
json_data = requests.get("https://api.smith.langchain.com/openapi.json").json()
splitter = RecursiveJsonSplitter(max_chunk_size=250)
json_chunks = splitter.split_json(json_data=json_data)
text_chunks = splitter.split_text(json_data=json_data)
docs = splitter.create_documents(texts=[json_data])
# -> list[dict]
# -> list[str], embeddable
# -> list[Document]
Production Example — API Schema RAG
splitter = RecursiveJsonSplitter(max_chunk_size=500, min_chunk_size=100)
docs = splitter.create_documents(texts=[api_openapi_spec], metadatas=[{"source": "openapi.json"
vectorstore = Chroma.from_documents(docs, embeddings)
# Enables natural-language Q&A over a large REST API spec without ever
# emitting a syntactically broken JSON fragment.
Advantages / Limitations
Advantages: the only splitter in the package that guarantees structural (syntactic) validity
of every chunk for a nested format. Limitations: chunk sizes are approximate (bounded by
serialized length, not exact); deeply nested single keys with enormous values can still force
an oversized chunk since a key/value pair is treated as atomic.
25
Best Practices
Directly applicable to your CPMPulse_v2 metadata-export work — if you ever serialize measure/table metadata to JSON for a RAG index (as an alternative or supplement to the ChromaDB synonym pipeline you built), RecursiveJsonSplitter is the correct tool rather than a
generic character splitter, because it guarantees every chunk stays valid, parseable JSON
your downstream code can json.loads() safely.
5.13 JSFrameworkTextSplitter
Module: jsx.py | Inherits: RecursiveCharacterTextSplitter
Purpose
Handles React (JSX), Vue, and Svelte component source files — splits with awareness of
component boundaries (function Component() {...}, <template>/<script>/<style> blocks
in Vue/Svelte) rather than treating them as plain JS/HTML text.
from langchain_text_splitters import JSFrameworkTextSplitter
splitter = JSFrameworkTextSplitter(chunk_size=1000, chunk_overlap=100)
chunks = splitter.split_text(open("Dashboard.jsx").read())
Niche but valuable for RAG-over-frontend-codebase tools (e.g., an internal “explain this component” assistant).
26
6. Comparison Tables
6.1 Feature Comparison
Preserves
Metadata
Hierarchy
Guarantees
Valid
Sub-Structure
Extra
Dependency
CharacterTextSplitter
No
Yes (factory)
RecursiveCharacterTextSplitter
Partial
Yes (factory)
No
No
No
No
none
none
(separator
hierarchy)
TokenTextSplitter
No
Yes (native)
SentenceTransformersTokenTextSplitter
No
Yes (native)
No
No
No
No
tiktoken
sentencetransformers
MarkdownHeaderTextSplitter
Yes
No (pair with
Yes
Partial
none
2nd pass)
ExperimentalMarkdownSyntaxTextSplitter
Yes
No
HTMLHeaderTextSplitter
Yes
No
HTMLSectionSplitter
Yes
No
HTMLSemanticPreservingSplitter
Yes
No
Yes
Yes
Yes
Yes
Splitter
StructureAware
Token-Aware
Option
RecursiveJsonSplitter
Yes
No
Partial
Yes (syntax)
PythonCodeTextSplitter
Yes (factory)
No
Partial
No
No
Yes
(tables/lists)
Yes (always
valid JSON)
Partial
none
No
No
Yes (sentence)
nltk
No
No
Yes (sentence)
spacy
Yes
(inherited)
No
Partial
none
lxml/bs4
lxml/bs4
lxml/bs4
none
none
/
from_language
NLTKTextSplitter
Sentence-
level
SpacyTextSplitter
Sentencelevel
JSFrameworkTextSplitter
Yes
(component)
6.2 Performance Comparison (Qualitative)
Splitter
Relative Speed
Memory Footprint
CharacterTextSplitter Fastest
Minimal
RecursiveCharacterTextSplitter
Fast
TokenTextSplitter
Fast (tiktoken is
Minimal
Low
Scales to Multi-GB
Corpora
Yes
(streaming-friendly)
Yes
Yes
C-optimized)
MarkdownHeaderTextSplitter
Moderate (parsing
/ HTML variants
overhead)
RecursiveJsonSplitter Moderate (recursive
dict walk)
NLTKTextSplitter
Slower (model
inference per
sentence)
Moderate (DOM/tree
parsing)
Moderate (holds
parsed JSON in
memory)
Low-Moderate
27
Yes, with per-doc
streaming
Caution — very large
single JSON
documents load fully
into memory first
Yes, but
throughput-bound
Splitter
Relative Speed
Memory Footprint
Scales to Multi-GB
Corpora
SpacyTextSplitter
Slowest of the group
Moderate-High
(loaded language
model)
Needs
batching/nlp.pipe
for large corpora
6.3 Use-Case Mapping
Use Case
Recommended Splitter
General prose RAG (default choice)
RecursiveCharacterTextSplitter with
from_tiktoken_encoder
MarkdownHeaderTextSplitter or
HTMLHeaderTextSplitter + length safety net
HTMLSemanticPreservingSplitter
Technical documentation / wiki with headers
Scraped web pages with tables/lists that
must stay intact
Codebase Q&A / code search
REST/GraphQL API schemas, config files
Small on-prem embedding model (e.g.,
MiniLM)
Legal/medical prose needing precise
sentence boundaries
React/Vue/Svelte component RAG
LaTeX academic papers
Korean-language corpora
RecursiveCharacterTextSplitter.from_language(...)
or PythonCodeTextSplitter
RecursiveJsonSplitter
SentenceTransformersTokenTextSplitter
SpacyTextSplitter (accuracy) or
NLTKTextSplitter (speed)
JSFrameworkTextSplitter
LatexTextSplitter
KonlpyTextSplitter
28
7. Chunking Strategy Deep Dive
7.1 Fixed Chunking
Theory: Cut text every N units regardless of content. Implementation: CharacterTextSplitter with a rarely-matching separator, or TokenTextSplitter.
Advantages:
predictable chunk count and size; trivial to reason about cost. Drawbacks: frequently cuts
mid-sentence or mid-idea, hurting both embedding quality and human readability of retrieved
snippets. Best for: homogeneous, low-structure text where boundary quality matters less
than uniformity (e.g., raw sensor logs, transcripts already segmented upstream).
7.2 Recursive Chunking
Theory: Prefer high-level structural boundaries, fall back progressively. Implementation:
RecursiveCharacterTextSplitter and its presets. Advantages: the best default trade-off
between simplicity and semantic quality; language- and format-aware presets exist for the
most common needs. Drawbacks: still purely syntactic — no understanding of meaning, so
a topic shift mid-paragraph is invisible to it. Best for: the majority of general-purpose RAG
ingestion pipelines; start here unless you have a specific reason not to.
7.3 Semantic Chunking
Theory: Group sentences by embedding similarity — a chunk boundary is placed wherever consecutive sentences’ embeddings diverge past a threshold, so each chunk is topically coherent regardless of length. Implementation: not in langchain_text_splitters
— lives in langchain_experimental.text_splitter.SemanticChunker, which wraps an embedding model to make the split decision. Advantages: chunks map to actual topic boundaries,
often measurably improving retrieval precision on heterogeneous documents. Drawbacks:
requires an embedding call per candidate boundary at ingestion time (cost + latency); nondeterministic chunk sizes complicate downstream token budgeting; experimental/less battletested API. Best for: high-value corpora where retrieval quality justifies the extra ingestion
cost (e.g., legal contracts, medical literature) — not typically worth it for high-volume, lowvalue text.
7.4 Token-Based Chunking
Theory: Measure and cut strictly by model tokens. Implementation: TokenTextSplitter,
SentenceTransformersTokenTextSplitter, or any splitter’s from_tiktoken_encoder/from_huggingface_token
factory. Advantages: the only approach that gives an exact guarantee against embeddingmodel truncation or LLM context overflow. Drawbacks: on its own (without a separator
hierarchy) it has zero regard for meaning. Best for: as a measurement layer combined
with recursive/structural splitting — i.e., almost always used as RecursiveCharacterTextSplitter.from_tiktoken_encoder(...) rather than raw TokenTextSplitter, except
when boundary quality genuinely doesn’t matter.
7.5 Structure-Aware Chunking
Theory: Respect the source format’s own explicit structure (headers, tags, JSON keys,
code syntax) as the primary split signal, and propagate that structure into chunk
metadata.
Implementation:
MarkdownHeaderTextSplitter, HTMLHeaderTextSplitter/HTMLSectionSplitter/HTMLSemanticPreservingSplitter,
RecursiveJsonSplitter,
language-mode RecursiveCharacterTextSplitter. Advantages: produces the most humaninterpretable and citation-friendly chunks; metadata enables hybrid retrieval (filter by
29
section/header before or alongside vector search). Drawbacks: requires well-formed source
structure; a single section can still be arbitrarily large, so it should almost always be paired
with a length-bounded second pass. Best for: documentation sites, wikis, structured reports, API specs, and codebases — anywhere the source format already encodes meaningful
hierarchy.
30
8. Production Recipes
8.1 PDF Ingestion Pipeline
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
def ingest_pdf(path: str, chunk_size=500, chunk_overlap=64):
pages = PyPDFLoader(path).load()
# one Document per page
splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
encoding_name="cl100k_base",
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
add_start_index=True,
)
return splitter.split_documents(pages)
8.2 RAG Application (Hybrid Structure + Length)
from langchain_text_splitters import MarkdownHeaderTextSplitter, RecursiveCharacterTextSplitter
def ingest_markdown_kb(markdown_text: str):
structural = MarkdownHeaderTextSplitter(
headers_to_split_on=[("#", "H1"), ("##", "H2"), ("###", "H3")]
).split_text(markdown_text)
safety_net = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=400, chunk_overlap=50
)
return safety_net.split_documents(structural)
# metadata survives both passes
8.3 Chatbot Ingestion (Multi-Format Router)
from pathlib import Path
from langchain_text_splitters import (
RecursiveCharacterTextSplitter, MarkdownHeaderTextSplitter,
HTMLHeaderTextSplitter, RecursiveJsonSplitter,
)
import json
def split_by_extension(path: Path, text: str):
if path.suffix == ".md":
return MarkdownHeaderTextSplitter(
headers_to_split_on=[("#", "H1"), ("##", "H2")]
).split_text(text)
if path.suffix in (".html", ".htm"):
return HTMLHeaderTextSplitter(
headers_to_split_on=[("h1", "H1"), ("h2", "H2")]
).split_text(text)
if path.suffix == ".json":
return RecursiveJsonSplitter(max_chunk_size=500).create_documents(
31
texts=[json.loads(text)]
)
# default fallback
return RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=500, chunk_overlap=60
).create_documents([text])
8.4 Knowledge Management System — Preserving Tables
from langchain_text_splitters import HTMLSemanticPreservingSplitter
splitter = HTMLSemanticPreservingSplitter(
headers_to_split_on=[("h1", "H1"), ("h2", "H2")],
max_chunk_size=700,
elements_to_preserve=["table", "ul", "ol"],
preserve_links=True,
preserve_parent_metadata=True,
)
docs = splitter.split_text(kb_article_html)
8.5 Enterprise Search over Codebase + Metadata (CPMPulse_v2-style)
from langchain_text_splitters import RecursiveCharacterTextSplitter, Language, RecursiveJsonSpl
# Code search
code_splitter = RecursiveCharacterTextSplitter.from_language(Language.PYTHON, chunk_size=800)
code_docs = code_splitter.create_documents([Path("pipeline.py").read_text()])
# Measure/table metadata search (analogous to your synonym -> ChromaDB pipeline)
metadata_splitter = RecursiveJsonSplitter(max_chunk_size=400)
metadata_docs = metadata_splitter.create_documents(texts=[measure_metadata_dict])
32
9. Troubleshooting Guide
9.1 Common Errors
Symptom
Likely Cause
Fix
ValueError: Got a larger
chunk overlap than chunk
size
chunk_overlap >=
chunk_size
Set chunk_overlap to roughly
10–20% of chunk_size.
Chunks silently exceed
Using
chunk_size
CharacterTextSplitter with
LookupError: Resource
punkt not found
a separator that rarely
matches
NLTKTextSplitter used
before
Switch to RecursiveCharacterTextSplitter, which
recurses into smaller
separators.
Run the download once at
environment setup, not
per-request.
Increase max_length on
SpacyTextSplitter, or
pre-chunk with Recur-
nltk.download("punkt")
spaCy ValueError: [E088]
Text of length N exceeds
maximum
Embedding API returns a
truncation warning
RecursiveJsonSplitter
output isn’t valid JSON when
concatenated
Retrieved chunks read as
“cut off mid-thought”
HTML tables appear broken
across two chunks
Document longer than
spaCy’s default
nlp.max_length (1,000,000
chars)
Chunk sized by characters,
not the embedding model’s
actual tokenizer
Expected — chunks are
independently valid, not a
partitioned stream
chunk_overlap too low, or
splitting purely on character
count with no structure
awareness
Using
HTMLHeaderTextSplitter
(header-only) instead of the
semantic-preserving variant
siveCharacterTextSplitter
first.
Use from_tiktoken_encoder /
from_huggingface_tokenizer
/ SentenceTransformersTokenTextSplitter.
Treat each chunk as a
standalone JSON document,
not a stream to reassemble.
Increase overlap; switch to a
structure-aware splitter
where the format supports it.
Switch to HTMLSemanticPreservingSplitter with
elements_to_preserve=["table"].
9.2 Debugging Techniques
• Inspect actual chunk sizes: [len(c) for c in chunks] (or apply your real
length_function) to spot outliers before they hit an embedding API.
• Visualize boundaries: print the last 30 and first 30 characters of adjacent chunks to
eyeball whether the overlap is meaningfully preserving context.
• Unit-test separator hierarchies: for RecursiveCharacterTextSplitter.from_language,
call the static get_separators_for_language(language) to inspect the exact list being
used without constructing a splitter.
9.3 Performance Tuning
• Batch spaCy calls with nlp.pipe() under the hood is not exposed directly by SpacyTextSplitter, so for very large corpora, prefer chunking with RecursiveCharacterTextSplitter first and only running spaCy sentence segmentation on the smaller resulting pieces if precision is critical.
33
• For very large JSON documents, consider streaming/pre-partitioning at the top-level key
before calling RecursiveJsonSplitter, since it loads the full parsed structure into memory.
9.4 Memory Optimization
Process documents one at a time through split_documents rather than concatenating an entire corpus into one giant string first — splitters do not require the whole corpus in memory
simultaneously, only one document at a time.
9.5 Token Overflow Issues
Character-based chunk_size is a heuristic, not a guarantee, against token overflow — nonEnglish text and code can run well under 4 characters/token. Always validate against the
actual tokenizer of your embedding/LLM provider for anything token-limit-sensitive.
9.6 Chunk Overlap Issues
Overlap that’s too small loses cross-boundary context (a pronoun in chunk 2 referring to a
noun that was the last word of chunk 1). Overlap that’s too large wastes embedding budget
and can inflate near-duplicate retrieval results. A common, reasonable starting point is 10–
20% of chunk_size, tuned empirically against your actual retrieval evaluation set.
34
10. Interview Questions & Answers
Beginner Level
Q1. What’s the difference between CharacterTextSplitter and RecursiveCharacterTextSplitter? A: CharacterTextSplitter splits on a single separator and does not recurse —
an oversized fragment between separators is emitted as-is, potentially exceeding chunk_size.
RecursiveCharacterTextSplitter tries an ordered list of separators, recursing into smaller
ones for any fragment still too large, guaranteeing (barring a single unsplittable token) that
output respects chunk_size.
Q2. What does chunk_overlap do, and why would you want it greater than zero? A: It
repeats a number of trailing units from one chunk at the start of the next, preserving context
across the boundary — e.g., so a sentence’s subject in chunk N and its resolution in chunk
N+1 aren’t fully separated from each other in retrieval.
Q3. What’s the difference between split_text and split_documents? A: split_text
operates on a raw string and returns List[str]. split_documents operates on Document objects, splits their page_content, and returns List[Document] with metadata preserved from
the source document.
Intermediate Level
Q4. Why would you use from_tiktoken_encoder instead of a plain character-based
chunk_size? A: Because embedding models and LLMs bill/limit by tokens, not characters,
and the character-to-token ratio varies by language and content type (code vs. prose, English
vs. CJK languages). Token-based sizing gives an accurate budget guarantee; character-based
sizing is only an approximation.
Q5. When would MarkdownHeaderTextSplitter alone be insufficient, and what’s the
standard fix? A: A single section under one header can still be arbitrarily long — the
splitter has no length ceiling. Standard fix: run RecursiveCharacterTextSplitter (ideally
from_tiktoken_encoder) as a second pass over the header-split output via split_documents,
so metadata survives while length is bounded.
Q6. Why does RecursiveJsonSplitter guarantee valid output while a naive character
splitter on a JSON string would not? A: It walks the parsed JSON structure recursively and
only cuts at key/value boundaries, re-serializing each chunk as its own syntactically complete
JSON fragment — it never truncates in the middle of a brace, bracket, or string literal the
way a length-only splitter over the raw serialized string could.
Advanced Level
Q7. Compare token-based chunking, recursive character chunking, and semantic
chunking on retrieval quality vs. cost trade-offs. A: Token-based chunking optimizes
purely for not exceeding a model’s limit — cheapest to compute, worst for boundary quality. Recursive character chunking adds separator-hierarchy awareness at negligible extra
cost, meaningfully improving boundary quality for structured/paragraphed text. Semantic
chunking (outside this package, in langchain_experimental) optimizes directly for topical
coherence using embedding similarity, typically the best retrieval quality on heterogeneous
text, but at the cost of an embedding call per candidate boundary during ingestion and nondeterministic chunk sizing that complicates downstream token budgeting.
Q8. How would you chunk a large HTML page containing pricing tables for
a RAG assistant, and why?
A: Use HTMLSemanticPreservingSplitter with elements_to_preserve=["table"] and header-based splitting for section boundaries. A table
35
split across chunks by a length-only splitter loses row/column alignment context, making
it nearly impossible for an LLM to answer questions correctly about it; preserving it intact
(even if it makes that one chunk larger than others) is essential for correctness.
Q9. What’s the practical difference between NLTKTextSplitter and SpacyTextSplitter, and how would you choose between them for a legal-document RAG system? A:
Both aim for true sentence-boundary splitting rather than naive punctuation regex. spaCy’s
statistical pipeline tends to handle irregular punctuation and domain-specific abbreviations
(common in legal text — “§”, “Inc.”, cross-references) more robustly than NLTK’s Punkt tokenizer, at the cost of a heavier model and slower throughput. For a legal-document RAG
system where sentence-boundary precision materially affects retrieval and citation correctness, spaCy’s added robustness usually justifies its cost; NLTK remains reasonable for cleaner,
less idiosyncratic prose at higher throughput.
Architect Level
Q10. Design an ingestion pipeline for a large, heterogeneous enterprise knowledge
base (Markdown wikis, scraped HTML docs, PDFs, JSON API specs, and a source
code repository). What splitter strategy would you use for each, and how would you
unify them for a single retriever? A: Route by source type at ingestion: Markdown wikis
→ MarkdownHeaderTextSplitter + token-aware RecursiveCharacterTextSplitter safety net;
scraped HTML → HTMLSemanticPreservingSplitter to protect tables/lists; PDFs → page-level
loader output through RecursiveCharacterTextSplitter.from_tiktoken_encoder; JSON
API specs → RecursiveJsonSplitter for structural validity; source code → RecursiveCharacterTextSplitter.from_language per detected language. Unify by (a) standardizing all
outputs to Document objects with a consistent metadata schema (source_type, source_path,
header/section path where available, start_index), (b) sizing every splitter’s chunk_size
against the same embedding model’s actual tokenizer so vectors are comparably dense
across source types, and (c) storing source-type and section metadata alongside vectors to
support metadata-filtered hybrid retrieval, not just pure vector similarity.
Q11.
What are the failure modes of relying solely on character-count-based
chunk_size across a multilingual corpus, and how would you mitigate them at the
architecture level? A: Character-to-token ratio varies substantially across languages (e.g.,
CJK characters often map close to 1:1 or 1:2 with tokens, versus ~4:1 for English), so a single
character-based chunk_size will produce wildly inconsistent actual token counts across
languages — over-stuffing embedding calls for some languages and under-utilizing budget
for others. Mitigation: size every splitter using the target embedding/LLM model’s real
tokenizer (from_tiktoken_encoder / from_huggingface_tokenizer) rather than raw character
counts, and, if the corpus mixes languages within single documents, consider per-language
length functions or at minimum validate chunk token counts post-hoc as part of the ingestion
pipeline’s QA step.
36
11. Best Practices, Anti-Patterns & Cheatsheet
11.1 Best Practices Checklist
□ Default to RecursiveCharacterTextSplitter unless the source format has strong explicit
structure worth preserving.
□ Size chunks against the actual tokenizer of your embedding/LLM model, not raw character count.
□ Set chunk_overlap to roughly 10–20% of chunk_size, then tune against a real retrieval
evaluation set.
□ For structured formats (Markdown/HTML/JSON), split on structure first, then apply a
length-bounded second pass as a safety net.
□ Preserve tables and lists intact when the source is HTML and content includes tabular
data — use HTMLSemanticPreservingSplitter.
□ Always use split_documents, not manual re-wrapping, to keep source metadata attached
to chunks.
□ For code, use from_language/PythonCodeTextSplitter rather than a generic prose splitter.
□ Validate chunk sizes empirically (log distribution of chunk lengths) before shipping an
ingestion pipeline to production.
□ Pin the langchain_text_splitters version if you depend on Experimental* classes’ exact
output shape.
11.2 Production Recommendations
Batch-process documents through the pipeline one at a time to control memory; log both
chunk count and chunk-size distribution per ingestion run as a regression signal; store
start_index/header metadata to support citation and “show me the source” UX; re-run a
small held-out QA/retrieval evaluation whenever you change chunk_size, chunk_overlap, or
splitter type, since these changes silently reshape retrieval behavior without any code-level
error.
11.3 Design Patterns
• Two-Pass Structural + Length Split — structure splitter first, length-bounded splitter
second (see §8.2).
• Format Router — dispatch to a format-specific splitter by file extension/MIME type,
falling back to RecursiveCharacterTextSplitter (see §8.3).
• Tokenizer-Matched Sizing — always construct splitters via the factory method matching your embedding model’s actual tokenizer.
11.4 Anti-Patterns
• [avoid] Using CharacterTextSplitter on unstructured prose and assuming chunk_size
is a hard guarantee.
• [avoid] Picking an arbitrary character chunk_size (e.g., “1000”) without checking what
that means in actual tokens for your embedding model.
• [avoid] Splitting HTML with a header-only splitter when the content contains tables that
must remain intact.
• [avoid] Setting chunk_overlap to zero for narrative/prose content and being surprised
retrieval loses cross-sentence context.
• [avoid] Treating RecursiveJsonSplitter chunks as a reassemblable stream rather than
independently valid JSON documents.
37
• [avoid] Shipping a change to chunk_size/chunk_overlap to production without revalidating retrieval quality on a test set.
11.5 Summary Cheatsheet
Need
Reach For
Safe general-purpose default
Guarantee token-budget compliance
RecursiveCharacterTextSplitter.from_tiktoken_encoder(
from_tiktoken_encoder /
from_huggingface_tokenizer /
SentenceTransformersTokenTextSplitter
MarkdownHeaderTextSplitter /
HTMLHeaderTextSplitter
HTMLSemanticPreservingSplitter
RecursiveCharacterTextSplitter.from_language(Language
RecursiveJsonSplitter
SpacyTextSplitter (accuracy) /
NLTKTextSplitter (speed)
JSFrameworkTextSplitter
LatexTextSplitter
KonlpyTextSplitter
Preserve document structure as metadata
Preserve tables/lists intact
Split source code
Split valid nested JSON
True sentence boundaries
React/Vue/Svelte components
LaTeX documents
Korean text
11.6 Quick Reference — Default Parameter Values
Parameter
Base TextSplitter Default
chunk_size
chunk_overlap
length_function
keep_separator
4000
200
len (characters)
False (True for
add_start_index
strip_whitespace
RecursiveCharacterTextSplitter)
False
True
End of reference document. This guide reflects the module layout, class set, and constructor
signatures of langchain_text_splitters as of the current LangChain release line; always
cross-check exact parameter names against your installed version with help(SplitterClass)
before relying on it in production, since the Experimental* classes in particular are explicitly
subject to change.
38
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )