Overview
PyMuPDF4LLM integrates with LangChain through a custom document loader that wrapsto_markdown() and returns LangChain Document objects. Each document carries the page’s Markdown content in its page_content field and PyMuPDF4LLM’s page metadata in its metadata field.
Installation
Make sure PyMuPDF4LLM LangChain is installed:Basic Usage
PyMuPDF4LLMLoader follows the LangChain BaseLoader interface. Call load() to get a list of Document objects — one per page.
Document Structure
EachDocument contains:
page_content— the Markdown text of the pagemetadata— a dictionary of page and document-level metadata
Building a RAG Pipeline
CombinePyMuPDF4LLMLoader with LangChain’s Chroma vector store and a chat model to build a retrieval-augmented generation pipeline:
Text Splitting
For large documents, split pages into smaller chunks before embedding to improve retrieval precision. LangChain’sMarkdownHeaderTextSplitter is a natural fit because PyMuPDF4LLM output preserves Markdown headings:
RecursiveCharacterTextSplitter for a simpler fixed-size approach:
Lazy Loading
For large documents or memory-constrained environments, uselazy_load() to yield documents one at a time rather than loading everything into memory at once:
Loading Multiple Documents
Combine multiple loaders to build an index across a folder of PDFs:Using with LCEL
PyMuPDF4LLMLoader works naturally inside LangChain Expression Language (LCEL) chains. Here’s a complete retrieval chain using the pipe syntax:Metadata Filtering
Because each document carries source and page metadata, you can scope retrieval to specific pages or files using metadata filters:Full Pipeline Example
Next Steps
PyMuPDF Pro
Use PyMuPDF4LLM with Office documents.
Extract Markdown
Full walkthrough of to_markdown() options.
OCR
Enable OCR for scanned PDFs before indexing.