|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.Linq; |
| 7 | +using System.Net.Http; |
| 8 | +using System.Text; |
| 9 | +using System.Text.Json; |
| 10 | +using System.Text.Json.Serialization; |
| 11 | +using System.Threading.Tasks; |
| 12 | + |
| 13 | +namespace Microsoft.SemanticKernel.Memory; |
| 14 | + |
| 15 | +/// <summary> |
| 16 | +/// Client for the Mem0 memory service. |
| 17 | +/// </summary> |
| 18 | +[ExcludeFromCodeCoverage] // Tested via integration tests. |
| 19 | +internal sealed class Mem0Client |
| 20 | +{ |
| 21 | + private static readonly Uri s_searchUri = new("/v1/memories/search/", UriKind.Relative); |
| 22 | + private static readonly Uri s_createMemoryUri = new("/v1/memories/", UriKind.Relative); |
| 23 | + |
| 24 | + private readonly HttpClient _httpClient; |
| 25 | + |
| 26 | + public Mem0Client(HttpClient httpClient) |
| 27 | + { |
| 28 | + Verify.NotNull(httpClient); |
| 29 | + |
| 30 | + this._httpClient = httpClient; |
| 31 | + } |
| 32 | + |
| 33 | + public async Task<IEnumerable<string>> SearchAsync(string? applicationId, string? agentId, string? threadId, string? userId, string? inputText) |
| 34 | + { |
| 35 | + if (string.IsNullOrWhiteSpace(applicationId) |
| 36 | + && string.IsNullOrWhiteSpace(agentId) |
| 37 | + && string.IsNullOrWhiteSpace(threadId) |
| 38 | + && string.IsNullOrWhiteSpace(userId)) |
| 39 | + { |
| 40 | + throw new InvalidOperationException("At least one of applicationId, agentId, threadId, or userId must be provided."); |
| 41 | + } |
| 42 | + |
| 43 | + var searchRequest = new SearchRequest |
| 44 | + { |
| 45 | + AppId = applicationId, |
| 46 | + AgentId = agentId, |
| 47 | + RunId = threadId, |
| 48 | + UserId = userId, |
| 49 | + Query = inputText ?? string.Empty |
| 50 | + }; |
| 51 | + |
| 52 | + // Search. |
| 53 | + using var content = new StringContent(JsonSerializer.Serialize(searchRequest, Mem0SourceGenerationContext.Default.SearchRequest), Encoding.UTF8, "application/json"); |
| 54 | + var responseMessage = await this._httpClient.PostAsync(s_searchUri, content).ConfigureAwait(false); |
| 55 | + responseMessage.EnsureSuccessStatusCode(); |
| 56 | + |
| 57 | + // Process response. |
| 58 | + var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); |
| 59 | + var searchResponseItems = JsonSerializer.Deserialize<SearchResponseItem[]>(response, Mem0SourceGenerationContext.Default.SearchResponseItemArray); |
| 60 | + return searchResponseItems?.Select(item => item.Memory) ?? []; |
| 61 | + } |
| 62 | + |
| 63 | + public async Task CreateMemoryAsync(string? applicationId, string? agentId, string? threadId, string? userId, string messageContent, string messageRole) |
| 64 | + { |
| 65 | + if (string.IsNullOrWhiteSpace(applicationId) |
| 66 | + && string.IsNullOrWhiteSpace(agentId) |
| 67 | + && string.IsNullOrWhiteSpace(threadId) |
| 68 | + && string.IsNullOrWhiteSpace(userId)) |
| 69 | + { |
| 70 | + throw new InvalidOperationException("At least one of applicationId, agentId, threadId, or userId must be provided."); |
| 71 | + } |
| 72 | + |
| 73 | + var createMemoryRequest = new CreateMemoryRequest() |
| 74 | + { |
| 75 | + AppId = applicationId, |
| 76 | + AgentId = agentId, |
| 77 | + RunId = threadId, |
| 78 | + UserId = userId, |
| 79 | + Messages = new[] |
| 80 | + { |
| 81 | + new CreateMemoryMessage |
| 82 | + { |
| 83 | + Content = messageContent, |
| 84 | + Role = messageRole |
| 85 | + } |
| 86 | + } |
| 87 | + }; |
| 88 | + |
| 89 | + using var content = new StringContent(JsonSerializer.Serialize(createMemoryRequest, Mem0SourceGenerationContext.Default.CreateMemoryRequest), Encoding.UTF8, "application/json"); |
| 90 | + var responseMessage = await this._httpClient.PostAsync(s_createMemoryUri, content).ConfigureAwait(false); |
| 91 | + responseMessage.EnsureSuccessStatusCode(); |
| 92 | + } |
| 93 | + |
| 94 | + public async Task ClearMemoryAsync(string? applicationId, string? agentId, string? threadId, string? userId) |
| 95 | + { |
| 96 | + string[] paramNames = ["app_id", "agent_id", "run_id", "user_id"]; |
| 97 | + |
| 98 | + // Build query string. |
| 99 | + var querystringParams = new string?[4] { applicationId, agentId, threadId, userId } |
| 100 | + .Select((param, index) => string.IsNullOrWhiteSpace(param) ? null : $"{paramNames[index]}={param}") |
| 101 | + .Where(x => x != null); |
| 102 | + var queryString = string.Join("&", querystringParams); |
| 103 | + var clearMemoryUrl = new Uri($"/v1/memories/?{queryString}", UriKind.Relative); |
| 104 | + |
| 105 | + // Delete. |
| 106 | + var responseMessage = await this._httpClient.DeleteAsync(clearMemoryUrl).ConfigureAwait(false); |
| 107 | + responseMessage.EnsureSuccessStatusCode(); |
| 108 | + } |
| 109 | + |
| 110 | + internal sealed class CreateMemoryRequest |
| 111 | + { |
| 112 | + [JsonPropertyName("app_id")] |
| 113 | + public string? AppId { get; set; } |
| 114 | + [JsonPropertyName("agent_id")] |
| 115 | + public string? AgentId { get; set; } |
| 116 | + [JsonPropertyName("run_id")] |
| 117 | + public string? RunId { get; set; } |
| 118 | + [JsonPropertyName("user_id")] |
| 119 | + public string? UserId { get; set; } |
| 120 | + [JsonPropertyName("messages")] |
| 121 | + public CreateMemoryMessage[] Messages { get; set; } = []; |
| 122 | + } |
| 123 | + |
| 124 | + internal sealed class CreateMemoryMessage |
| 125 | + { |
| 126 | + [JsonPropertyName("content")] |
| 127 | + public string Content { get; set; } = string.Empty; |
| 128 | + [JsonPropertyName("role")] |
| 129 | + public string Role { get; set; } = string.Empty; |
| 130 | + } |
| 131 | + |
| 132 | + internal sealed class SearchRequest |
| 133 | + { |
| 134 | + [JsonPropertyName("app_id")] |
| 135 | + public string? AppId { get; set; } |
| 136 | + [JsonPropertyName("agent_id")] |
| 137 | + public string? AgentId { get; set; } = null; |
| 138 | + [JsonPropertyName("run_id")] |
| 139 | + public string? RunId { get; set; } = null; |
| 140 | + [JsonPropertyName("user_id")] |
| 141 | + public string? UserId { get; set; } = null; |
| 142 | + [JsonPropertyName("query")] |
| 143 | + public string Query { get; set; } = string.Empty; |
| 144 | + } |
| 145 | + |
| 146 | + internal sealed class SearchResponseItem |
| 147 | + { |
| 148 | + [JsonPropertyName("id")] |
| 149 | + public string Id { get; set; } = string.Empty; |
| 150 | + [JsonPropertyName("memory")] |
| 151 | + public string Memory { get; set; } = string.Empty; |
| 152 | + [JsonPropertyName("hash")] |
| 153 | + public string Hash { get; set; } = string.Empty; |
| 154 | + [JsonPropertyName("metadata")] |
| 155 | + public object? Metadata { get; set; } |
| 156 | + [JsonPropertyName("score")] |
| 157 | + public double Score { get; set; } |
| 158 | + [JsonPropertyName("created_at")] |
| 159 | + public DateTime CreatedAt { get; set; } |
| 160 | + [JsonPropertyName("updated_at")] |
| 161 | + public DateTime? UpdatedAt { get; set; } |
| 162 | + [JsonPropertyName("user_id")] |
| 163 | + public string UserId { get; set; } = string.Empty; |
| 164 | + [JsonPropertyName("app_id")] |
| 165 | + public string? AppId { get; set; } |
| 166 | + [JsonPropertyName("agent_id")] |
| 167 | + public string AgentId { get; set; } = string.Empty; |
| 168 | + [JsonPropertyName("session_id")] |
| 169 | + public string RunId { get; set; } = string.Empty; |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +[JsonSourceGenerationOptions(JsonSerializerDefaults.General, |
| 174 | + UseStringEnumConverter = false, |
| 175 | + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| 176 | + WriteIndented = false)] |
| 177 | +[JsonSerializable(typeof(Mem0Client.CreateMemoryRequest))] |
| 178 | +[JsonSerializable(typeof(Mem0Client.SearchRequest))] |
| 179 | +[JsonSerializable(typeof(Mem0Client.SearchResponseItem[]))] |
| 180 | +internal partial class Mem0SourceGenerationContext : JsonSerializerContext |
| 181 | +{ |
| 182 | +} |
0 commit comments