Log inBook a Demo
BuildMidData / MLAuto-graded

Rank documents by cosine similarity for RAG retrieval

Return the k documents closest to a query, with scores rounded to 6 places and ties broken by id.search(query_vec, corpus, k) is the retrieval step of a RAG pipeline: it takes a query vector and returns the k closest documents with their scores. On some corpora it picks the wrong documents, puts them in the wrong order and reports scores that look off. Make it rank by cosine similarity, highest first, report each score rounded to 6 decimal places, and break ties by id. The vectors are plain data, so there is no model or embeddings API involved.
30 min
python

You're done when

  • The top result is the document most similar to the query by cosine similarity.
  • When k is smaller than the corpus, exactly k results come back.
  • k = 0 returns an empty list.
  • When k is larger than the corpus, every document comes back, with no error.
  • Results are ordered from most to least similar.

What it measures

Retrieval fundamentalsRanking and scoring results by cosine similarity, as the contract asks.
Working with vectorsHandling the vectors so each score reflects how close a document is to the query.
Edge casesGetting `k` right at zero, below and above the corpus size, and ordering ties by `id`.

Your environment

Terminal + editorA full shell in the browser
Coding agentAlready signed in, no API key to set up
Isolated workspaceOnly yours, wiped when you finish

Start this lab

30 min
Start labYou'll need to sign in to Anthropos first. The lab opens in a private cloud workspace with your coding agent ready to use.
AI Labs is part of Anthropos Workforce. Not on your plan yet? Book a demo