Lesson 3 of 5 · 2 min
Retrieval, and checking it first
To retrieve, turn the question and every chunk into vectors and take the closest. This toy uses word counts; real systems use learned embeddings, which also match different words with the same meaning.
import math, re
from collections import Counter
docs = ["refunds are accepted within thirty days", "damaged items can be returned at any time", "our office is closed on sunday"]
def vec(s): return Counter(re.findall(r"[a-z]+", s.lower()))
def cosine(a, b):
dot = sum(a[k] * b[k] for k in a)
return dot / (math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values())) or 1)
for q in ["can I return a damaged item", "when are refunds accepted", "money back?"]:
best = max(docs, key=lambda d: cosine(vec(q), vec(d)))
print(f"{q:32} -> {best}")
Look at the last line. "money back" shares no words with the refund sentence, so word counting fails. When an answer is wrong, print the retrieved chunks before touching the prompt.
