AI Hints
Home›RAG Tutorial›Context and Variety
RAG · Lesson 64 of 120

Chunk Headers

Add the title back.

⏱ 2 min read▶ Video at 1:03:30🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

When we split a page, most chunks lose its title. A chunk that says, Choose 12 months at 0 percent, doesn't say it's about paying monthly. And some chunks are just a lone heading. Chunk headers fix both.

Chunk Headers
From the video: Chunk Headers
  • Chunks lose the title
  • Lone headings
  • Add the title back

Adding the page title

We take each page's first line as its title. Every chunk gets its title in front, and we drop tiny chunks that are only a heading. Then we check if the fact is in the top three, with and without headers. Run it. Plain chunks miss both facts. With headers, both are found.

headers.pypython
from rag_kit import load_docs, make_chunks, Index

docs = load_docs()
chunks = make_chunks(docs)
titles = {d["source"]: d["text"].splitlines()[0].lstrip("# ") for d in docs}
with_titles = [{**c, "text": titles[c["source"]] + ": " + c["text"]}
               for c in chunks if len(c["text"]) > 40]

plain, headed = Index(chunks), Index(with_titles)
found = lambda index, q, fact: any(fact in c["text"] for s, c in index.search(q, 3))
for q, fact in [("Can I pay monthly?", "0 percent"),
                ("How many hours until my e-bike is full again?", "4 hours")]:
    print("plain:", found(plain, q, fact), " headers:", found(headed, q, fact), "|", q)
Output
plain: False  headers: True | Can I pay monthly?
plain: False  headers: True | How many hours until my e-bike is full again?
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Header tips

Use the page title, and the section heading if you have one. Keep the original text for showing to customers, and use the header version only for search. And merge or drop chunks that are just a heading.

keyvalue
Addpage and section title
Search withheaded text
Showoriginal text
Droplone headings

Summary

Put the page title in front of every chunk, and drop lone headings. Chunks then carry their own context. Next, varied results with MMR.

Key takeaways
  • Title in front
  • Drop lone headings
  • Better matches
Next up: MMR — varied results