|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +#pragma warning disable CA1054 // URI-like parameters should not be strings |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Linq; |
| 7 | +using System.Net.Http; |
| 8 | +using System.Text; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.Extensions.AI; |
| 12 | +using Microsoft.SemanticKernel.Memory; |
| 13 | +using Moq; |
| 14 | +using Xunit; |
| 15 | + |
| 16 | +namespace SemanticKernel.UnitTests.Memory; |
| 17 | + |
| 18 | +/// <summary> |
| 19 | +/// Contains tests for the <see cref="Mem0MemoryComponent"/> class. |
| 20 | +/// </summary> |
| 21 | +public class Mem0MemoryComponentTests : IDisposable |
| 22 | +{ |
| 23 | + private readonly HttpClient _httpClient; |
| 24 | + private readonly Mock<MockableMessageHandler> _mockMessageHandler; |
| 25 | + private bool _disposedValue; |
| 26 | + |
| 27 | + public Mem0MemoryComponentTests() |
| 28 | + { |
| 29 | + this._mockMessageHandler = new Mock<MockableMessageHandler>() { CallBase = true }; |
| 30 | + this._httpClient = new HttpClient(this._mockMessageHandler.Object) |
| 31 | + { |
| 32 | + BaseAddress = new Uri("https://localhost/fakepath") |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + [Fact] |
| 37 | + public void ValidatesHttpClientBaseAddress() |
| 38 | + { |
| 39 | + // Arrange |
| 40 | + using var httpClientWithoutBaseAddress = new HttpClient(); |
| 41 | + |
| 42 | + // Act & Assert |
| 43 | + var exception = Assert.Throws<ArgumentException>(() => |
| 44 | + { |
| 45 | + new Mem0MemoryComponent(httpClientWithoutBaseAddress); |
| 46 | + }); |
| 47 | + |
| 48 | + Assert.Equal("The BaseAddress of the provided httpClient parameter must be set. (Parameter 'httpClient')", exception.Message); |
| 49 | + } |
| 50 | + |
| 51 | + [Fact] |
| 52 | + public void AIFunctionsAreSetCorrectly() |
| 53 | + { |
| 54 | + // Arrange |
| 55 | + var sut = new Mem0MemoryComponent(this._httpClient, new() { ApplicationId = "test-app-id" }); |
| 56 | + |
| 57 | + // Act |
| 58 | + var aiFunctions = sut.AIFunctions; |
| 59 | + |
| 60 | + // Assert |
| 61 | + Assert.NotNull(aiFunctions); |
| 62 | + Assert.Single(aiFunctions); |
| 63 | + Assert.Equal("ClearStoredUserFacts", aiFunctions.First().Name); |
| 64 | + } |
| 65 | + |
| 66 | + [Theory] |
| 67 | + [InlineData(false, "test-thread-id")] |
| 68 | + [InlineData(true, "test-thread-id-1")] |
| 69 | + public async Task PostsMemoriesOnNewMessage(bool scopePerOperationThread, string expectedThreadId) |
| 70 | + { |
| 71 | + // Arrange |
| 72 | + using var httpResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK }; |
| 73 | + this._mockMessageHandler |
| 74 | + .Setup(x => x.MockableSendAsync(It.IsAny<HttpMethod>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) |
| 75 | + .ReturnsAsync(httpResponse); |
| 76 | + |
| 77 | + var sut = new Mem0MemoryComponent(this._httpClient, new() { ApplicationId = "test-app-id", AgentId = "test-agent-id", ThreadId = "test-thread-id", UserId = "test-user-id", ScopeToPerOperationThreadId = scopePerOperationThread }); |
| 78 | + |
| 79 | + // Act |
| 80 | + await sut.OnNewMessageAsync("test-thread-id-1", new ChatMessage(ChatRole.User, "Hello, my name is Caoimhe.")); |
| 81 | + |
| 82 | + // Assert |
| 83 | + var expectedPayload = $$""" |
| 84 | + {"app_id":"test-app-id","agent_id":"test-agent-id","run_id":"{{expectedThreadId}}","user_id":"test-user-id","messages":[{"content":"Hello, my name is Caoimhe.","role":"user"}]} |
| 85 | + """; |
| 86 | + this._mockMessageHandler.Verify(x => x.MockableSendAsync(HttpMethod.Post, "https://localhost/v1/memories/", expectedPayload, It.IsAny<CancellationToken>()), Times.Once); |
| 87 | + } |
| 88 | + |
| 89 | + [Theory] |
| 90 | + [InlineData(false, "test-thread-id", null, "Consider the following memories when answering user questions:{0}Name is Caoimhe")] |
| 91 | + [InlineData(true, "test-thread-id-1", "Custom Prompt:", "Custom Prompt:{0}Name is Caoimhe")] |
| 92 | + public async Task SearchesForMemoriesOnModelInvoke(bool scopePerOperationThread, string expectedThreadId, string? customContextPrompt, string expectedAdditionalInstructions) |
| 93 | + { |
| 94 | + // Arrange |
| 95 | + var expectedResponseString = """ |
| 96 | + [{"id":"1","memory":"Name is Caoimhe","hash":"abc123","metadata":null,"score":0.9,"created_at":"2023-01-01T00:00:00Z","updated_at":null,"user_id":"test-user-id","app_id":null,"agent_id":"test-agent-id","session_id":"test-thread-id-1"}] |
| 97 | + """; |
| 98 | + using var httpResponse = new HttpResponseMessage() |
| 99 | + { |
| 100 | + StatusCode = System.Net.HttpStatusCode.OK, |
| 101 | + Content = new StringContent(expectedResponseString, Encoding.UTF8, "application/json") |
| 102 | + }; |
| 103 | + |
| 104 | + this._mockMessageHandler |
| 105 | + .Setup(x => x.MockableSendAsync(It.IsAny<HttpMethod>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) |
| 106 | + .ReturnsAsync(httpResponse); |
| 107 | + |
| 108 | + var sut = new Mem0MemoryComponent(this._httpClient, new() |
| 109 | + { |
| 110 | + ApplicationId = "test-app-id", |
| 111 | + AgentId = "test-agent-id", |
| 112 | + ThreadId = "test-thread-id", |
| 113 | + UserId = "test-user-id", |
| 114 | + ScopeToPerOperationThreadId = scopePerOperationThread, |
| 115 | + ContextPrompt = customContextPrompt |
| 116 | + }); |
| 117 | + await sut.OnThreadCreatedAsync("test-thread-id-1"); |
| 118 | + |
| 119 | + // Act |
| 120 | + var actual = await sut.OnModelInvokeAsync(new[] { new ChatMessage(ChatRole.User, "What is my name?") }); |
| 121 | + |
| 122 | + // Assert |
| 123 | + var expectedPayload = $$""" |
| 124 | + {"app_id":"test-app-id","agent_id":"test-agent-id","run_id":"{{expectedThreadId}}","user_id":"test-user-id","query":"What is my name?"} |
| 125 | + """; |
| 126 | + this._mockMessageHandler.Verify(x => x.MockableSendAsync(HttpMethod.Post, "https://localhost/v1/memories/search/", expectedPayload, It.IsAny<CancellationToken>()), Times.Once); |
| 127 | + |
| 128 | + Assert.Equal(string.Format(expectedAdditionalInstructions, Environment.NewLine), actual); |
| 129 | + } |
| 130 | + |
| 131 | + [Theory] |
| 132 | + [InlineData(false, "test-thread-id")] |
| 133 | + [InlineData(true, "test-thread-id-1")] |
| 134 | + public async Task ClearsStoredUserFacts(bool scopePerOperationThread, string expectedThreadId) |
| 135 | + { |
| 136 | + // Arrange |
| 137 | + using var httpResponse = new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK }; |
| 138 | + this._mockMessageHandler |
| 139 | + .Setup(x => x.MockableSendAsync(It.IsAny<HttpMethod>(), It.IsAny<string>(), null, It.IsAny<CancellationToken>())) |
| 140 | + .ReturnsAsync(httpResponse); |
| 141 | + |
| 142 | + var sut = new Mem0MemoryComponent(this._httpClient, new() { ApplicationId = "test-app-id", AgentId = "test-agent-id", ThreadId = "test-thread-id", UserId = "test-user-id", ScopeToPerOperationThreadId = scopePerOperationThread }); |
| 143 | + await sut.OnThreadCreatedAsync("test-thread-id-1"); |
| 144 | + |
| 145 | + // Act |
| 146 | + await sut.ClearStoredUserFactsAsync(); |
| 147 | + |
| 148 | + // Assert |
| 149 | + var expectedUrl = $"https://localhost/v1/memories/?app_id=test-app-id&agent_id=test-agent-id&run_id={expectedThreadId}&user_id=test-user-id"; |
| 150 | + this._mockMessageHandler.Verify(x => x.MockableSendAsync(HttpMethod.Delete, expectedUrl, null, It.IsAny<CancellationToken>()), Times.Once); |
| 151 | + } |
| 152 | + |
| 153 | + [Fact] |
| 154 | + public async Task ThrowsExceptionWhenThreadIdChangesAfterBeingSet() |
| 155 | + { |
| 156 | + // Arrange |
| 157 | + var sut = new Mem0MemoryComponent(this._httpClient, new() { ScopeToPerOperationThreadId = true }); |
| 158 | + |
| 159 | + // Act |
| 160 | + await sut.OnThreadCreatedAsync("initial-thread-id"); |
| 161 | + |
| 162 | + // Assert |
| 163 | + var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => |
| 164 | + { |
| 165 | + await sut.OnThreadCreatedAsync("new-thread-id"); |
| 166 | + }); |
| 167 | + |
| 168 | + Assert.Equal("The Mem0MemoryComponent can only be used with one thread at a time when ScopeToPerOperationThreadId is set to true.", exception.Message); |
| 169 | + } |
| 170 | + |
| 171 | + protected virtual void Dispose(bool disposing) |
| 172 | + { |
| 173 | + if (!this._disposedValue) |
| 174 | + { |
| 175 | + if (disposing) |
| 176 | + { |
| 177 | + this._httpClient.Dispose(); |
| 178 | + } |
| 179 | + |
| 180 | + this._disposedValue = true; |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + public void Dispose() |
| 185 | + { |
| 186 | + this.Dispose(disposing: true); |
| 187 | + GC.SuppressFinalize(this); |
| 188 | + } |
| 189 | + |
| 190 | + public class MockableMessageHandler : DelegatingHandler |
| 191 | + { |
| 192 | + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 193 | + { |
| 194 | + string? contentString = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken); |
| 195 | + return await this.MockableSendAsync(request.Method, request.RequestUri?.AbsoluteUri, contentString, cancellationToken); |
| 196 | + } |
| 197 | + |
| 198 | + public virtual Task<HttpResponseMessage> MockableSendAsync(HttpMethod method, string? absoluteUri, string? content, CancellationToken cancellationToken) |
| 199 | + { |
| 200 | + throw new NotImplementedException(); |
| 201 | + } |
| 202 | + } |
| 203 | +} |
0 commit comments