Frame · dsa / ai-algorithms / 06-maximal-marginal-relevance.jsJavaScript
Maximal Marginal Relevance for Diverse Retrieval
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Maximal Marginal Relevance for Diverse Retrieval
Problem: Top-k similarity search often returns near-duplicate chunks that
waste the context window. MMR picks results one at a time, balancing
relevance to the query against redundancy with what is already picked:
MMR(d) = lambda * sim(q, d) - (1 - lambda) * max over s in S of sim(d, s)
(the penalty is 0 when S is empty). Given a query embedding, candidates
`{ id, vector }`, `k` and `lambda` in [0, 1], return the ids of the k
selected candidates in selection order, using cosine similarity. Ties go to
the candidate with the lower index.
Constraints:
- 1 <= candidates.length <= 10^4, 1 <= k
Example:
q = [1, 0]; a = [1, 0.1], b = [1, 0.11] (near-duplicate of a),
c = [0.6, -0.8]; k = 2
lambda = 1 -> ["a", "b"] (pure relevance)
lambda = 0.5 -> ["a", "c"] (b is penalised for redundancy)
Approach: Pre-compute query similarities. Keep, for every unselected
candidate, its max similarity to the selected set and update it
incrementally after each pick, so each round is O(n * d). Total time
O(k * n * d), space O(n).
@param {number[]} query
@param {{ id: string, vector: number[] }[]} candidates
@param {number} k
@param {number} [lambda]
@returns {string[]}