Top chunks by cosine similarity

Top chunks by cosine similarity

Cohere RAG Interview Question

Retrieval comes down to one comparison: how close is the question's embedding to each document's embedding. Cohere ranks by cosine similarity, written below for a query q and a document d.

Write a function top_k(query, documents, k) that returns the ids of the k documents closest to the query. The documents are a list of dictionaries, each with an id and a vector. Sort by similarity from high to low, and break ties by id in alphabetical order. A document whose vector is all zeros has a similarity of 0.

Note

similarity(q,d)=q⋅d∥q∥ ∥d∥\text{similarity}(q, d) = \frac{q \cdot d}{\lVert q \rVert \, \lVert d \rVert}
∥v∥=∑ivi2\lVert v \rVert = \sqrt{\sum_i v_i^2}

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

query = [1, 0], documents = [{"id": "a", "vector": [2, 0]}, {"id": "b", "vector": [0, 5]}, {"id": "c", "vector": [1, 1]}], k = 2

Output

["a", "c"]

Example 2

Input

query = [1, 1], documents = [{"id": "x", "vector": [1, 1]}, {"id": "y", "vector": [2, 2]}], k = 2

Output

["x", "y"]

Explanation

In the first example "a" points the same way as the query, so its similarity is 1. "b" is at right angles to it, giving 0, and "c" sits between the two. The top 2 are therefore "a" and "c".

Submit also runs 2 hidden test cases that check edge cases.

Similar questions