Retrieve the closest chunks for a question by cosine similarity.
def cosine_similarity(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = sum(x * x for x in a) ** 0.5
norm_b = sum(y * y for y in b) ** 0.5
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
question = "How do models improve?"
q_vec = embed(question)
print("Top retrieved chunks for the question:")
scored = sorted(((cosine_similarity(q_vec, emb), chunk) for chunk, emb in vector_db), reverse=True)
for score, chunk in scored[:3]:
print(" similarity=%.4f %s" % (score, chunk[:40]))
print("Context window only loads relevant chunks: True")
Before you run it, say out loud what it will print. Then open the answer.
What it prints
Top retrieved chunks for the question:
similarity=0.9663 learning models improve with data. Vecto
similarity=0.9657 Machine learning models improve with dat
similarity=0.9637 models improve with data. Vector databa
Context window only loads relevant chunks: True