Document object.
1. The Document Object
In LangChain, all text data is wrapped in a standard Document class. A Document has two main attributes:
page_content(str): The actual textual content.metadata(dict): A dictionary of key-value pairs storing contextual information (e.g., the source file path, page number, creation date, author).
💡 Example: Manually Preparing Documents
Before loading files directly, you can constructDocument objects manually. This is extremely useful when loading data from databases, custom APIs, or hardcoded strings.
2. Loading Documents from Files
For real-world applications, you’ll load data from physical files. LangChain provides specialized Document Loader subclasses that handle parsing logic for different formats. Let’s explore five commonly used file loaders.2.1 Plain Text Loader (TextLoader)
The TextLoader reads plain text files (.txt, .md, etc.) directly into a single Document object.
Sample File (knowledge.txt):
2.2 PDF Loader (PyPDFLoader)
The PyPDFLoader parses PDF documents page-by-page. It places the content of each page into a separate Document object and automatically populates the page number in the metadata.
Sample File (annual_report.pdf):
A PDF containing two pages:
- Page 1: “Annual Financial Report 2026. Page 1 content summary.”
- Page 2: “Revenue increased by 15% year-over-year. Page 2 content details.”
2.3 CSV Loader (CSVLoader)
The CSVLoader reads tabular data. It creates a separate Document object for each row, presenting the column headers and row values as line pairs inside page_content.
Sample File (users.csv):
2.4 JSON Loader (JSONLoader)
The JSONLoader parses JSON files. It uses a jq query filter to select fields to load into page_content.
Sample File (messages.json):
2.5 HTML Loader (UnstructuredHTMLLoader)
The UnstructuredHTMLLoader parses HTML pages, extracting the main text content free of scripts, CSS, and HTML tags.
Sample File (webpage.html):
3. Practice Exercises
Practice 1: Multi-File Text Loading
Write a script that searches the current directory for all.txt files and loads their content into a list of LangChain Document objects using TextLoader.
Solution
Solution
Summary
- The
DocumentObject: The standard data container in LangChain representing text (page_content) and associated source context (metadata). - Document Loaders: Specialized parsers that extract text from specific formats and wrap them into standard
Documentobjects:TextLoader: Reads plain text files into a single Document.PyPDFLoader: Automatically parses PDFs page-by-page, recording page indexes in metadata.CSVLoader: Converts structured rows into key-value pairs per Document.JSONLoader: Selectively queries text nodes usingjqschemas.UnstructuredHTMLLoader: Extracts clean, main text content free of markup tags, scripts, and styles.