AI Hints
Home›RAG Tutorial›Working with Indexes
RAG · Lesson 36 of 120

Top-k and Scores

How many to fetch.

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

How many chunks should we fetch? That number is called k. Too few, and we might miss the answer. Too many, and we flood the prompt with noise. Scores can help us decide.

Top-k and Scores
From the video: Top-k and Scores
  • k chunks
  • Too few: miss
  • Too many: noise

Looking at the scores

We search for the York store's opening hours, and print the top six, with their scores. Run it. The stores page is clearly ahead, then the scores drop off. A minimum score, here zero point three, cuts the weak matches.

top_k.pypython
from rag_kit import load_docs, make_chunks, Index

index = Index(make_chunks(load_docs()))

hits = index.search("When is the York shop open?", k=6)
for score, chunk in hits:
    print(score, chunk["source"])

good = [c for s, c in hits if s >= 0.3]
print("kept", len(good), "of", len(hits))
Output
0.54 stores.md
0.38 stores.md
0.36 servicing.md
0.35 stores.md
0.31 shipping.md
0.26 shipping.md
kept 5 of 6
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
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]

Choosing k

Start with k between three and five for short chunks. Fetch more, like twenty, when a reranker will pick the best ones later. And remember, score thresholds depend on the model, so set them by testing, not by guessing.

keyvalue
Short chunksk = 3 to 5
With rerankerfetch 20
Thresholdsset by testing
Scoresmodel specific

Summary

k decides how many chunks we fetch. Look at the scores, and use a threshold to drop weak matches. Next, approximate search.

Key takeaways
  • k = 3 to 5
  • Scores drop off
  • Minimum score
Next up: Approximate Search — speed versus exactness