Recency and Relevance Memory Scoring
Problem Statement
Rank agent memories by a weighted blend of relevance (similarity to the query) and recency (how recently the memory was accessed), returning the top-k memory ids.
Background
A common retrieval score is score = alpha * relevance + (1 - alpha) * recency, where both components are in [0, 1]. Recency is derived from an age: recency = 1 / (1 + age) so newer (smaller age) memories score higher. Ties are broken by smaller id for determinism.
Your Task
Implement:
def rank_memories(memories, alpha, k):
- memories: list of {"id": int, "relevance": float, "age": float}.
- Compute score = alpharelevance + (1-alpha)(1/(1+age)).
- Return the ids of the top k by score (desc), ties broken by smaller id.
Input Format
- memories (list of dicts), alpha (float in [0,1]), k (int).
Output Format
- A list of ints (memory ids).
Sample
mem = [{"id":1,"relevance":0.9,"age":10},{"id":2,"relevance":0.4,"age":0}]
print(rank_memories(mem, 0.5, 1))
Output:
[2]
Example
mem = [{"id":1,"relevance":0.9,"age":10},{"id":2,"relevance":0.4,"age":0}]
print(rank_memories(mem, 0.5, 1))[2]
- Calculate the recency component for each memory using the formula :
- For Memory 1 (age 10):
- For Memory 2 (age 0):
- Compute the total score for each memory using the weighted blend with :
- Memory 1:
- Memory 2:
- Rank the memories by score in descending order to determine the top candidates:
- Memory 2 has a score of
- Memory 1 has a score of
- Since , Memory 2 is ranked first.
- Select the top memories where , which corresponds to the single highest-ranked item, Memory 2.
- The final output is [2]
Constraints
0 <= alpha <= 1,age >= 0,0 <= relevance <= 1.recency = 1/(1+age).- Sort by score desc, then id asc; return the first
kids.