Sub topic 15
Using retrieval in applications: RAG, clustering, deduplication, recommendations
This chapter assumes you can generate embeddings with a pretrained model, compute cosine similarity, and run a top-k search over a set of vectors. It shows how that one capability supports four common applications.
One building block, several uses
Every application below uses the same operation: embed texts, then ask which vectors are close to which. The applications differ in what you compare and what you do with the result.
| Application | Compare | Action on the result |
|---|---|---|
| Retrieval-augmented generation (RAG) | Question against document chunks | Paste the top chunks into a prompt |
| Clustering | Every item against every other | Group items with similar vectors |
| Deduplication | Item pairs above a high threshold | Drop or merge near-copies |
| Recommendations | Item or user profile against items | Suggest the nearest unseen items |
Retrieval-augmented generation
A language model only knows what was in its training data. RAG supplies current or private facts at question time. The flow is:
- Split documents into chunks and embed them once, ahead of time.
- Embed the user's question.
- Retrieve the top-k chunks.
- Build a prompt that contains those chunks and the question.
- Send the prompt to a language model.
The retrieval step sets the ceiling on answer quality. If the right chunk is not in the top k, the model cannot use it, and it may answer from guesswork. The metrics from the evaluation chapter, such as recall@k, apply directly here.
def build_prompt(question, chunks):
context = "\n\n".join(f"[{i + 1}] {c}" for i, c in enumerate(chunks))
return (
"Answer using only the context below. "
"If the context does not contain the answer, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
chunks = ["Passwords can be reset under Settings > Security."]
print(build_prompt("How do I reset my password?", chunks))Numbering the chunks lets the model cite its sources, and the "say so" instruction reduces invented answers.
Clustering and deduplication
Clustering groups texts by meaning without labels. Run k-means on the embeddings and read a few items from each group to name it.
import numpy as np
from sklearn.cluster import KMeans
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
texts = [
"How do I reset my password?",
"Steps to recover access to your account",
"The cafeteria serves lunch at noon",
"Lunch is available in the canteen at 12",
]
emb = model.encode(texts, normalize_embeddings=True)
labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(emb)
print(labels)
# Deduplication: flag pairs whose cosine similarity is above a threshold.
sims = emb @ emb.T
threshold = 0.85
for i in range(len(texts)):
for j in range(i + 1, len(texts)):
if sims[i, j] >= threshold:
print("near-duplicate:", texts[i], "|", texts[j])Clustering needs you to choose the number of clusters. Deduplication needs a threshold. Neither value transfers between models, so inspect pairs near the cutoff by hand and adjust. The full pairwise matrix grows with the square of the item count, so for large collections use an approximate nearest-neighbor index and check only each item's closest neighbors.
Recommendations
For "more like this", embed the items and return the nearest neighbors of the item a user is viewing, excluding that item. For personalized suggestions, average the embeddings of items the user liked and search with that mean vector.
def recommend(item_embeddings, liked_ids, k=3):
profile = item_embeddings[liked_ids].mean(axis=0)
profile = profile / np.linalg.norm(profile)
scores = item_embeddings @ profile
scores[liked_ids] = -np.inf # do not suggest what the user already has
return np.argsort(-scores)[:k]This content-based approach works for new items with no interaction history. It cannot learn from behavior, so many systems blend it with click or purchase signals.
Pitfalls
- Retrieved chunks can be off-topic. Rerank, or drop chunks below a score cutoff, instead of always passing k results.
- Duplicate chunks waste prompt space in RAG. The deduplication step above also helps there.
- Similar is not the same as relevant. Recommending near-identical items gives users little variety.
Exercise
In the recommend function, why is the score of each liked item set to negative infinity before sorting?
Show answer
Items the user already liked are, by construction, very close to the profile vector, so they would rank at the top. Setting their score to negative infinity removes them from the results, so only unseen items are suggested.
Exercise
A RAG system gives wrong answers even though the language model is strong. Which measurement would you take first, and why?
Show answer
Measure recall@k of the retrieval step on labeled questions. If the relevant chunk is often missing from the top k, the model never sees the needed facts, so the fix belongs in chunking, the embedding model, hybrid search, or reranking, not in the language model.