Generative AIby Dhruv Narang

What Is a Document?

Definition

A Document is a small LangChain object that holds one piece of text. It has two parts: page_content, the text itself, and metadata, a dictionary with information about that text, such as where it came from.

Documentpage_contenta string: the textthe text of the page goes here, as one string …metadataa dictionary: information about the text{ source: the location of the file, page: 0, … }
What a loader gives back: a list of Documents
docs = [
    Document(
        metadata={'source': 'location of the file', 'page': 0},
        page_content='text of page 1 ...'),
    Document(
        metadata={'source': 'location of the file', 'page': 1},
        page_content='text of page 2 ...'),
]
The shape of what print(docs) shows.
docs[0]
the first Document in the list
page_content
docs[0].page_content is the text of the first Document, a string. This is what we cut into chunks, embed, search and finally give to the LLM.
metadata
docs[0].metadata is its information, a dictionary. It is about the text, not the text itself: where it came from, which page. Later we use it to say where an answer came from.

What Is a Document Loader?

Definition

A document loader reads a source, such as a text file, a PDF or a web page, and gives back its text as a list of Documents.

A SOURCEA LIST OF DOCUMENTStext filePDF fileweb pageloader.load()Documentpage_content, metadataDocumentpage_content, metadataDocumentpage_content, metadata
loader = SomeLoader(location)
docs = loader.load()
Every loader works the same way. You give it the location of the source and call .load(). You always get a list of Documents, so the rest of the pipeline does not care where the text came from.

Types of Loaders

There is a loader for almost every kind of source. This table shows the common ones.

LoaderReadsOne Document is
TextLoadera plain text filethe whole file
PyPDFLoadera PDF fileone page
CSVLoadera CSV fileone row
Many moreWord, Excel, Markdown, JSON, HTML, Wikipedia, YouTube…depends on the loader
install: pip install langchain-communitylangchain-community pypdflangchain-community
from langchain_community.document_loaders import TextLoader

txtLoader = TextLoader("data/sample_notes.txt", encoding="utf-8")
docs = txtLoader.load()

print(len(docs))
print(docs[0].metadata)from langchain_community.document_loaders import PyPDFLoader

pdfLoader = PyPDFLoader("data/iitd_ug_rules.pdf")
docs = pdfLoader.load()

print(len(docs))
print(docs[4].metadata["page"])
print(docs[4].metadata["page_label"])from langchain_community.document_loaders import CSVLoader

csvLoader = CSVLoader("data/students.csv")
docs = csvLoader.load()

print(len(docs))
print(docs[0].page_content)
One text file gives one Document. Always add encoding="utf-8". Without it, a file with Hindi or emoji can give an error on Windows.A PDF with 30 pages gives 30 Documents. One page is one Document.A CSV with 3 rows gives 3 Documents. One row is one Document.

Loader Packages: Why We Install Them

A loader does not read every file format by itself. For each format, a pre-built package already does the hard work. The loader calls that package and puts the result into Documents.

Your code
loader.load()
→
The LangChain loader
from langchain-community. It wraps the package.
→
A pre-built package
does the real reading, such as pypdf
→
Documents
the same shape every time
LoaderWhat does the readingInstall
TextLoaderplain Python can read a text filenothing extra
PyPDFLoaderpypdf, a package that reads PDF filespip install pypdf
CSVLoaderPython's built-in csv modulenothing extra
The loader classes themselveslangchain-community: the LangChain package that holds TextLoader, PyPDFLoader and CSVLoader. You import them from langchain_community.document_loaders.pip install langchain-community
When a package is missing
Python stops with an import error that names the missing package. Install it and run again.
Your requirements.txt already lists langchain-community and pypdf.

PyPDFLoader: How It Works

A very common loader in RAG, because a lot of company knowledge sits in PDFs.

A PDF FILEA LIST OF DOCUMENTSpage 1pypdf reads the textDocument, page: 0page 2pypdf reads the textDocument, page: 1page 3pypdf reads the textDocument, page: 2
1. Open
The loader opens the PDF with a Python library called pypdf.
2. Read
It goes through the pages one by one and reads the text of each page.
3. Make Documents
For each page it makes one Document. page_content is the text of that page. metadata holds source (the location of the file), page (the page number, starting at 0), page_label, total_pages, and details of the PDF such as its title and author.
4. Return
A list with one Document for every page.
Why one Document per page: a page is a natural unit, and the page number in the metadata lets us tell the user which page an answer came from.
A real PDF. This is the UG Programme Rules of IIT Delhi.
You look atYou see
len(docs)30. The PDF has 30 pages, so 30 Documents.
docs[0].page_contentonly 91 characters. It is the cover page: the title and the name of the institute.
docs[0].metadatasource, page, page_label, total_pages and some facts about the file, like who made it and when.
docs[4].metadata["page"]4
docs[4].metadata["page_label"]'v'
Real values from this PDF. Another PDF gives other numbers.
page and page_label are different. page is the count the loader makes. It starts at 0. page_label is the number printed on the page, like v (a Roman number). So the fifth page has page 4 and page_label v.

Check What You Loaded

A loader gives you Documents even when the text is bad. Look before you go on.

Look at it after every load. Print three things. It takes a few seconds and saves a lot of trouble.
print(len(docs))
print(docs[0].metadata)
print(docs[0].page_content[:200])
Two things can go wrong. The loader does not stop. It gives you Documents, even when the text is no good.
ProblemWhat you seeWhy
No textpage_content is emptythe PDF is a scan. Each page is a picture, and pypdf reads only text.
Garbage textcharacters like /K37/K2B/K32/K74the PDF has a font that pypdf cannot decode. We saw this in a real game-rulebook PDF.
What to do. Try another copy of the PDF, or use an OCR tool for a scan. Do not go on to chunking until the text looks right. Bad text in means bad answers out.

Loading Methods: load and lazy_load

Every loader has the same methods. They give the same Documents, but they hand them over in different ways.

load()lazy_load()ALL IN MEMORY AT ONCEDoc 1Doc 2Doc 3Doc 4a list with every DocumentONE AT A TIMEwaitswaitswaits1 Documentyour loop gets one when it asksBoth give the same Documents. Only the way they arrive is different.
MethodIt givesHow it worksUse it when
load()a list of Documentsreads everything first, then hands over the whole listthe source is a normal size
lazy_load()a generator: one Document at a timereads the next Document only when your loop asks for itthe source is very big, such as a PDF with thousands of pages, and you want to use little memory
for doc in loader.lazy_load():
    print(doc.metadata)
lazy_load() is a generator: each step of the loop gives one Document, starting with page 0.
load() is built on lazy_load(). In the library, load() simply collects everything that lazy_load() gives into a list. So the Documents are the same. Only the way they arrive is different.

Code
TextLoader01_text_loader.py · 26 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from dotenv import load_dotenv
load_dotenv()

from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.document_loaders import TextLoader
from langchain_core.document_loaders import BaseLoader
parser = StrOutputParser()
model = init_chat_model("groq:openai/gpt-oss-20b")
"""TextLoader: one .txt file -> 1 Document"""
txtLoader = TextLoader("data/sample_notes.txt", encoding="utf-8")

print(type(txtLoader)) # class
print(isinstance(txtLoader, BaseLoader)) # TRUE

"""load() gives a list of Documents: page_content + metadata"""
docs = txtLoader.load()

print(len(docs)) # -> 1
print(docs)
print(docs[0].page_content)



    
PyPDFLoader02_pdf_loader.py · 30 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from dotenv import load_dotenv
load_dotenv()

from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.document_loaders import PyPDFLoader

parser = StrOutputParser()


"""PyPDFLoader: one PDF -> 1 Document per page"""
path = "data/iitd_ug_rules.pdf"

pdfLoader = PyPDFLoader(path)

docs = pdfLoader.load()


print(len(docs))
page1 = docs[0]
print(page1.page_content)
print("-----------------")
print(page1.metadata)

model = init_chat_model("groq:openai/gpt-oss-20b")
parser = StrOutputParser()