Turn text into vectors and measure how close two vectors point. The closest document is the one RAG retrieves.
AI · intermediate · 8 min · 30 steps · free
import math
VOCAB = ['refund', 'money', 'back', 'ship', 'open']
def embed(text):
words = text.lower().split()
return [words.count(w) for w in VOCAB]
def cosine(a, b):
size = math.hypot(*a) * math.hypot(*b)
return math.sumprod(a, b) / size if size else 0.0
docs = ['refund money back', 'refund on shipping fees', 'shop is open daily']
query = embed('how do i get my money back refund')
scores = [round(cosine(query, embed(d)), 2) for d in docs]
best = docs[scores.index(max(scores))]
print(best, scores)math module, so the program can use the functions it provides.embed(). Its body does not run yet: it runs each time the function is called.cosine(). Its body does not run yet: it runs each time the function is called.docs is created and points to a new list: ['refund money back', 'refund on shipping fees', 'shop is open daily'].embed(), with text = 'how do i get my money back refund'. It gets its own names.words is created and points to a new list: ['how', 'do', 'i', 'get', 'my', 'money', 'back', 'refund'].[words.count(w) for w in VOCAB].embed(), with text = 'refund money back'. It gets its own names.words is created and points to a new list: ['refund', 'money', 'back'].[words.count(w) for w in VOCAB].size is the length of each vector multiplied together.math.sumprod(a, b) / size if size else 0.0.embed(), with text = 'refund on shipping fees'. It gets its own names. cosine() has finished, so its names are gone.words is created and points to a new list: ['refund', 'on', 'shipping', 'fees'].[words.count(w) for w in VOCAB].size is created with the value 1.73205.math.sumprod(a, b) / size if size else 0.0.embed(), with text = 'shop is open daily'. It gets its own names. cosine() has finished, so its names are gone.words is created and points to a new list: ['shop', 'is', 'open', 'daily'].[words.count(w) for w in VOCAB].cosine(), with a = [1, 1, 1, 0, 0] and b = [0, 0, 0, 0, 1]. It gets its own names. embed() has finished, so its names are gone.size is created with the value 1.73205.math.sumprod(a, b) / size if size else 0.0.cosine() has finished, so its names are gone. The value it returned, [1, 0.58, 0], is stored in scores.refund money back [1.0, 0.58, 0.0].Answer: 1
Answer: So long documents do not win just for being long