Retrieve the top-k chunks for a query embedding

The retrieval step of RAG: you have one query embedding and a matrix of chunk embeddings. Return the indices of the k most similar chunks by cosine similarity, best first. Break ties by lower index.

Write top_k_chunks(query, chunks, k). query is (d,), chunks is (n, d). Return a list of ints.

Signaturedef top_k_chunks(query, chunks, k)

Understand the idea

The retrieval step of RAG finds the chunks whose embeddings point in the most similar direction to the query. Cosine similarity ignores vector length, so a chunk cannot win just because its vector is large. Think of comparing which way arrows point, not how long they are. Worked example: query [1, 0], chunks [[10, 10], [1, 0], [0, 1], [2, 0]], k = 2. Cosines: chunk 0 is 10 / (1 x 14.14) = 0.707, chunk 1 is 1, chunk 2 is 0, chunk 3 is 2 / 2 = 1. Chunks 1 and 3 tie at 1, so the lower index comes first: answer [1, 3]. A raw dot product would wrongly rank chunk 0 first with score 10. Rule: score_i = (q . c_i) / (|q| |c_i|); sort descending with a stable sort so ties keep lower index; take the first k. Every RAG system, from chat-with-your-PDF apps to enterprise search, runs this step before calling the LLM.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 2.

  • Sample 1: long vector does not win by lengthtop_k_chunks([1.0, 1.0], _C, 3)
  • Sample 2: axis querytop_k_chunks([0.0, 3.0], _C, 2)