Custom document loaders help you bring in data from places not covered by built-in loaders. They let you read and prepare your own files or sources for your app.
Custom document loaders in LangChain
from langchain.document_loaders import BaseLoader class MyLoader(BaseLoader): def __init__(self, source_path: str): self.source_path = source_path def load(self): # read and process your data here documents = [] with open(self.source_path, 'r', encoding='utf-8') as f: text = f.read() # create Document objects or dicts documents.append({'page_content': text, 'metadata': {}}) return documents
Custom loaders must inherit from BaseLoader and implement a load method.
The load method returns a list of documents, each with content and optional metadata.
class TxtLoader(BaseLoader): def __init__(self, filepath): self.filepath = filepath def load(self): with open(self.filepath, 'r', encoding='utf-8') as f: text = f.read() return [{'page_content': text, 'metadata': {}}]
class JsonLoader(BaseLoader): def __init__(self, filepath): self.filepath = filepath def load(self): import json with open(self.filepath, 'r', encoding='utf-8') as f: data = json.load(f) docs = [] for item in data['items']: docs.append({'page_content': item['text'], 'metadata': {'id': item['id']}}) return docs
This example shows a simple custom loader that reads a text file and adds the file path as metadata. It prints the content and metadata of the loaded document.
from langchain.document_loaders import BaseLoader class SimpleTxtLoader(BaseLoader): def __init__(self, filepath): self.filepath = filepath def load(self): with open(self.filepath, 'r', encoding='utf-8') as f: text = f.read() return [{'page_content': text, 'metadata': {'source': self.filepath}}] # Usage example loader = SimpleTxtLoader('example.txt') docs = loader.load() for doc in docs: print(f"Content:\n{doc['page_content']}") print(f"Metadata: {doc['metadata']}")
Make sure your custom loader handles file encoding and errors gracefully.
Adding metadata helps track where documents come from and can be useful later.
Test your loader with different inputs to ensure it works as expected.
Custom document loaders let you bring in data from any source you want.
They must inherit from BaseLoader and implement a load method.
Use them to read, clean, and add metadata to your documents before using them.
Practice
Solution
Step 1: Understand the role of document loaders
Document loaders bring data into Langchain, preparing it for processing.Step 2: Identify the purpose of custom loaders
Custom loaders allow loading from any source and preprocessing like cleaning or adding metadata.Final Answer:
To load and preprocess documents from any data source before use -> Option AQuick Check:
Custom loaders = load + preprocess documents [OK]
- Confusing loaders with UI components
- Thinking loaders train models
- Assuming loaders manage databases
Solution
Step 1: Check inheritance from BaseLoader
Custom loaders must inherit from BaseLoader to fit Langchain's pattern.Step 2: Confirm the method name is load
The required method to implement is load(), not read().Final Answer:
class MyLoader(BaseLoader):\n def load(self):\n pass -> Option CQuick Check:
Inherit BaseLoader + define load() method [OK]
- Not inheriting from BaseLoader
- Using wrong method name like read()
- Defining function instead of class
print(docs) output?from langchain.schema import Document
from langchain.document_loaders.base import BaseLoader
class SimpleLoader(BaseLoader):
def load(self):
return [Document(page_content='Hello World', metadata={'source': 'test'})]
loader = SimpleLoader()
docs = loader.load()Solution
Step 1: Analyze the load method return value
The load method returns a list with one Document object containing content and metadata.Step 2: Understand what docs holds
docs is assigned the list returned, so printing docs shows the list with the Document instance.Final Answer:
[Document(page_content='Hello World', metadata={'source': 'test'})] -> Option AQuick Check:
load() returns list of Document objects [OK]
- Expecting a list of strings instead of Document objects
- Thinking load() returns None
- Assuming syntax error due to imports
from langchain.document_loaders.base import BaseLoader
class FaultyLoader(BaseLoader):
def load(self):
docs = []
docs.append('Just a string')
return docs
loader = FaultyLoader()
loader.load()Solution
Step 1: Check what load returns
The load method returns a list with a string instead of Document objects.Step 2: Recall Langchain expects Document objects
Custom loaders must return Document instances, not plain strings, for proper processing.Final Answer:
The load method should return Document objects, not strings -> Option DQuick Check:
load() must return Document objects [OK]
- Returning strings instead of Document objects
- Misnaming the load method
- Thinking BaseLoader can't be inherited
Solution
Step 1: Confirm inheritance and method implementation
Custom loaders must subclass BaseLoader and implement load() method.Step 2: Ensure load reads files and returns Document objects with metadata
Reading files and wrapping content in Document with filename metadata is correct.Final Answer:
Inherit BaseLoader, implement load() to read files, create Document with content and metadata filename, return list -> Option BQuick Check:
Subclass + load() returns Document list with metadata [OK]
- Not subclassing BaseLoader
- Returning strings instead of Document objects
- Ignoring metadata addition
Ready to prove it?
Pass the test and this pattern moves unknown
