
Top chunks by cosine similarity
mediumTop 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
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 = 2Output
["a", "c"]
Example 2
Input
query = [1, 1], documents = [{"id": "x", "vector": [1, 1]}, {"id": "y", "vector": [2, 2]}], k = 2Output
["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.
- Similarity
Similar questions
Company
Cohere
Difficulty
medium
Topic
RAG
Language
Python
Your code
Loading Python in the background. You can start writing.