Generative AIby Dhruv Narang

What Is Chunking?

Definition

Chunking means cutting a long text into small pieces called chunks. Each chunk is embedded and stored on its own.

Abstract Large pre-trained language models have been shown to store factual knowledge in their parameters, and achieve state-of-the-art results when fine-tuned on down- stream NLP tasks. However, their ability to access and precisely manipulate knowl- edge is still limited, and hence on knowledge-intensive tasks, their performance lags behind task-specific architectures. Additionally, providing provenance for their decisions and updating their world knowledge remain open research problems. Pre- trained models with a differentiable access mechanism to explicit non-parametric memory have so far been only investigated for extractive downstream tasks. We explore a general-purpose fine-tuning
chunk 1chunk 2chunk 3
The text of a real page of a PDF, cut into 3 chunks. Each colour is one chunk.
Input: a long text, such as a PDF, a web page or a file. Output: many short chunks. Each one is a Document, with the metadata of its source.

Text Splitters: Four Kinds

Definition

A text splitter is the LangChain object that does the cutting. You create it, and then call a method on it. LangChain has several, in four kinds.

Length-based
every N characters, or every N tokens
Splitters:
CharacterTextSplitter
TokenTextSplitter

Good for: simple text, or a strict token limit
Text-structure-based
Best general choice
Cuts at: paragraph breaks first, then lines, then words, then characters

Splitter:
RecursiveCharacterTextSplitter

Good for: most texts
Document-structure-based
headers, tags, objects and functions of the document
Splitters:
MarkdownHeaderTextSplitter
HTMLHeaderTextSplitter
RecursiveJsonSplitter
code splitters (Language)

Good for: Markdown, HTML, JSON and source code
Semantic
where the meaning changes, using embeddings
Splitters:
SemanticChunker
from the langchain-experimental package

Good for: long texts that jump between topics

RecursiveCharacterTextSplitter: The Best Choice

It cuts at natural places, always in the same order.

First
Paragraph
\n\n
Then
Line
\n
Then
Word
" " (a space)
Last
Letter
"" (any character)
Recursive means: if a piece is still too big, try the next separator. So paragraphs and sentences stay whole wherever they can.

Chunk Size and Chunk Overlap

Definition

Two settings control the chunks. Chunk size is how big each chunk is. Chunk overlap is how much of the end of a chunk is repeated at the start of the next one.

the page textapproach, RAG-Token, can predict each target token based on a different document. In the following, weone chunkapproach, RAG-Token, can predict each target token based on a differentthe next chunkeach target token based on a different document. In the following, wethe same 38 characters
Two neighbouring chunks of a paragraph. Here the chunk size is 300 and the chunk overlap is 40.
Chunk size is how big each chunk is, counted in characters.
Chunk overlap is how many characters are repeated. The end of one chunk appears again at the start of the next, so a sentence cut in between is not lost.

Two Ways to Split

A text splitter has two methods. They differ in what you give it, and in what you get back.

Method 1
split_text
A string goes in.
A list of strings comes out.
Method 2
split_documents
Documents go in.
Smaller Documents come out.
For a file from a loader, use split_documents. Each chunk keeps its page, so later we know where it came from.

The Code

The code of the two methods. Pick a tab. Each tab shows what to install first.

install: pip install langchain-text-splitterslangchain-text-splitters langchain-community pypdf
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=300,
    chunk_overlap=40,
    separators=["\n\n", "\n", " ", ""]
)

raw_string = """
Generative AI is transforming modern software engineering.
Developers build agents and RAG pipelines using LangChain and LCEL.
Text Splitters break large text into smaller, manageable chunks.
This prevents context window overflow and improves search precision.
"""

string_chunks = splitter.split_text(raw_string)

print(string_chunks)
print(len(string_chunks))from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=300,
    chunk_overlap=40,
    separators=["\n\n", "\n", " ", ""]
)

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

docs_chunks = splitter.split_documents(docs)

print(docs_chunks[0].metadata)
print(len(docs_chunks))
A string in, a list of strings out. This text is shorter than 300 characters, so we get 1 chunk.Documents in, smaller Documents out. The 30 pages of the IIT Delhi PDF give 340 chunks. Each chunk keeps the metadata of its page.

Code
Text chunking with the recursive splitter01_text_chunking.py · 35 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
28
29
30
31
32
33
34
35
from dotenv import load_dotenv

load_dotenv()

from langchain_community.document_loaders import TextLoader , PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

"""RecursiveCharacterTextSplitter: tries 

, then 
, then space, then any char"""
splitter =  RecursiveCharacterTextSplitter(chunk_size=300,chunk_overlap=40 ,  separators=["\n\n", "\n", " ", ""])

raw_string = """
Generative AI is transforming modern software engineering.
Developers build agents and RAG pipelines using LangChain and LCEL.
Text Splitters break large text into smaller, manageable chunks.
This prevents context window overflow and improves search precision.
"""

"""1. split_text: str -> list of str"""
string_chunks = splitter.split_text(raw_string)

print(string_chunks)
print(len(string_chunks))
print(type(string_chunks[0]))

"""2. split_documents: list of Documents -> smaller Documents (metadata kept)"""
loader = PyPDFLoader("data/iitd_ug_rules.pdf")
docs = loader.load()

docs_chunks = splitter.split_documents(docs)
print(docs_chunks[0].metadata)
print(len(docs_chunks))
print(type(docs_chunks[0]))