RAG · Lesson 47 of 120
Formatting Context
Numbered chunks.
How we lay out the context matters. A wall of text makes it hard for the model to tell chunks apart. Numbered chunks, each with its source, are clearer, and easy to cite.

- A wall of text
- Number each chunk
- Show its source
Numbered chunks
Format context loops over the hits, counting from one. Each chunk gets a number, and its source, then its text. Run it. Each chunk is clearly separated, and labelled.
format_context.pypython
from rag_kit import load_docs, make_chunks, Index
index = Index(make_chunks(load_docs()))
def format_context(hits):
parts = []
for n, (score, c) in enumerate(hits, 1):
parts.append(f"[{n}] {c['source']}\n{c['text'][:60]}...")
return "\n\n".join(parts)
print(format_context(index.search("Can I return a bike I've ridden?")))Output
[1] returns.md ## Change of mind You can return any unused item within 30 d... [2] warranty.md ## Making a claim To make a warranty claim, email photos of ... [3] rentals.md A £150 deposit is taken on a card and released within 3 days...
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]Good context layout
Number the chunks, so the model can cite them as one, two, three. Add the source and title. Keep a blank line between chunks. And remove junk like menus and footers before indexing.
| key | value |
|---|---|
| Numbers | easy to cite |
| Source | where it's from |
| Blank lines | clear breaks |
| No junk | clean first |
Summary
Number each chunk and label its source, so the model can tell them apart and cite them. Next, how much context to send.
Key takeaways- [1] [2] [3]
- Source on each
- Clean text
Next up: The Context Budget — how much to send