Document Loaders and Text Splitters
Ingestion decides what retrieval can ever find. Loaders turn sources into `Document` objects (text in `page_content`, provenance in `metadata`), and splitters cut them into chunks that are small enough to retrieve precisely and fit the model, while copying metadata onto every chunk. Know the `BaseLoader` contract, how the recursive splitter really cuts and overlaps, how to size by tokens, and when to split by structure instead of size.
Key points
- 1
Document(page_content, metadata={}, id=None)fromlangchain_core.documents.metadatais a free-form dict (source,page,row, anything you add) used later for filtering and citations;idis an optional string. - 2
Every loader implements
BaseLoader:load(),lazy_load(),aload(),alazy_load()(and the legacyload_and_split(), which callsload()and should be treated as deprecated). Implementlazy_loadas a generator; the defaultload()islist(self.lazy_load())and the defaultalazy_load()runs the sync generator in an executor. If a subclass overrides onlyload(),lazy_load()falls back toiter(self.load()), which is not lazy. - 3
Concrete loaders:
PyPDFLoader(langchain-community; defaultmode="page"gives oneDocumentper page withsource,total_pages, zero-basedpageandpage_label;mode="single"returns one document;extraction_mode="layout"is available),CSVLoader(oneDocumentper row ascolumn: valuelines, metadatasourceandrow),DirectoryLoader(path, glob=..., loader_cls=...),WebBaseLoader. Layout-aware options for hard PDFs include Unstructured, Docling and PyMuPDF/PDFPlumber loaders. - 4
Splitters come from
langchain-text-splitters.TextSplitterdefaults:chunk_size=4000,chunk_overlap=200,length_function=len,add_start_index=False,strip_whitespace=True. An overlap larger than the chunk size raisesValueErrorat construction. Splitters are document transformers, not Runnables (noinvoke). - 5
Entry points:
split_text(str) -> list[str];create_documents(texts, metadatas=None) -> list[Document];split_documents(docs) -> list[Document], which deep-copies each parent's metadata onto its chunks. Chunks getid=None; assign deterministic ids yourself if you upsert or delete by id. - 6
RecursiveCharacterTextSplitteris the recommended default: separators["\n\n", "\n", " ", ""], cut on the first separator present, recursively re-split any piece still too big with the next one, then merge pieces up tochunk_size, carrying trailing pieces up tochunk_overlapinto the next chunk.CharacterTextSplitterhas one separator (default"\n\n"), so an oversized piece stays oversized and only logs a warning. - 7
keep_separator: the recursive splitter defaults toTrue(same as"start", separator begins the next piece);"end"attaches it to the previous piece;Falsedrops it (theCharacterTextSplitterdefault).is_separator_regex=Truetreats separators as regexes, so a bare.matches every character. - 8
add_start_index=Truestores each chunk's character offset in the parent text asmetadata["start_index"], correct even with overlap; use it to highlight the cited passage. - 9
Token sizing:
length_functionsets the unit ofchunk_size.CharacterTextSplitter.from_tiktoken_encodercan exceed the token limit;RecursiveCharacterTextSplitter.from_tiktoken_encoderenforces it;TokenTextSplitterslices tokens directly and can break a multi-byte character (avoid for Chinese/Japanese).from_huggingface_tokenizerandSentenceTransformersTokenTextSplittersize chunks for a specific embedding model's window. The tiktoken options need thetiktokenpackage. - 10
Structure-aware splitting:
MarkdownHeaderTextSplitter(headers_to_split_on=[("#", "h1"), ...], strip_headers=True, return_each_line=False)puts the header path in metadata, ignores#lines inside code fences, has nochunk_sizeand nosplit_documents; follow it withRecursiveCharacterTextSplitter.split_documentsto cap size (overlap stays within a section). HTML:HTMLHeaderTextSplitter,HTMLSectionSplitter,HTMLSemanticPreservingSplitter(keeps tables and lists; needsbs4).RecursiveJsonSplitterfor nested JSON. Code:RecursiveCharacterTextSplitter.from_language(Language.PYTHON, ...)uses regex separators such as\nclassand\ndef(about 28 languages). - 11
Semantic chunking:
SemanticChunker(inlangchain_experimental) embeds sentence groups (buffer_size) and breaks where cosine distance between neighbours exceeds a threshold (breakpoint_threshold_typepercentile 95 by default, or standard_deviation, interquartile, gradient, ornumber_of_chunks). It costs extra embedding calls at ingest and has no maximum chunk size. - 12
Chunk sizing is a trade-off: large chunks dilute the vector and waste prompt tokens; small chunks lose context; overlap protects boundaries but adds chunks and duplicate hits. Tune against real queries, and keep each chunk within the embedding model's window, since text past the window is truncated.
Common traps
Using
split_texton header-split sections (or on loaded documents) silently drops all metadata; usesplit_documents.Assuming
chunk_sizeis in tokens: by default it is characters, so chunks can overflow the embedding model's window.CharacterTextSplittercannot cut a paragraph larger thanchunk_size; it only warns.Displaying
PyPDFLoader'spageas the printed page number: it is zero-based; usepage_labelorpage + 1.Expecting chunks to inherit the parent
Document.id: they come back withid=None, and random store ids create duplicates on re-runs.Calling
lazy_load()on a loader that only overridesload()still builds the full list in memory.Setting
is_separator_regex=Truewith an unescaped.returns an empty list.Blaming embeddings for retrieval misses before printing loaded text and chunk boundaries.
Read the source
Further reading
Suggest a resourceNo extra reading for Document Loaders and Text Splitters yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Document Loaders and Text Splitters
Ten questions, with the answer and explanation after each one.