Generative AI Part 12: Document Loading and Chunking Strategies for RAG

Generative AI Part 12 banner: PDF, Markdown and HTML files loaded, cleaned and split into chunks with IDs for RAG
PART 12 Generative AI Series · DevDojo Document Loading & Chunking Strategies Turn PDFs, web pages and Markdown into clean RAG chunks Your files PDF MD HTML TXT messy, mixed formats 1 · Load + Clean plain text+ metadatasource · page · section 2 · ChunkSplitter 3 · Chunks with IDs refund.md:1 · 280 chars refund.md:2 · 260 chars handbook.pdf:p2:1 devdojo.co.in · Beginner friendly · Python + Node.js examples
Series: Generative AI Part 12 of 30

What you should know first: read Part 11: RAG Fundamentals and Part 9: Embeddings Explained. You need Python 3.10+ or Node.js 20+. No API key is needed for any example in this post.

In Part 11 we built a RAG app, but we cheated a little: our “documents” were four neat sentences typed straight into the code. Real knowledge lives in PDFs, web pages, Markdown docs and messy notes. Before an LLM can answer from them, you must load each file into clean text and then cut that text into small, meaningful pieces called chunks. In this post you will learn document loading and chunking strategies for RAG: how to read PDF, HTML, Markdown and text files in Python and Node.js, how fixed-size, overlapping, recursive and heading-based chunking differ, and how to test which chunking strategy gives the best answers on your own data.

Quick Summary
  • Document loading = turning each file (PDF, HTML, Markdown, text) into plain text plus metadata like file name, page and section.
  • Chunking = cutting that text into pieces small enough to embed and retrieve, but big enough to hold a complete idea.
  • Four main chunking strategies: fixed size, fixed size with overlap, recursive (paragraph → sentence → word) and by structure (headings, pages).
  • A good default: split by headings when you have them, then use a recursive splitter of about 300–1,000 characters with 10–20% overlap.
  • Don’t guess. Write 10–20 test questions and measure which strategy retrieves the right chunk.
Full Generative AI roadmap (30 parts)

Beginner

  1. What Is Generative AI and How Do LLMs Work?
  2. Tokens, Context Windows and Model Parameters
  3. Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)
  4. Prompt Engineering Basics: Roles, Instructions and Examples
  5. Temperature, Top-p and Controlling Model Output
  6. Run LLMs Locally with Ollama
  7. Streaming Responses and Building a Simple Chat UI
  8. Structured Outputs: Getting Reliable JSON from LLMs

Intermediate

  1. Embeddings Explained: Turning Text into Vectors
  2. Vector Databases: pgvector, Chroma and Pinecone
  3. RAG Fundamentals: Retrieval-Augmented Generation
  4. Document Loading and Chunking StrategiesYou are here
  5. Better RAG: Hybrid Search, Re-ranking and Query RewritingComing soon
  6. Function Calling and Tool UseComing soon
  7. Conversation Memory and Long Context ManagementComing soon
  8. Multimodal AI: Vision, Images and Audio InputsComing soon
  9. How Image Generation Works: Diffusion Models BasicsComing soon
  10. LangChain vs LlamaIndex: When to Use a FrameworkComing soon
  11. Testing LLM Apps: Evals, Metrics and Test SetsComing soon
  12. Cutting Cost and Latency: Caching, Batching and Model ChoiceComing soon

Advanced

  1. Fine-Tuning vs Prompting vs RAG: Choosing the Right ToolComing soon
  2. Fine-Tuning an Open Model with LoRAComing soon
  3. Transformers Deep Dive: Attention Explained SimplyComing soon
  4. Reasoning Models and Thinking TimeComing soon
  5. Guardrails, Safety and Prompt Injection DefenceComing soon
  6. Monitoring and Tracing LLM Apps in ProductionComing soon
  7. Serving Open Models: vLLM, Quantization and GPUsComing soon
  8. Building a Production GenAI App End to EndComing soon
  9. Responsible AI: Privacy, Licensing and BiasComing soon
  10. Final Project: Build Your Own AI Knowledge AssistantComing soon

What are document loading and chunking?

Every RAG app has an indexing phase that runs before anyone asks a question (you saw it in Part 11). Today we zoom into its first three steps:

  1. Load: open each file and pull out its text. A PDF needs a PDF reader, a web page needs its HTML tags removed, a Markdown file can be read as it is.
  2. Clean: throw away text that is not real content: menus, cookie banners, footers, page numbers, repeated headers.
  3. Chunk: cut the clean text into pieces and attach metadata to each piece, so you can cite it later (“refund-policy.md, section: How to ask for a refund”).

Only after this do you create embeddings and store them in a vector database.

This post: Load → Clean → Chunk LoadPDF, MD, HTML Cleandrop menus, ads Chunksplit + metadata EmbedPart 9 Storevector DB · Part 10 Bad chunks here = bad answers later. Retrieval can only find what chunking kept together.
Figure 1: The RAG indexing pipeline. Loading, cleaning and chunking happen before embeddings and the vector database you met in Parts 9 and 10.

Think of it like preparing notes for an open-book exam. If you tear the book into random strips, you will never find the right answer quickly. If you keep each topic on its own labelled card, you will.

Why chunk size matters

Why not just embed a whole file? Because an embedding is one vector that summarises the whole text. Embed a 40-page handbook as one vector and its meaning becomes a blurry average of everything, so it matches no question well. Also, embedding models and LLMs have input limits (remember context windows from Part 2).

Chunks too bigVectors get blurry, retrieval gets less precise, and each chunk fills the prompt with unrelated text (more tokens, more cost, more confusion).
Chunks too smallA single sentence like “It takes 5 to 7 days.” loses its context. What takes 5 to 7 days? The model can’t tell.
Just rightOne complete idea per chunk: a paragraph or a short section, with its title. Small enough to be precise, big enough to make sense alone.

Step 1: Loading PDF, HTML, Markdown and text files

Let’s create a tiny knowledge base for an imaginary “DevDojo Pro” plan with four file types: refund-policy.md, a two-page handbook.pdf, an faq.html page (with a menu, footer and a script we must ignore) and notes.txt. Install the packages first:

Terminal — setup
# Project folder with the sample files from this post
$ mkdir devdojo-chunking && cd devdojo-chunking && mkdir docs
# Python packages (Python 3.10+)
$ pip install pypdf langchain-text-splitters
# Node.js packages (Node.js 20+)
$ npm install unpdf @langchain/textsplitters @langchain/core

We use pypdf to read PDFs in Python and unpdf in Node.js. For HTML we keep things dependency-free: Python’s built-in html.parser, and a couple of regular expressions in Node.js. Every loader returns the same shape: {text, metadata}. PDFs return one document per page, so the page number becomes metadata you can cite.

load_docs.py — devdojo-chunking — Visual Studio Code
devdojo-chunking › load_docs.py
from pathlib import Path
from html.parser import HTMLParser
from pypdf import PdfReader

class TextOnly(HTMLParser):
    """Keeps visible text, skips <script>, <style>, <nav> and <footer>."""
    SKIP = {"script", "style", "nav", "footer"}
    def __init__(self):
        super().__init__()
        self.parts, self.skipping = [], 0
    def handle_starttag(self, tag, attrs):
        if tag in self.SKIP:
            self.skipping += 1
    def handle_endtag(self, tag):
        if tag in self.SKIP:
            self.skipping -= 1
    def handle_data(self, data):
        if not self.skipping and data.strip():
            self.parts.append(data.strip())

def load(path: Path):
    """Return a list of {text, metadata} documents for one file."""
    if path.suffix == ".pdf":
        reader = PdfReader(path)
        return [{"text": page.extract_text(), "metadata": {"source": path.name, "page": i}}
                for i, page in enumerate(reader.pages, 1)]
    raw = path.read_text(encoding="utf-8")
    if path.suffix == ".html":
        parser = TextOnly()
        parser.feed(raw)
        raw = "\n".join(parser.parts)
    return [{"text": raw, "metadata": {"source": path.name}}]

if __name__ == "__main__":
    docs = [d for p in sorted(Path("docs").iterdir()) for d in load(p)]
    for d in docs:
        preview = d["text"].replace("\n", " ")[:55]
        print(f"{str(d['metadata']):38} {len(d['text']):4} chars | {preview}...")
    print(f"Loaded {len(docs)} documents")
TERMINALOUTPUTPROBLEMS
$ python load_docs.py
{'source': 'faq.html'}                  281 chars | DevDojo FAQ Frequently asked questions Do I get a certi...
{'source': 'handbook.pdf', 'page': 1}   173 chars | DevDojo Student Handbook Page 1: Getting started Create...
{'source': 'handbook.pdf', 'page': 2}   201 chars | Page 2: Mentors and projects Every DevDojo Pro student ...
{'source': 'notes.txt'}                 246 chars | Team meeting notes - support desk  Support is available...
{'source': 'refund-policy.md'}          538 chars | # DevDojo Pro Refund Policy  DevDojo Pro is our paid pl...
Loaded 5 documents
⎇ mainLn 39, Col 1Spaces: 4UTF-8LFPython
devdojo-chunking › load_docs.mjs
import { readdir, readFile } from "node:fs/promises";
import { extname, join } from "node:path";
import { extractText, getDocumentProxy } from "unpdf";

// Keep visible text: drop <script>, <style>, <nav>, <footer>, then all tags
function htmlToText(html) {
  return html
    .replace(/<(script|style|nav|footer)[\s\S]*?<\/\1>/gi, " ")
    .replace(/<[^>]+>/g, "\n")
    .split("\n").map((s) => s.trim()).filter(Boolean).join("\n");
}

async function load(file) {
  const path = join("docs", file);
  if (extname(file) === ".pdf") {
    const pdf = await getDocumentProxy(new Uint8Array(await readFile(path)));
    const { text } = await extractText(pdf, { mergePages: false });
    return text.map((t, i) => ({ text: t, metadata: { source: file, page: i + 1 } }));
  }
  let raw = await readFile(path, "utf8");
  if (extname(file) === ".html") raw = htmlToText(raw);
  return [{ text: raw, metadata: { source: file } }];
}

const files = (await readdir("docs")).sort();
const docs = (await Promise.all(files.map(load))).flat();
for (const d of docs) {
  const preview = d.text.replace(/\n/g, " ").slice(0, 55);
  console.log(`${JSON.stringify(d.metadata).padEnd(38)} ${String(d.text.length).padStart(4)} chars | ${preview}...`);
}
console.log(`Loaded ${docs.length} documents`);
TERMINALOUTPUTPROBLEMS
$ node load_docs.mjs
{"source":"faq.html"}                   281 chars | DevDojo FAQ Frequently asked questions Do I get a certi...
{"source":"handbook.pdf","page":1}      173 chars | DevDojo Student Handbook Page 1: Getting started Create...
{"source":"handbook.pdf","page":2}      201 chars | Page 2: Mentors and projects Every DevDojo Pro student ...
{"source":"notes.txt"}                  246 chars | Team meeting notes - support desk  Support is available...
{"source":"refund-policy.md"}           538 chars | # DevDojo Pro Refund Policy  DevDojo Pro is our paid pl...
Loaded 5 documents
⎇ mainLn 31, Col 1Spaces: 2UTF-8LFJavaScript

Click the load_docs.py / load_docs.mjs tabs to switch language, then press ▶ Run to see the real output.

Why one document per PDF page? When the bot answers “Mentors review 3 projects (handbook.pdf, page 2)”, users can open the exact page and check. Keep metadata from the very first step; it is very hard to add later.
Scanned PDFs have no text. If extract_text() returns an empty string, the PDF is just images of pages. You need OCR (for example Tesseract) or a document-parsing service before you can chunk it.

Chunking strategies for RAG

There are many chunking strategies, but four cover almost every project. Click through the explorer below to compare them.

How it works: cut the text every N characters (or N tokens), no matter what is there.

Good: very simple, fast, predictable chunk sizes. Bad: breaks words and sentences, so one fact can end up split across two chunks and neither chunk answers the question.

Use it when: you need a quick baseline, or the text has no structure at all (logs, transcripts).

How it works: fixed-size chunks, but each new chunk starts a little before the previous one ended (for example 300 characters with 50 of overlap).

Good: a sentence cut at a border usually survives whole in the next chunk. Bad: more chunks to embed and store, and repeated text can show up twice in the prompt.

Use it when: you use fixed or recursive splitting. 10–20% overlap is a common starting point.

How it works: try to split on the biggest natural break first (blank line between paragraphs), and only if a piece is still too long, split it on a smaller break (line, sentence, word). This is LangChain’s RecursiveCharacterTextSplitter.

Good: respects paragraphs and sentences while keeping a size limit. Bad: does not know what a heading means, so a heading can land alone in its own tiny chunk.

Use it when: almost always. It is the best general-purpose default.

How it works: split on the document’s own structure: Markdown or HTML headings, PDF pages, code functions. Each chunk keeps its section title as metadata. Long sections are then cut again with a recursive splitter.

Good: each chunk is one complete topic, and you can cite “Refund Policy › How to ask for a refund”. Bad: needs clean structure; sections can be very uneven in size.

Use it when: docs, help centres, wikis, READMEs, legal and policy pages.

Fixed sizecuts anywhere …refund within 7 days of your first payment. Refunds are not available for… Cuts “7 days” and “payment” in half With overlaprepeats a little text …refund within 7 days of your first days of your first payment. Refunds are… shared part The shared part keeps the sentence whole in at least one chunk By headingsfollows structure ## Who can get a refund## How to ask for a refund## When the money comes back Each chunk = one complete topic with its title. Best for docs with headings. Same text, three strategies, very different chunks.
Figure 2: Fixed-size, overlapping and heading-based chunking of the same refund policy. Red lines show where a fixed-size split breaks words.

You may also hear about semantic chunking (start a new chunk where the meaning changes, measured with embeddings) and agentic or LLM-based chunking (ask a model to split the text). They can help on long, unstructured text, but they are slower and cost more. Start with recursive or structure-based splitting and only move on if your tests show a real gain.

Chunkers from scratch in Python and Node.js

Libraries are great, but writing the three basic chunkers yourself takes 30 lines and makes everything else easy to understand. We run each one on refund-policy.md and print the start of the second chunk:

chunkers.py — devdojo-chunking — Visual Studio Code
devdojo-chunking › chunkers.py
import re

text = open("docs/refund-policy.md", encoding="utf-8").read()

# Strategy 1: fixed size (simple, but cuts words and sentences)
def fixed_size(text, size=120, overlap=0):
    step = size - overlap
    return [text[i:i + size] for i in range(0, len(text), step)]

# Strategy 2: sentence-based (pack whole sentences up to a size limit)
def by_sentences(text, max_chars=200):
    sentences = re.split(r"(?<=[.!?])\s+", text.replace("\n", " "))
    chunks, current = [], ""
    for s in sentences:
        if current and len(current) + len(s) + 1 > max_chars:
            chunks.append(current)
            current = s
        else:
            current = f"{current} {s}".strip()
    return chunks + [current] if current else chunks

# Strategy 3: by Markdown headings (each section keeps its title)
def by_headings(md):
    sections = re.split(r"\n(?=#{1,3} )", md.strip())
    return [s.strip() for s in sections if s.strip()]

if __name__ == "__main__":
    for name, chunks in [("fixed_size(120)", fixed_size(text)),
                         ("fixed_size(120, overlap=30)", fixed_size(text, 120, 30)),
                         ("by_sentences(200)", by_sentences(text)),
                         ("by_headings", by_headings(text))]:
        print(f"{name}: {len(chunks)} chunks")
        print(f"  chunk 2 -> {chunks[1][:70]!r}")
TERMINALOUTPUTPROBLEMS
$ python chunkers.py
fixed_size(120): 5 chunks
  chunk 2 -> 't a refund\n\nYou can ask for a full refund within 7 days of your first '
fixed_size(120, overlap=30): 6 chunks
  chunk 2 -> 'doubt sessions.\n\n## Who can get a refund\n\nYou can ask for a full refun'
by_sentences(200): 3 chunks
  chunk 2 -> 'Refunds are not available for renewals after the first month. ## How t'
by_headings: 4 chunks
  chunk 2 -> '## Who can get a refund\n\nYou can ask for a full refund within 7 days o'
⎇ mainLn 33, Col 1Spaces: 4UTF-8LFPython
devdojo-chunking › chunkers.mjs
import { readFileSync } from "node:fs";

const text = readFileSync("docs/refund-policy.md", "utf8");

// Strategy 1: fixed size (simple, but cuts words and sentences)
function fixedSize(text, size = 120, overlap = 0) {
  const chunks = [];
  for (let i = 0; i < text.length; i += size - overlap) chunks.push(text.slice(i, i + size));
  return chunks;
}

// Strategy 2: sentence-based (pack whole sentences up to a size limit)
function bySentences(text, maxChars = 200) {
  const sentences = text.replace(/\n/g, " ").split(/(?<=[.!?])\s+/);
  const chunks = [];
  let current = "";
  for (const s of sentences) {
    if (current && current.length + s.length + 1 > maxChars) {
      chunks.push(current);
      current = s;
    } else current = `${current} ${s}`.trim();
  }
  return current ? [...chunks, current] : chunks;
}

// Strategy 3: by Markdown headings (each section keeps its title)
const byHeadings = (md) =>
  md.trim().split(/\n(?=#{1,3} )/).map((s) => s.trim()).filter(Boolean);

for (const [name, chunks] of [
  ["fixedSize(120)", fixedSize(text)],
  ["fixedSize(120, overlap=30)", fixedSize(text, 120, 30)],
  ["bySentences(200)", bySentences(text)],
  ["byHeadings", byHeadings(text)],
]) {
  console.log(`${name}: ${chunks.length} chunks`);
  console.log(`  chunk 2 -> ${JSON.stringify(chunks[1].slice(0, 70))}`);
}
TERMINALOUTPUTPROBLEMS
$ node chunkers.mjs
fixedSize(120): 5 chunks
  chunk 2 -> "t a refund\n\nYou can ask for a full refund within 7 days of your first "
fixedSize(120, overlap=30): 6 chunks
  chunk 2 -> "doubt sessions.\n\n## Who can get a refund\n\nYou can ask for a full refun"
bySentences(200): 3 chunks
  chunk 2 -> "Refunds are not available for renewals after the first month. ## How t"
byHeadings: 4 chunks
  chunk 2 -> "## Who can get a refund\n\nYou can ask for a full refund within 7 days o"
⎇ mainLn 38, Col 1Spaces: 2UTF-8LFJavaScript

Press ▶ Run and look at “chunk 2” for each strategy: only the heading-based chunk starts at a clean boundary.

Look closely at the output. The plain fixed-size chunk starts with "t a refund": a broken word. With overlap, chunk 2 starts a bit earlier and keeps the full heading. The sentence chunker keeps whole sentences, but it removed the line breaks, so a heading (## How t…) got glued onto the previous section. Only the heading-based chunker starts exactly at a topic boundary.

LangChain text splitters (Python and Node.js)

In real projects you will usually use a ready-made splitter. The most popular are in LangChain’s small, standalone text splitter packages. You don’t need the rest of LangChain to use them. The RecursiveCharacterTextSplitter tries a list of separators in order ("\n\n", "\n", sentence end, space) and only falls back to a smaller one when a piece is still longer than chunk_size.

splitters.py — devdojo-chunking — Visual Studio Code
devdojo-chunking › splitters.py
from langchain_text_splitters import (
    MarkdownHeaderTextSplitter,
    RecursiveCharacterTextSplitter,
)

md = open("docs/refund-policy.md", encoding="utf-8").read()

# 1. Split by headings first; each chunk remembers its section titles
header_splitter = MarkdownHeaderTextSplitter(
    headers_to_split_on=[("#", "title"), ("##", "section")]
)
sections = header_splitter.split_text(md)

# 2. Then cut long sections into ~150-character pieces with overlap
splitter = RecursiveCharacterTextSplitter(
    chunk_size=150,
    chunk_overlap=30,
    separators=["\n\n", "\n", ". ", " ", ""],  # try big breaks first
)
chunks = splitter.split_documents(sections)

for i, c in enumerate(chunks, 1):
    section = c.metadata.get("section", "(intro)")
    print(f"[{i}] {section:26} | {c.page_content[:58]}")
print(f"{len(sections)} sections -> {len(chunks)} chunks")
TERMINALOUTPUTPROBLEMS
$ python splitters.py
[1] (intro)                    | DevDojo Pro is our paid plan with all video courses and li
[2] Who can get a refund       | You can ask for a full refund within 7 days of your first 
[3] How to ask for a refund    | Email support@devdojo.example with your order ID. Our team
[4] When the money comes back  | Refunds go back to the original payment method. UPI and ca
4 sections -> 4 chunks
⎇ mainLn 25, Col 1Spaces: 4UTF-8LFPython
devdojo-chunking › splitters.mjs
import { readFileSync } from "node:fs";
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";

const md = readFileSync("docs/refund-policy.md", "utf8");

// Markdown-aware recursive splitter: tries headings, then paragraphs,
// then sentences, then words, so chunks break at natural places
const splitter = RecursiveCharacterTextSplitter.fromLanguage("markdown", {
  chunkSize: 150,
  chunkOverlap: 30,
});

const chunks = await splitter.createDocuments(
  [md],
  [{ source: "refund-policy.md" }],
);

chunks.forEach((c, i) => {
  const preview = c.pageContent.replace(/\n/g, " ").slice(0, 58);
  console.log(`[${i + 1}] lines ${c.metadata.loc.lines.from}-${c.metadata.loc.lines.to} | ${preview}`);
});
console.log(`${chunks.length} chunks`);
TERMINALOUTPUTPROBLEMS
$ node splitters.mjs
[1] lines 1-3 | # DevDojo Pro Refund Policy  DevDojo Pro is our paid plan 
[2] lines 5-5 | ## Who can get a refund
[3] lines 7-7 | You can ask for a full refund within 7 days of your first 
[4] lines 9-11 | ## How to ask for a refund  Email support@devdojo.example 
[5] lines 13-13 | ## When the money comes back
[6] lines 15-15 | Refunds go back to the original payment method. UPI and ca
6 chunks
⎇ mainLn 22, Col 1Spaces: 2UTF-8LFJavaScript

Compare the two outputs: the Python version splits by headings first, the Node.js version leaves headings in their own small chunks.

The Python version is the pattern to copy for Markdown: first split by headings with MarkdownHeaderTextSplitter (each chunk gets title and section in its metadata), then run the recursive splitter so very long sections still fit the size limit. In the Node.js output you can see the weakness of a size-only splitter: chunks 2 and 5 are just headings with no content, which are useless for retrieval. Merge them or prefix each chunk with its heading (we do this in the pipeline below).

Characters or tokens? Both splitters measure size in characters by default. A rough rule for English: 1 token ≈ 4 characters, so 1,000 characters ≈ 250 tokens. Hindi and other non-Latin scripts use more tokens per character, so check with a tokenizer if you work with them.

Testing which chunking strategy works best

The honest answer to “what is the best chunk size?” is: it depends on your documents, so measure it. Write a handful of real questions, note a phrase the correct chunk must contain, and count how often the top retrieved chunk contains it. To keep this example free and fast, we use simple word matching instead of embeddings. The idea is exactly the same with a vector database.

compare_chunking.py — devdojo-chunking — Visual Studio Code
devdojo-chunking › compare_chunking.py
import re
from chunkers import fixed_size, by_sentences, by_headings

md = open("docs/refund-policy.md", encoding="utf-8").read()

# Small test set: question -> words the right chunk MUST contain
tests = [
    ("How many days do I have to ask for a refund?", "7 days of your first payment"),
    ("Can I get a refund on a renewal?", "not available for renewals"),
    ("How do I ask for a refund?", "with your order ID"),
    ("How long does a UPI refund take?", "5 to 7 working days"),
]

STOP = {"a", "an", "the", "i", "do", "does", "how", "to", "on", "for", "of", "my", "can", "is"}

def words(t):
    # lowercase words, no common filler words, "refunds" -> "refund"
    return {w.rstrip("s") for w in re.findall(r"[a-z0-9]+", t.lower()) if w not in STOP}

def top_chunk(question, chunks):
    # stand-in for embedding search: most shared words wins
    return max(chunks, key=lambda c: len(words(question) & words(c)))

strategies = {
    "fixed 80, no overlap": fixed_size(md, 80),
    "fixed 80, overlap 20": fixed_size(md, 80, 20),
    "sentences (200)": by_sentences(md, 200),
    "headings": by_headings(md),
}
for name, chunks in strategies.items():
    hits = sum(answer in top_chunk(q, chunks) for q, answer in tests)
    print(f"{name:22} {len(chunks):2} chunks  -> {hits}/{len(tests)} answers found")
TERMINALOUTPUTPROBLEMS
$ python compare_chunking.py
fixed 80, no overlap    7 chunks  -> 0/4 answers found
fixed 80, overlap 20    9 chunks  -> 1/4 answers found
sentences (200)         3 chunks  -> 2/4 answers found
headings                4 chunks  -> 3/4 answers found
⎇ mainLn 32, Col 1Spaces: 4UTF-8LFPython

Press ▶ Run to see how many test questions each strategy answers. This file imports the functions from chunkers.py above.

On this small file, fixed-size chunks with no overlap answer 0 of 4 questions: every answer phrase was cut across a border. Overlap rescues one. Sentence packing gets 2, and heading-based chunks get 3 of 4. With real embeddings the scores will be higher, but the ranking is usually similar on well-structured docs. The miss also teaches something: for “How do I ask for a refund?” the useful words are only “ask” and “refund”, and the “Who can get a refund” section contains both too, so simple word matching picked the wrong section. Fixing that is the job of better retrieval (hybrid search and re-ranking), which is exactly what Part 13 covers.

A complete ingest pipeline with metadata and stable IDs

Now let’s put it together into a script you can actually reuse: load every file, split Markdown by headings, cut everything with a recursive splitter (300 characters, 50 overlap), add the section title to the chunk text, and give every chunk a stable ID.

ingest.py — devdojo-chunking — Visual Studio Code
devdojo-chunking › ingest.py
import json
from pathlib import Path
from langchain_text_splitters import MarkdownHeaderTextSplitter, RecursiveCharacterTextSplitter
from load_docs import load

headers = MarkdownHeaderTextSplitter([("#", "title"), ("##", "section")])
splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)

def chunk_document(doc):
    meta = doc["metadata"]
    if meta["source"].endswith(".md"):  # structure-aware for Markdown
        parts = [(p.page_content, {**meta, **p.metadata}) for p in headers.split_text(doc["text"])]
    else:
        parts = [(doc["text"], meta)]
    for text, m in parts:
        for piece in splitter.split_text(text):
            yield piece, m

records = []
for path in sorted(Path("docs").iterdir()):
    for doc in load(path):
        for n, (text, meta) in enumerate(chunk_document(doc), 1):
            heading = meta.get("section") or meta.get("title")
            # Stable ID: same file + page + position -> same ID on re-index
            records.append({
                "id": f"{meta['source']}:p{meta.get('page', 1)}:{n}",
                "text": f"{heading}: {text}" if heading else text,  # add context
                "metadata": meta,
            })

Path("chunks.jsonl").write_text("\n".join(json.dumps(r) for r in records), encoding="utf-8")
for r in records[:3] + records[-2:]:
    preview = r["text"][:48].replace("\n", " ")
    print(f"{r['id']:24} {len(r['text']):3} chars | {preview}")
print(f"Saved {len(records)} chunks to chunks.jsonl")
TERMINALOUTPUTPROBLEMS
$ python ingest.py
faq.html:p1:1            281 chars | DevDojo FAQ Frequently asked questions Do I get 
handbook.pdf:p1:1        173 chars | DevDojo Student Handbook Page 1: Getting started
handbook.pdf:p2:1        201 chars | Page 2: Mentors and projects Every DevDojo Pro s
refund-policy.md:p1:3    114 chars | How to ask for a refund: Email support@devdojo.e
refund-policy.md:p1:4    153 chars | When the money comes back: Refunds go back to th
Saved 8 chunks to chunks.jsonl
⎇ mainLn 35, Col 1Spaces: 4UTF-8LFPython

This is the version you would use in a real project: it reuses load() from load_docs.py and writes chunks.jsonl, ready for embedding.

Two small details make a big difference in production:

  • Stable IDs such as handbook.pdf:p2:1 mean that when you re-index after a document changes, you can upsert (update or insert) instead of creating duplicate chunks.
  • Heading prefix (“How to ask for a refund: Email support…”) gives every chunk context, which improves both the embedding and the LLM’s understanding. This simple trick is often called a contextual chunk header.

The chunks.jsonl file is the input for the embedding and vector-database code from Parts 9–11: read each line, embed text, and store it with its id and metadata.

Choosing chunk size and overlap

These are starting points, not rules. Always confirm with your own test questions.

Content typeStrategyStarting sizeOverlap
Docs, help centre, wiki (Markdown/HTML)By headings, then recursive500–1,000 chars10–15%
FAQ pagesOne question + answer per chunkWhole Q&ANone
PDF reports and manualsPer page, then recursive800–1,500 chars15–20%
Chat logs, transcriptsRecursive or by time window500–1,000 chars20%
Source codeBy function or class (language-aware splitter)One functionNone
Legal and policy textBy clause or section numberOne clauseSmall

Common errors and fixes

ProblemWhy it happensFix
extract_text() returns "" for a PDFScanned PDF: the pages are imagesRun OCR first, or use a document-parsing tool that supports scanned pages
Words glued together or split with hyphens (“pay-
ment”)
PDF layout extraction is not perfectClean with a small regex (join hyphenated line breaks, collapse spaces) before chunking
Every chunk contains “Home | Courses | Login”Menus and footers were loaded as contentSkip nav, footer, script, style tags, or extract only main/article
The answer is half in one chunk, half in the nextFixed-size split with no overlapAdd 10–20% overlap or split on structure
Chunks that contain only a headingSize-based splitter cut before the contentSplit by headings first, or prefix each chunk with its heading
Duplicate chunks after re-indexingRandom IDs on every runUse stable IDs (file + page + position) and upsert
Embedding API error: input too longChunk is bigger than the embedding model’s input limitLower chunk_size, or measure length in tokens
ModuleNotFoundError: langchain_text_splittersPackage name uses dashes on pippip install langchain-text-splitters
SyntaxError on await or import in Node.jsFile is treated as CommonJSUse the .mjs extension or add "type": "module" to package.json

Best practices for document loading and chunking

  • Look at your chunks. Print 20 random chunks and read them. If a human can’t understand a chunk alone, the model can’t either.
  • Keep metadata from the start: source, page, section, URL, last updated date. You will need it for citations and filters.
  • Use structure when you have it (headings, pages, FAQ items). Fall back to recursive splitting when you don’t.
  • Clean before you chunk. Remove menus, cookie text and repeated headers; they waste tokens and pollute search results.
  • Measure with a test set. Change one thing at a time (size, overlap, strategy) and re-run the same questions.
  • Treat document text as data. A loaded file can contain text like “ignore your instructions”. Never let document content act as instructions to your bot (more in Part 25).

Practice task

Chunk your own notes:

  1. Put 3 of your own files in docs/: one PDF (any notes or a resume), one Markdown file (a project README works well) and one saved web page.
  2. Run load_docs.py or load_docs.mjs and check that the text looks clean. Fix anything messy.
  3. Write 5 questions with an answer phrase each and add them to compare_chunking.py. Point it at your Markdown file.
  4. Try chunk sizes 100, 300 and 600 with overlap 0 and 20%. Which combination wins?
  5. Bonus: feed chunks.jsonl into the Ollama RAG app from Part 11 and ask your questions for real.

Conclusion

A RAG app is only as good as its chunks. Load each file into clean text with metadata, use the document’s structure when it has one, fall back to a recursive splitter with a little overlap, give every chunk a stable ID and a heading, and test your choices with real questions. With this, you can turn real PDFs, web pages and docs into a knowledge base your LLM can actually use.

Next part → Part 13: Better RAG: Hybrid Search, Re-ranking and Query Rewriting. Our test showed simple matching can pick the wrong chunk. Next we combine keyword and vector search, re-rank the results and rewrite vague questions, so the right chunk comes first.

New posts every day on DevDojo

Follow the full Generative AI series from basics to production. Bookmark devdojo.co.in and open the roadmap above to see what is coming next.

FAQ

What is chunking in RAG?

Chunking is cutting documents into smaller pieces before you create embeddings. Each chunk gets its own vector, so the retriever can find the exact paragraph that answers a question instead of a whole document.

What is the best chunk size for RAG?

There is no single best size. A common starting point is 500–1,000 characters (roughly 100–250 tokens) with 10–20% overlap, adjusted after testing with real questions on your own documents.

Why use chunk overlap?

Overlap repeats a little text at the start of each chunk, so a sentence that falls on a border still appears whole in at least one chunk. It costs a few more chunks, but prevents answers from being split in half.

Do I need LangChain for chunking?

No. You can write simple chunkers in a few lines, as shown above. The langchain-text-splitters and @langchain/textsplitters packages are small and handy, but they are optional.

How do I load PDFs for RAG?

Use a PDF library such as pypdf (Python) or unpdf (Node.js) to extract text page by page and keep the page number as metadata. Scanned PDFs need OCR first because they contain images, not text.

What is semantic chunking?

Semantic chunking uses embeddings to find places where the topic changes and starts a new chunk there. It can help with long unstructured text, but it is slower and costs more, so try recursive or heading-based chunking first.

Share