|
| 1 | +using AiDotNet.Interfaces; |
| 2 | +using AiDotNet.LinearAlgebra; |
| 3 | +using AiDotNet.RetrievalAugmentedGeneration.VectorSearch; |
| 4 | +using AiDotNet.RetrievalAugmentedGeneration.VectorSearch.Metrics; |
| 5 | + |
| 6 | +namespace AiDotNet.Agentic.Memory; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// A semantic <see cref="IAgentMemoryStore"/> that ranks memories by meaning, not words. It embeds each |
| 10 | +/// memory with an <see cref="IEmbeddingModel{T}"/> and scores a query by cosine similarity against those |
| 11 | +/// embeddings — reusing AiDotNet's RAG embedding and similarity-metric stack, so a memory about "due date" |
| 12 | +/// is recalled for a query about "deadline". |
| 13 | +/// </summary> |
| 14 | +/// <typeparam name="T">The numeric type of the embedding model and similarity metric.</typeparam> |
| 15 | +/// <remarks> |
| 16 | +/// <para> |
| 17 | +/// Memories and their embedding vectors are held in memory; the vector for each memory is computed once on |
| 18 | +/// <see cref="AddAsync"/>. This keeps the abstraction identical to the lexical |
| 19 | +/// <see cref="InMemoryAgentMemoryStore"/> while delivering true semantic recall — pick whichever fits the |
| 20 | +/// deployment without touching agent code. |
| 21 | +/// </para> |
| 22 | +/// <para><b>For Beginners:</b> Same notebook idea, but instead of matching words it matches <em>meaning</em>. |
| 23 | +/// It turns every note (and your question) into a list of numbers that capture meaning, then finds the notes |
| 24 | +/// whose numbers are closest to your question's — so synonyms and paraphrases still match. |
| 25 | +/// </para> |
| 26 | +/// </remarks> |
| 27 | +public sealed class EmbeddingAgentMemoryStore<T> : IAgentMemoryStore |
| 28 | +{ |
| 29 | + private readonly object _gate = new(); |
| 30 | + private readonly List<Entry> _entries = new(); |
| 31 | + private readonly IEmbeddingModel<T> _embeddingModel; |
| 32 | + private readonly ISimilarityMetric<T> _similarity; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Initializes a new semantic memory store. |
| 36 | + /// </summary> |
| 37 | + /// <param name="embeddingModel">The model used to embed memories and queries.</param> |
| 38 | + /// <param name="similarity">The similarity metric. <c>null</c> uses cosine similarity.</param> |
| 39 | + /// <exception cref="ArgumentNullException">Thrown when <paramref name="embeddingModel"/> is <c>null</c>.</exception> |
| 40 | + public EmbeddingAgentMemoryStore(IEmbeddingModel<T> embeddingModel, ISimilarityMetric<T>? similarity = null) |
| 41 | + { |
| 42 | + Guard.NotNull(embeddingModel); |
| 43 | + _embeddingModel = embeddingModel; |
| 44 | + _similarity = similarity ?? new CosineSimilarityMetric<T>(); |
| 45 | + } |
| 46 | + |
| 47 | + /// <inheritdoc/> |
| 48 | + public async Task<string> AddAsync( |
| 49 | + string content, |
| 50 | + IReadOnlyDictionary<string, string>? metadata = null, |
| 51 | + CancellationToken cancellationToken = default) |
| 52 | + { |
| 53 | + Guard.NotNullOrWhiteSpace(content); |
| 54 | + var id = Guid.NewGuid().ToString("N"); |
| 55 | + var memory = new AgentMemory(id, content, metadata); |
| 56 | + var vector = await _embeddingModel.EmbedAsync(content).ConfigureAwait(false); |
| 57 | + |
| 58 | + lock (_gate) |
| 59 | + { |
| 60 | + _entries.Add(new Entry(memory, vector)); |
| 61 | + } |
| 62 | + |
| 63 | + return id; |
| 64 | + } |
| 65 | + |
| 66 | + /// <inheritdoc/> |
| 67 | + public async Task<IReadOnlyList<ScoredMemory>> SearchAsync( |
| 68 | + string query, |
| 69 | + int topK = 5, |
| 70 | + CancellationToken cancellationToken = default) |
| 71 | + { |
| 72 | + Guard.NotNullOrWhiteSpace(query); |
| 73 | + Guard.Positive(topK); |
| 74 | + |
| 75 | + List<Entry> snapshot; |
| 76 | + lock (_gate) |
| 77 | + { |
| 78 | + snapshot = new List<Entry>(_entries); |
| 79 | + } |
| 80 | + |
| 81 | + if (snapshot.Count == 0) |
| 82 | + { |
| 83 | + return new List<ScoredMemory>(); |
| 84 | + } |
| 85 | + |
| 86 | + var queryVector = await _embeddingModel.EmbedAsync(query).ConfigureAwait(false); |
| 87 | + |
| 88 | + var scored = new List<ScoredMemory>(snapshot.Count); |
| 89 | + foreach (var entry in snapshot) |
| 90 | + { |
| 91 | + var score = Convert.ToDouble(_similarity.Calculate(queryVector, entry.Vector)); |
| 92 | + scored.Add(new ScoredMemory(entry.Memory, score)); |
| 93 | + } |
| 94 | + |
| 95 | + var ordered = _similarity.HigherIsBetter |
| 96 | + ? scored.OrderByDescending(s => s.Score) |
| 97 | + : scored.OrderBy(s => s.Score); |
| 98 | + |
| 99 | + return ordered.Take(topK).ToList(); |
| 100 | + } |
| 101 | + |
| 102 | + /// <inheritdoc/> |
| 103 | + public Task<IReadOnlyList<AgentMemory>> GetAllAsync(CancellationToken cancellationToken = default) |
| 104 | + { |
| 105 | + lock (_gate) |
| 106 | + { |
| 107 | + IReadOnlyList<AgentMemory> all = _entries.Select(e => e.Memory).ToList(); |
| 108 | + return Task.FromResult(all); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /// <inheritdoc/> |
| 113 | + public Task RemoveAsync(string id, CancellationToken cancellationToken = default) |
| 114 | + { |
| 115 | + Guard.NotNullOrWhiteSpace(id); |
| 116 | + |
| 117 | + lock (_gate) |
| 118 | + { |
| 119 | + _entries.RemoveAll(e => string.Equals(e.Memory.Id, id, StringComparison.Ordinal)); |
| 120 | + } |
| 121 | + |
| 122 | + return Task.CompletedTask; |
| 123 | + } |
| 124 | + |
| 125 | + private readonly struct Entry |
| 126 | + { |
| 127 | + public Entry(AgentMemory memory, Vector<T> vector) |
| 128 | + { |
| 129 | + Memory = memory; |
| 130 | + Vector = vector; |
| 131 | + } |
| 132 | + |
| 133 | + public AgentMemory Memory { get; } |
| 134 | + |
| 135 | + public Vector<T> Vector { get; } |
| 136 | + } |
| 137 | +} |
0 commit comments