374. RAG retrieval: pick the top-k help article chunks for a question
You are building the retrieval step of a help-centre chatbot (RAG). Every help article was split into chunks, and each chunk was embedded into a vector. When a customer asks a question, the question is embedded too, and the k chunks that point most nearly the same way are pasted into the LLM's prompt.
Write top_k_chunks(query, chunks, k). query has shape (d,), chunks has shape (n, d). Return a list of k Python ints (chunk indices, best first). Plain ints matter: the list goes straight into a JSON response, and json.dumps cannot encode np.int64.
Rules:
- Rank by cosine similarity, not the raw dot product. A long chunk vector must not win just because it is long.
- The same paragraph often appears in two articles, so exact ties are common. Round each similarity to 12 decimal places before ranking (so values that differ only by floating point noise count as tied), and break ties by the lower index.
- If k is larger than n, return all n indices.
- Every vector has at least one non-zero entry. Inputs can be lists or NumPy arrays.
def top_k_chunks(query, chunks, k)Cosine similarity between a query and a document
Treat a as the query embedding and b as a document embedding. Retrieval ranks documents by this cosine score.
- a · b
- 3.6
- |a|, |b|
- 2.474, 2.236
- cosine similarity
- 0.6508
- angle
- 49.4°
- projection of a on b
- (0.72, 1.44)
Example 1
Input: top_k_chunks([0.0, 3.0], [[1.0, 0.0], [10.0, 1.0], [0.0, 1.0], [0.7, 0.7], [2.0, 2.0]], 2)
Output: [2, 3]
Explanation: Chunk 2 points exactly along the query. Chunks 3 and 4 point the same way, so they tie and the lower index, 3, comes first.
Example 2
Input: query = [1.0, 1.0], chunks = [[1.0, 0.0], [10.0, 1.0], [0.0, 1.0], [0.7, 0.7], [2.0, 2.0]], k = 3
Output: [3, 4, 1]
Example 3
Input: query = [1.0, 0.0], chunks = [[0.0, 1.0], [2.0, 0.1], [1.0, 1.0]], k = 2
Output: [1, 2]
Constraints
queryhas shape(d,)chunkshas shape(n, d)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 8 tests to be accepted.
Hint 1
Cosine similarity is a dot product between unit vectors, so normalise first and the ranking becomes a matrix-vector product.
Hint 2
Divide each chunk row by its norm and the query by its norm, compute all scores with one matrix product, then sort indices by score descending, breaking ties by lower index.
Hint 3
Sort with a key like (-score, index) and take the first k. Rounding scores slightly (for example to 12 decimals) before sorting stops tiny float noise from breaking ties that should be exact, as in the example where [0.7, 0.7] and [2.0, 2.0] point the same way.
Common mistakes
- The buggy version ranks by raw dot product.
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.
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.
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.