Building Robust RAG Pipelines: A Deep Dive into LangChain Document Loaders
A hands-on guide to LangChain document loaders for RAG in Python, built on langchain-core. You load PDFs page by page or as one file, turn CSV rows into documents with a useful source, strip web pages down to the article, load a folder of Markdown, split everything into chunks and give every document the same metadata keys.

This guide is for Python developers building a RAG app who need to get real files into it: PDFs, CSV exports, web pages and folders of docs. You will write a small LangChain document loader for each kind, keep the metadata you need for citations and filters, and split the text into chunks that are ready for a vector store.
Key takeaways
- Every loader returns
Documentobjects: text inpage_contentand facts about the source inmetadata. Keep the metadata, because it is how you cite and filter later. - Pick the parser for the file type, and set its options with care: PDF mode, the CSV source column, and which parts of a web page to keep.
- Use
lazy_load()for big jobs. Give every document the same metadata keys first, then split into chunks for indexing.
Why loading matters in a RAG pipeline
A RAG demo usually starts with one clean .txt file. Real data is messier. It lives in PDFs laid out for printing, in CSV exports with dozens of columns, in web pages full of menus and footers, and in folders of Markdown.
If the text you load is jumbled or full of noise, retrieval returns the wrong chunks, and the model answers from bad context. Garbage in, garbage out.
A document loader is a class that reads data from a source, such as a file, a folder or a URL, and returns it as Document objects. In LangChain, loaders share one interface, BaseLoader from langchain-core: lazy_load() yields documents one at a time, and load() collects them into a list.
This post is part 6 of the LLM & LangChain Fundamentals series. In part 5 you built your first RAG pipeline from one small file. Here you feed it real documents.
What a LangChain Document holds
A Document has two fields you will use all the time, plus an optional id:
page_content: the text.metadata: a dict of facts about where the text came from, such as the file path or page number.
from langchain_core.documents import Document
doc = Document(
page_content="Orders ship within two business days.",
metadata={"source": "policies/shipping.md", "section": "Shipping"},
)
print(doc.page_content)
print(doc.metadata["source"])
Checked against langchain-core@1.7.3, langchain-text-splitters@1.1.3, pypdf@6.21.4 and beautifulsoup4@4.15.0 on Python 3.14, 2026-10-31.
Don't skip the metadata. When the model needs to cite a source, or you want only chunks from one file or date, metadata is what makes that possible.
Set up
You need langchain-core for Document and BaseLoader, the text splitters, and one parser library per file type. CSV files and folders need only the Python standard library:
pip install -U "langchain-core==1.7.3" "langchain-text-splitters==1.1.3" "pypdf==6.21.4" "beautifulsoup4==4.15.0"
Why this guide doesn't use langchain-community
The ready-made PyPDFLoader, CSVLoader, WebBaseLoader and DirectoryLoader classes lived in langchain-community. LangChain sunset that package on 22 May 2026 (issue 674) and archived its repository, so it gets no more fixes. The document loaders page lists no standalone package for these four, so this guide builds each one on BaseLoader with the parser library itself.
Each loader below is a short class: __init__ stores the options, and lazy_load() yields the documents. BaseLoader then gives you load() for free. The code blocks build on each other, so run them in order in one file.
Load PDFs
PDFs are built for printing. The text is stored as positioned pieces on a page, not as clean paragraphs, so extraction is rarely perfect.
One document per page
This loader uses the pypdf library. By default (mode="page") you get one Document per page:
from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
from pypdf import PdfReader
class PdfLoader(BaseLoader):
"""Reads a PDF with pypdf: one Document per page, or one for the whole file."""
def __init__(self, path, mode="page", extraction_mode="plain"):
self.path = str(path)
self.mode = mode
self.extraction_mode = extraction_mode
def lazy_load(self):
reader = PdfReader(self.path)
texts = (page.extract_text(extraction_mode=self.extraction_mode) for page in reader.pages)
if self.mode == "single":
yield Document(page_content="\n".join(texts), metadata={"source": self.path})
return
for number, text in enumerate(texts):
yield Document(page_content=text, metadata={"source": self.path, "page": number})
loader = PdfLoader("./docs/quarterly_report.pdf")
pages = loader.load() # one Document per page
print(f"Loaded {len(pages)} pages.")
print(pages[0].page_content[:200])
print(pages[0].metadata["source"], pages[0].metadata["page"])
Each page's metadata includes the file path in source and a zero-based page number. That page number is what lets you cite a page in an answer; add 1 when you show it, so page 3 is "page 4".
One document per file, or a layout that keeps columns
Page mode has a side effect: a sentence that runs across a page break ends up in two documents. If that matters, load the whole file as one document with mode="single", then let the splitter cut it later. For a page with columns or tables, pypdf's extraction_mode="layout" keeps the text closer to how it looks when printed:
# One Document for the whole file, so sentences don't break at page ends
whole = PdfLoader("./docs/quarterly_report.pdf", mode="single").load()
# Keep columns and spacing closer to the printed page
laid_out = PdfLoader("./docs/complex_layout.pdf", extraction_mode="layout").load()
For scanned PDFs, or layouts that still come out jumbled, try UnstructuredLoader from the langchain-unstructured package. It splits a file into elements such as titles and narrative text, and records each one's type in metadata["category"]. It needs extra system tools for local runs, or an API key for the hosted service.
Load CSV files
If you paste a raw CSV row into a prompt, the model sees values with no column names. This loader fixes that. It uses csv.DictReader to make one Document per row and writes each field as a column: value line.
import csv
class CsvRowLoader(BaseLoader):
"""One Document per CSV row, written as 'column: value' lines."""
def __init__(self, path, source_column=None, metadata_columns=(), encoding="utf-8"):
self.path = str(path)
self.source_column = source_column
self.metadata_columns = list(metadata_columns)
self.encoding = encoding
def lazy_load(self):
with open(self.path, newline="", encoding=self.encoding) as f:
for number, row in enumerate(csv.DictReader(f)):
text = "\n".join(f"{k}: {v}" for k, v in row.items() if k not in self.metadata_columns)
source = row[self.source_column] if self.source_column else self.path
metadata = {"source": source, "row": number}
metadata.update({k: row[k] for k in self.metadata_columns})
yield Document(page_content=text, metadata=metadata)
loader = CsvRowLoader(
"./data/customer_feedback.csv",
source_column="Ticket_ID", # this row's ticket id becomes metadata["source"]
metadata_columns=["Created_At"], # copied into metadata, left out of the text
)
rows = loader.load()
print(rows[0].page_content)
print(rows[0].metadata)
Without source_column, every row's source is the file path, so all rows look alike. With it, a retrieved chunk tells you straight away which ticket it came from. Columns in metadata_columns stay out of the text, which is handy for dates you want to filter on but not embed. The Python docs ask for newline="" when you open a CSV file, so quoted fields with line breaks are read correctly. If the file comes from Excel's "CSV UTF-8" export, pass encoding="utf-8-sig": it drops the byte order mark that would otherwise end up in the first column name.
Load web pages
This loader fetches a URL and parses it with BeautifulSoup. Most pages carry menus, footers and cookie banners you don't want in your vector store. Pass a SoupStrainer as parse_only to keep only the parts you name:
from urllib.request import Request, urlopen
import bs4
class WebPageLoader(BaseLoader):
"""Fetches each URL and keeps only the HTML parts that parse_only names."""
def __init__(self, urls, parse_only=None, user_agent="my-rag-ingest/0.1"):
self.urls = list(urls)
self.parse_only = parse_only
self.user_agent = user_agent
def lazy_load(self):
for url in self.urls:
request = Request(url, headers={"User-Agent": self.user_agent})
with urlopen(request, timeout=30) as response:
html = response.read()
soup = bs4.BeautifulSoup(html, "html.parser", parse_only=self.parse_only)
yield Document(page_content=soup.get_text("\n", strip=True), metadata={"source": url})
loader = WebPageLoader(
["https://lilianweng.github.io/posts/2023-06-23-agent/"],
parse_only=bs4.SoupStrainer(class_=("post-title", "post-header", "post-content")),
)
web_docs = loader.load()
print(len(web_docs[0].page_content))
The class names come from that page's HTML. Open your target page in the browser's dev tools to find the right ones. Keeping only the article means fewer tokens to embed and less noise in your search results. Set a User-Agent that names your app, so site owners can see who is fetching their pages.
Load a whole folder
In practice you load folders, not single files. This loader finds files with a glob pattern and reads each one as a Document:
from pathlib import Path
class TextFolderLoader(BaseLoader):
"""Loads every file under a folder that matches a glob pattern, one Document per file."""
def __init__(self, folder, glob="**/*.md", encoding="utf-8"):
self.folder = Path(folder)
self.glob = glob
self.encoding = encoding
def lazy_load(self):
for path in sorted(self.folder.glob(self.glob)):
if path.is_file():
text = path.read_text(encoding=self.encoding)
yield Document(page_content=text, metadata={"source": str(path)})
md_docs = TextFolderLoader("./my-docs/").load()
print(f"Loaded {len(md_docs)} Markdown files.")
Path.glob returns paths in no particular order, according to the pathlib docs, so sorted keeps runs repeatable. For a folder of mixed files, run one loader per file type, for example PdfLoader for each path that glob("**/*.pdf") returns.
Which loader should you use?
| Loader | What it does | Trade-off | When to use |
|---|---|---|---|
PdfLoader (pypdf) |
Text from each page | Jumbles some multi-column pages | Text-based PDFs; start here |
PdfLoader(extraction_mode="layout") |
Keeps the printed layout | Extra spaces in the text | Columns and simple tables |
UnstructuredLoader |
Splits files into typed elements | Extra system tools or an API key | Scanned or complex layouts |
CsvRowLoader (csv) |
One document per row, column: value lines |
Wide rows make long documents | Exports, tickets, catalogs |
WebPageLoader (bs4) |
Fetches and parses HTML | You must pick what to keep | Docs sites and articles |
TextFolderLoader (pathlib) |
Reads matching files in a folder | One file type per glob | Folders of Markdown or text |
Give every document the same metadata keys
Each loader writes its own keys. PdfLoader adds page, and CsvRowLoader adds row plus any metadata_columns. Filters are easier when every document also shares a few keys you control:
from datetime import datetime, timezone
def normalize(docs, doc_type):
loaded_at = datetime.now(timezone.utc).isoformat()
for d in docs:
d.metadata["source"] = str(d.metadata.get("source", ""))
d.metadata["doc_type"] = doc_type
d.metadata["loaded_at"] = loaded_at
return docs
all_docs = normalize(pages, "pdf") + normalize(rows, "csv") + normalize(web_docs, "web") + normalize(md_docs, "markdown")
print({d.metadata["doc_type"] for d in all_docs})
Do this before you split. The splitter copies each document's metadata into its chunks, so keys you add afterwards never reach the chunks you index. Now you can filter by doc_type or by load date the same way for every source, and the loader's own keys are still there.
Split documents into chunks
Loading is only step one. A 50-page PDF in single mode is one huge document. Embedding models cap how much text they accept (OpenAI's embeddings guide lists a maximum input of 8,192 for its current models), and as a rule of thumb, smaller chunks give more precise search results. So split before you index:
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, add_start_index=True)
chunks = splitter.split_documents(all_docs)
print(f"{len(all_docs)} documents -> {len(chunks)} chunks")
print(sorted(chunks[0].metadata)) # includes doc_type, loaded_at and start_index
These are the settings LangChain's own knowledge base tutorial uses. RecursiveCharacterTextSplitter tries paragraph breaks first, then line breaks, then spaces, so chunks tend to end at natural points. The overlap repeats a little text between chunks, so when a key sentence falls on a boundary, part of it appears in both chunks. add_start_index=True records each chunk's position in metadata["start_index"]. Each chunk keeps its parent's metadata too, including the keys normalize added.
Habits for production loading
Stream big jobs with lazy_load()
load() returns a full list, so every document sits in memory at once. For large sets, lazy_load() gives you one document at a time:
for page in PdfLoader("./docs/quarterly_report.pdf").lazy_load():
print(page.metadata["page"], len(page.page_content))
Send each document (or a small batch) to your splitter and vector store inside the loop, instead of building one big list first.
Set the encoding yourself
The CSV and folder loaders above pass encoding="utf-8" to open() and read_text(). Leave it out and Python picks the default. Since Python 3.15, UTF-8 mode is on by default (PEP 686), but older versions used the system's locale encoding, which on some machines is not UTF-8. A file with accents or emoji can then fail to load. Set the encoding so your pipeline behaves the same everywhere.
Next steps
Start with the parser that fits each data type, keep only the content you need, and never throw away the metadata.
Your documents are now loaded and split. Next you need somewhere to store and search them. Part 7 helps you choose a vector database, and part 8 shows how to set up semantic search with a vector store in LangChain.
Frequently asked questions
What is the difference between load() and lazy_load()?
load() reads every document and returns them as one list. lazy_load() returns an iterator that yields one document at a time. Use lazy_load() when the data is too large to hold in memory at once.
Can I still use PyPDFLoader and the other langchain-community loaders?
They still install from PyPI, but the package was sunset in May 2026 and gets no more fixes. If old code depends on them, pin the version you tested. In this guide, PdfLoader replaces PyPDFLoader, CsvRowLoader replaces CSVLoader, WebPageLoader replaces WebBaseLoader, and TextFolderLoader replaces DirectoryLoader with TextLoader. For new code, build on BaseLoader as this guide does, or use a maintained integration package such as langchain-unstructured.
Why load a PDF one page per document?
Page mode keeps page numbers in the metadata, which you need for citations. Pass mode="single" to PdfLoader if you would rather get one document for the whole file and let the text splitter decide where to cut.
How do I stop menus and footers from ending up in my vector store?
Pass a BeautifulSoup SoupStrainer as parse_only, and name the HTML classes or tags that hold the article. Everything else on the page is skipped when it is parsed.
Which loader should I use for scanned PDFs?
pypdf reads the text stored in a PDF and doesn't run OCR, so a scanned page with no text layer gives you little or no text. Use a loader that can run OCR instead, such as UnstructuredLoader from langchain-unstructured. Its local setup needs tesseract, an OCR engine, installed on your machine, so check its install notes first.
Sources
Verified against the sources below on October 31, 2026. Products and docs change often: check the linked sources if something looks different.
- LangChain: Document loaders
- LangChain: Build a semantic search engine (knowledge base tutorial)
- LangChain: Unstructured document loader
- LangChain reference: BaseLoader
- LangChain reference: Document
- LangChain reference: RecursiveCharacterTextSplitter
- langchain-community: sunset announcement (issue 674)
- langchain-community on PyPI
- pypdf docs: Extract text from a PDF
- Python docs: csv module
- Python docs: pathlib
- Beautiful Soup documentation
- OpenAI API: Vector embeddings guide
- PEP 686: Make UTF-8 mode default
- Python docs: open() and the default encoding
All 14 parts in this series
- Part 01What Is LangChain? When to Use It and When to Write Your Own Code
- Part 02LangChain vs. LlamaIndex vs. Vanilla: The Builder's Stack Selection Matrix
- Part 03Structured JSON Output from LLMs: Schema Injection, Pydantic and Retry Loops
- Part 04Building Your First LLM Chain: A Developer's Guide to Sequential Logic
- Part 05Building Your First RAG Pipeline: A Developer’s Guide to Context-Aware AI
- Part 06Building Robust RAG Pipelines: A Deep Dive into LangChain Document Loaders
- Part 07Stop Overthinking Vector Databases: A Builder’s Decision Framework
- Part 08Building Long-Term Memory: Setting Up Vector Databases for Semantic Search in LangChain
- Part 09From Chatbot to Agent: The Engineer's Guide to LLM Memory Systems
- Part 10Building State: A Deep Dive into LangChain Memory for Conversational AI
- Part 11Beyond Built-ins: Architecting Custom Tools in LangChain
- Part 12Unmasking the Black Box: Mastering LangChain Callbacks for Debugging
- Part 13Architecting Autonomous Agents: A Builder’s Guide to Complex Workflows
- Part 14Best Practices for Deploying LangChain Apps to Production
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...