-
Notifications
You must be signed in to change notification settings - Fork 74
feat(agent-memory): Phase 2 — recall() ranking #249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jamby77
wants to merge
2
commits into
feature/agent-memory-phase1-remember
Choose a base branch
from
feature/agent-memory-phase2-recall
base: feature/agent-memory-phase1-remember
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+431
−2
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
packages/agent-memory/src/__tests__/MemoryStore.recall.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import { describe, it, expect, vi } from 'vitest'; | ||
| import { MemoryStore } from '../MemoryStore'; | ||
| import { fakeEmbed } from './helpers/fakeEmbed'; | ||
| import { mockClient } from './helpers/mockClient'; | ||
|
|
||
| interface Row { | ||
| key: string; | ||
| fields: Record<string, string>; | ||
| } | ||
|
|
||
| function searchReply(rows: Row[]): unknown[] { | ||
| const out: unknown[] = [String(rows.length)]; | ||
| for (const row of rows) { | ||
| out.push(row.key); | ||
| const flat: string[] = []; | ||
| for (const [field, value] of Object.entries(row.fields)) { | ||
| flat.push(field, value); | ||
| } | ||
| out.push(flat); | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| const now = Date.now(); | ||
| function baseFields(over: Record<string, string>): Record<string, string> { | ||
| return { | ||
| content: 'c', | ||
| importance: '0.5', | ||
| tags: '', | ||
| created_at: String(now), | ||
| last_accessed_at: String(now), | ||
| access_count: '0', | ||
| ...over, | ||
| }; | ||
| } | ||
|
|
||
| describe('MemoryStore.recall', () => { | ||
| it('embeds the query, runs a widened KNN FT.SEARCH, and returns ranked hits capped at k', async () => { | ||
| const embedFn = vi.fn(fakeEmbed(8)); | ||
| const reply = searchReply([ | ||
| { key: 'mem:mem:a', fields: baseFields({ content: 'closer', __score: '0.1' }) }, | ||
| { key: 'mem:mem:b', fields: baseFields({ content: 'farther', __score: '0.6' }) }, | ||
| ]); | ||
| const client = mockClient((command) => (command === 'FT.SEARCH' ? reply : 'OK')); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn }); | ||
|
|
||
| const hits = await store.recall('what does the user prefer', { | ||
| k: 2, | ||
| threshold: 1, | ||
| threadId: 't1', | ||
| tags: ['x'], | ||
| }); | ||
|
|
||
| expect(embedFn).toHaveBeenCalledWith('what does the user prefer'); | ||
| const search = client.call.mock.calls.find((args) => args[0] === 'FT.SEARCH'); | ||
| expect(search?.[1]).toBe('mem:mem:idx'); | ||
| // internal k widened to k*4 = 8 | ||
| expect(search?.[2]).toBe('(@threadId:{t1} @tags:{x})=>[KNN 8 @vector $vec AS __score]'); | ||
| expect(search).toContain('8'); | ||
|
|
||
| expect(hits).toHaveLength(2); | ||
| expect(hits[0].item.id).toBe('a'); | ||
| expect(hits[0].item.content).toBe('closer'); | ||
| expect(hits[0].similarity).toBe(0.1); | ||
| expect(hits[0].score).toBeGreaterThan(hits[1].score); | ||
| }); | ||
|
|
||
| it('drops candidates beyond the distance threshold', async () => { | ||
| const reply = searchReply([ | ||
| { key: 'mem:mem:a', fields: baseFields({ __score: '0.1' }) }, | ||
| { key: 'mem:mem:b', fields: baseFields({ __score: '0.9' }) }, | ||
| ]); | ||
| const client = mockClient((command) => (command === 'FT.SEARCH' ? reply : 'OK')); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const hits = await store.recall('q', { k: 5, threshold: 0.3 }); | ||
|
|
||
| expect(hits.map((h) => h.item.id)).toEqual(['a']); | ||
| }); | ||
|
|
||
| it('drops candidates whose distance score is missing or non-numeric', async () => { | ||
| const reply = searchReply([ | ||
| { key: 'mem:mem:a', fields: baseFields({ __score: '0.1' }) }, | ||
| { key: 'mem:mem:b', fields: baseFields({}) }, | ||
| ]); | ||
| const client = mockClient((command) => (command === 'FT.SEARCH' ? reply : 'OK')); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const hits = await store.recall('q', { k: 5, threshold: 1 }); | ||
|
|
||
| expect(hits.map((h) => h.item.id)).toEqual(['a']); | ||
| }); | ||
|
|
||
| it('drops a candidate whose distance score is empty (not treated as 0)', async () => { | ||
| const reply = searchReply([ | ||
| { key: 'mem:mem:a', fields: baseFields({ __score: '0.1' }) }, | ||
| { key: 'mem:mem:b', fields: baseFields({ __score: ' ' }) }, | ||
| ]); | ||
| const client = mockClient((command) => (command === 'FT.SEARCH' ? reply : 'OK')); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const hits = await store.recall('q', { k: 5, threshold: 1 }); | ||
|
|
||
| expect(hits.map((h) => h.item.id)).toEqual(['a']); | ||
| }); | ||
|
|
||
| it('drops a candidate whose composite score is NaN (malformed importance)', async () => { | ||
| const reply = searchReply([ | ||
| { key: 'mem:mem:a', fields: baseFields({ __score: '0.1' }) }, | ||
| { key: 'mem:mem:b', fields: baseFields({ __score: '0.1', importance: 'not-a-number' }) }, | ||
| ]); | ||
| const client = mockClient((command) => (command === 'FT.SEARCH' ? reply : 'OK')); | ||
| const store = new MemoryStore({ client, name: 'mem', embedFn: fakeEmbed(8) }); | ||
|
|
||
| const hits = await store.recall('q', { k: 5, threshold: 1 }); | ||
|
|
||
| expect(hits.map((h) => h.item.id)).toEqual(['a']); | ||
| }); | ||
| }); |
20 changes: 20 additions & 0 deletions
20
packages/agent-memory/src/__tests__/buildRecallQuery.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { buildRecallQuery } from '../buildRecallQuery'; | ||
|
|
||
| describe('buildRecallQuery', () => { | ||
| it('builds a bare KNN query when there are no filters', () => { | ||
| expect(buildRecallQuery(32, {}, [])).toBe('*=>[KNN 32 @vector $vec AS __score]'); | ||
| }); | ||
|
|
||
| it('filters by scope and tags with AND semantics', () => { | ||
| expect(buildRecallQuery(8, { threadId: 't1', namespace: 'user:1' }, ['pref'])).toBe( | ||
| '(@threadId:{t1} @namespace:{user\\:1} @tags:{pref})=>[KNN 8 @vector $vec AS __score]', | ||
| ); | ||
| }); | ||
|
|
||
| it('escapes scope and tag values', () => { | ||
| expect(buildRecallQuery(8, { agentId: 'a:b' }, ['x y'])).toBe( | ||
| '(@agentId:{a\\:b} @tags:{x\\ y})=>[KNN 8 @vector $vec AS __score]', | ||
| ); | ||
| }); | ||
| }); |
72 changes: 72 additions & 0 deletions
72
packages/agent-memory/src/__tests__/compositeScore.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
| import { compositeScore } from '../compositeScore'; | ||
|
|
||
| const W = { similarity: 0.6, recency: 0.25, importance: 0.15 }; | ||
| const HALF = 604800; // 7 days | ||
|
|
||
| describe('compositeScore', () => { | ||
| it('decays recency to ~0.5 at one half-life', () => { | ||
| const score = compositeScore({ | ||
| similarity: 0, | ||
| importance: 0, | ||
| ageSeconds: HALF, | ||
| weights: { similarity: 0, recency: 1, importance: 0 }, | ||
| halfLifeSeconds: HALF, | ||
| }); | ||
| expect(score).toBeCloseTo(0.5, 5); | ||
| }); | ||
|
|
||
| it('combines weighted similarity, recency, and importance', () => { | ||
| const score = compositeScore({ | ||
| similarity: 1, | ||
| importance: 1, | ||
| ageSeconds: 0, | ||
| weights: W, | ||
| halfLifeSeconds: HALF, | ||
| }); | ||
| expect(score).toBeCloseTo(1, 5); | ||
| }); | ||
|
|
||
| it('ranks an identical recent match above a distant one', () => { | ||
| const identical = compositeScore({ | ||
| similarity: 1, | ||
| importance: 0.5, | ||
| ageSeconds: 0, | ||
| weights: W, | ||
| halfLifeSeconds: HALF, | ||
| }); | ||
| const distant = compositeScore({ | ||
| similarity: 0.2, | ||
| importance: 0.5, | ||
| ageSeconds: 0, | ||
| weights: W, | ||
| halfLifeSeconds: HALF, | ||
| }); | ||
| expect(identical).toBeGreaterThan(distant); | ||
| }); | ||
|
|
||
| it('lets recency promote a recent-but-weaker item over an old-but-closer one', () => { | ||
| const recentWeaker = compositeScore({ | ||
| similarity: 0.6, | ||
| importance: 0.5, | ||
| ageSeconds: 0, | ||
| weights: W, | ||
| halfLifeSeconds: HALF, | ||
| }); | ||
| const oldCloser = compositeScore({ | ||
| similarity: 0.8, | ||
| importance: 0.5, | ||
| ageSeconds: HALF * 5, | ||
| weights: W, | ||
| halfLifeSeconds: HALF, | ||
| }); | ||
| expect(recentWeaker).toBeGreaterThan(oldCloser); | ||
| }); | ||
|
|
||
| it('breaks ties by importance', () => { | ||
| const base = { similarity: 0.5, ageSeconds: 0, weights: W, halfLifeSeconds: HALF }; | ||
| const high = compositeScore({ ...base, importance: 0.9 }); | ||
| const low = compositeScore({ ...base, importance: 0.1 }); | ||
| expect(high).toBeGreaterThan(low); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { escapeTag } from '@betterdb/valkey-search-kit'; | ||
| import type { MemoryScope } from './types'; | ||
|
|
||
| export const SCORE_FIELD = '__score'; | ||
| export const VECTOR_FIELD = 'vector'; | ||
|
|
||
| export function buildRecallQuery(k: number, scope: MemoryScope, tags: string[]): string { | ||
| const clauses: string[] = []; | ||
| if (scope.threadId !== undefined) { | ||
| clauses.push(`@threadId:{${escapeTag(scope.threadId)}}`); | ||
| } | ||
| if (scope.agentId !== undefined) { | ||
| clauses.push(`@agentId:{${escapeTag(scope.agentId)}}`); | ||
| } | ||
| if (scope.namespace !== undefined) { | ||
| clauses.push(`@namespace:{${escapeTag(scope.namespace)}}`); | ||
| } | ||
| for (const tag of tags) { | ||
| clauses.push(`@tags:{${escapeTag(tag)}}`); | ||
| } | ||
| const filterExpr = clauses.length > 0 ? `(${clauses.join(' ')})` : '*'; | ||
| return `${filterExpr}=>[KNN ${k} @${VECTOR_FIELD} $vec AS ${SCORE_FIELD}]`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| export interface RecallWeights { | ||
| similarity: number; | ||
| recency: number; | ||
| importance: number; | ||
| } | ||
|
|
||
| export interface CompositeScoreParams { | ||
| similarity: number; // 0..1, mapped from cosine distance | ||
| ageSeconds: number; | ||
| importance: number; // 0..1 | ||
| weights: RecallWeights; | ||
| halfLifeSeconds: number; | ||
| } | ||
|
|
||
| /** | ||
| * Weighted blend of semantic similarity, recency, and importance. | ||
| * Recency is a true half-life decay: 0.5 at one halfLifeSeconds. | ||
| */ | ||
| export function compositeScore(params: CompositeScoreParams): number { | ||
| const recency = Math.exp((-Math.LN2 * params.ageSeconds) / params.halfLifeSeconds); | ||
| return ( | ||
| params.weights.similarity * params.similarity + | ||
| params.weights.recency * recency + | ||
| params.weights.importance * params.importance | ||
| ); | ||
| } | ||
|
|
||
| /** Map cosine distance (0..2, lower = closer) to a 0..1 similarity score. */ | ||
| export function similarityFromDistance(distance: number): number { | ||
| return 1 - distance / 2; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.