Sub topic 15
Using Retrieval in Applications: RAG, Clustering, Deduplication, Recommendations
This chapter assumes you can already embed text with a pretrained model, compute cosine similarity with a matrix product, and chunk documents. Here you apply those pieces to four common jobs: answering questions with a language model, grouping texts, removing near-duplicates, and recommending items. All four use the same primitive. You turn texts into unit-length vectors and compare them by dot product.
One primitive, four jobs
With unit-length vectors, emb @ q gives the cosine similarity of every stored text to a query. Each application asks a different question of those scores.
| Application | Question asked of the vectors | Typical operation |
|---|---|---|
| Retrieval-augmented generation (RAG) | Which chunks help answer this question? | Top-k by similarity to a query |
| Clustering | Which texts belong together? | Group nearby vectors |
| Deduplication | Which texts say the same thing? | Pairs above a similarity threshold |
| Recommendations | What is similar to what this user liked? | Top-k to an averaged vector |
Retrieval-augmented generation
A language model only knows what was in its training data and its prompt. RAG puts retrieved text into the prompt, so the model can answer from your documents. It can also cite them.
The retrieval half is the semantic search you already built. The new work is building the prompt and handling retrieval that finds nothing useful.
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
chunks = [
"Refunds are available within 30 days of purchase with a receipt.",
"To reset your password, open Settings and choose Security.",
"Our support team answers email from 9 to 5 on weekdays.",
]
chunk_emb = model.encode(chunks, normalize_embeddings=True)
def retrieve(question, k=2, min_score=0.25):
q = model.encode(question, normalize_embeddings=True)
scores = chunk_emb @ q
order = np.argsort(-scores)[:k]
return [(int(i), float(scores[i])) for i in order if scores[i] >= min_score]
def build_prompt(question, k=2):
hits = retrieve(question, k)
if not hits:
return None # nothing relevant: do not call the model with an empty context
context = "\n".join(f"[{i}] {chunks[i]}" for i, _ in hits)
return (
"Answer using only the numbered context below. "
"Cite the numbers you used. If the context does not contain the answer, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
)
prompt = build_prompt("How long do I have to return an item?")
print(prompt if prompt else "No relevant context found.")The prompt text goes to whichever language model you use. That call is outside this chapter, and the code above stops where it would happen.
Where RAG fails
Most RAG failures are retrieval failures, so inspect retrieved chunks before blaming the model.
- Retrieval miss. The answer is in the corpus but not in the top k. Check recall@k on labeled questions, and consider hybrid search or reranking.
- Score floor. Without
min_score, top-k always returns something, even for off-topic questions. The model then answers from irrelevant text. Pick the threshold from your own score distribution, since it depends on the model. - Context overload. Raising k adds noise. Retrieve more candidates (for example 20), rerank, and pass only the best few.
- Chunk boundaries. An answer split across two chunks may be retrieved half-complete. Overlap and sensible chunk sizes help.
- Stale index. When a source document changes, re-embed its chunks and delete the old ones. Store a document id and a version with each chunk.
Clustering
Clustering groups texts without labels, which is useful for exploring a support inbox or finding themes in survey answers. K-means works well on normalized embeddings. For unit vectors, minimizing squared Euclidean distance orders points the same way as maximizing cosine similarity, because the two are linked: ||a - b||² = 2 - 2·cos(a, b).
from collections import defaultdict
from sentence_transformers import SentenceTransformer
from sklearn.cluster import KMeans
model = SentenceTransformer("all-MiniLM-L6-v2")
texts = [
"My card was charged twice this month",
"Please refund the duplicate payment",
"Invoice shows the wrong amount",
"The app crashes when I open settings",
"Screen freezes after the latest update",
"Login page never finishes loading",
]
emb = model.encode(texts, normalize_embeddings=True)
labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(emb)
groups = defaultdict(list)
for text, label in zip(texts, labels):
groups[int(label)].append(text)
for label, members in sorted(groups.items()):
print(label, members)K-means needs the number of clusters in advance. Try several values and read samples from each cluster. Density-based methods such as HDBSCAN pick the count themselves and can mark outliers as noise, but they need tuning of their own. For large corpora, embeddings are often reduced to fewer dimensions with PCA or UMAP before clustering. The cluster labels you present to users still have to come from reading the members, or from asking a language model to summarize them.
Deduplication
Exact deduplication hashes the text. Embeddings catch near-duplicates: reposted articles, reworded product listings, or the same question asked twice. The approach is to find pairs whose similarity is above a threshold, then keep one item from each group.
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
def near_duplicate_pairs(emb, threshold=0.9):
sims = emb @ emb.T
rows, cols = np.triu_indices(len(emb), k=1) # each pair once, no self-pairs
mask = sims[rows, cols] >= threshold
return [(int(i), int(j), float(sims[i, j])) for i, j in zip(rows[mask], cols[mask])]
def keep_first(emb, threshold=0.9):
kept = []
for i in range(len(emb)):
if all(float(emb[i] @ emb[j]) < threshold for j in kept):
kept.append(i)
return kept
texts = [
"How do I reset my password?",
"How can I reset my password?",
"What are your opening hours?",
]
emb = model.encode(texts, normalize_embeddings=True)
print(near_duplicate_pairs(emb, 0.85))
print(keep_first(emb, 0.85))Some limits matter in practice:
- Threshold. It depends on the model and the text length. Label a sample of pairs as duplicate or not, then choose the value that gives the precision you need.
- Cost. The full similarity matrix is n by n. At 100,000 texts that is 10 billion floats, which will not fit in memory. At that size, query an approximate index for each item's nearest neighbors and apply the threshold to those results.
- Meaning, not wording. Embeddings can rate "Order 1001 shipped" and "Order 1002 shipped" as nearly identical. If small details matter, such as numbers, names, or negation, confirm candidate pairs with a string comparison before deleting anything.
- Chains. Keep-first is simple but depends on order. If A is close to B and B to C but A is far from C, the result is not unique. Review borderline cases.
Recommendations
Item-to-item recommendation embeds each item's description. A user's taste profile is the average of the vectors of items they liked. You then rank all items by similarity to that profile, excluding items the user already has.
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
items = [
"Beginner guide to baking sourdough bread",
"Advanced pastry techniques for home bakers",
"Intro to trail running and ultramarathons",
"Training plans for your first half marathon",
"Knife skills every home cook should know",
]
item_emb = model.encode(items, normalize_embeddings=True)
def recommend(liked_ids, k=2):
profile = item_emb[liked_ids].mean(axis=0)
profile = profile / np.linalg.norm(profile) # re-normalize after averaging
scores = item_emb @ profile
scores[liked_ids] = -np.inf # never recommend what they already liked
top = np.argsort(-scores)[:k]
return [(items[int(i)], float(scores[i])) for i in top]
for title, score in recommend([0]):
print(f"{score:.3f} {title}")The mean of unit vectors is shorter than one, so re-normalize it. The ranking would not change, but the scores would be on a different scale from other cosine values you compare against.
Content-based recommendation needs no interaction history from other users, so it works for a new item on day one. It cannot discover taste patterns that text does not show, such as people who buy both an item and an unrelated accessory. Production systems usually blend it with signals from clicks and purchases. A user with several different interests also gets a muddy average. One fix is to cluster their liked items and search once per cluster.
Choosing a setup
| Situation | Reasonable choice |
|---|---|
| Under about 100,000 items, static or rarely changing | Exact search with a matrix product |
| Millions of items, or low latency required | Approximate index (HNSW or IVF) in a library or vector database |
| Queries contain product codes, names, or rare terms | Hybrid search with rank fusion |
| Top results look related but the best one is not first | Add a cross-encoder reranker |
| Corpus changes daily | A vector database with upserts and deletes, plus document versions |
Exercise
Exercise
A RAG assistant answers an off-topic question ("What's the capital of France?") with a confident but irrelevant answer built from a refund-policy chunk. Retrieval ran with k=3 and no score floor. Give two changes to the retrieval step that would prevent this, and explain why each helps.
Show answer
First, add a minimum similarity threshold, calibrated on your own data. Top-k always returns k results, even when none are relevant, so a floor lets retrieval return nothing, and the app can then say it has no answer instead of calling the model with unrelated context. Second, tell the model in the prompt to answer only from the provided context and to say so when the context lacks the answer. You can also route low-scoring queries to a fallback response. A reranker's relevance score can serve as a more reliable floor than a bi-encoder cosine score.
Exercise
You need to deduplicate 2 million product descriptions. Why is the keep_first approach with a full n-by-n similarity matrix a poor fit, and what would you do instead?
Show answer
The similarity matrix holds about 4 trillion values, which does not fit in memory, and a loop comparing each item to every kept item is also too slow. Instead, build an approximate nearest-neighbor index (HNSW or IVF). For each item, retrieve its top few neighbors and apply the similarity threshold only to those. Then group the flagged pairs and confirm borderline matches with a string or attribute check before deleting.