forked from microsoft/kernel-memory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
298 lines (250 loc) · 11.4 KB
/
Program.cs
File metadata and controls
298 lines (250 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright (c) Microsoft. All rights reserved.
using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Models;
using Microsoft.KernelMemory;
using Microsoft.KernelMemory.MemoryDb.AzureAISearch;
using Microsoft.KernelMemory.MemoryStorage;
namespace Microsoft.AzureAISearch.TestApplication;
public static class Program
{
// Azure Search Index name
private const string Index = "test01";
// A Memory ID example. This value is later serialized.
private const string ExternalRecordId1 = "usr=user2//ppl=f05//prt=7b9bad8968804121bb9b1264104608ac";
private const string ExternalRecordId2 = "usr=user2//ppl=f06//prt=7b9bad8968804121bb9b1264104608ac";
// Size of the vectors
private const int EmbeddingSize = 3;
private const string VectorSearchProfileName = "KMDefaultProfile";
private const string VectorSearchConfigName = "KMDefaultAlgorithm";
private static SearchIndexClient s_adminClient = null!;
public static async Task Main()
{
var cfg = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Development.json", optional: true)
.Build();
var config = cfg.GetSection("KernelMemory:Services:AzureAISearch").Get<AzureAISearchConfig>();
ArgumentNullExceptionEx.ThrowIfNull(config, nameof(config), "AzureAISearch config not found");
// Azure AI Search service client
s_adminClient = new SearchIndexClient(
new Uri(config.Endpoint),
new AzureKeyCredential(config.APIKey),
new SearchClientOptions
{
Diagnostics =
{
IsTelemetryEnabled = true,
ApplicationId = "Kernel-Memory"
}
});
// Create an index (if doesn't exist)
await CreateIndexAsync(Index);
// Insert two records
var recordId1 = await InsertRecordAsync(Index,
externalId: ExternalRecordId1,
payload: new Dictionary<string, object> { { "filename", "dotnet.pdf" }, { "text", "this is a sentence" }, },
tags: new TagCollection
{
{ "category", "demo" },
{ "category", "dotnet" },
{ "category", "search" },
{ "year", "2024" },
},
embedding: new[] { 0f, 0.5f, 1 });
var recordId2 = await InsertRecordAsync(Index,
externalId: ExternalRecordId2,
payload: new Dictionary<string, object> { { "filename", "python.pdf" }, { "text", "this is a sentence" }, },
tags: new TagCollection
{
{ "category", "demo" },
{ "category", "pyt'hon" },
{ "category", "search" },
{ "year", "2023" },
},
embedding: new[] { 0f, 0.5f, 1 });
await Task.Delay(TimeSpan.FromSeconds(2));
// Search by tags
var records = await SearchByFieldValueAsync(Index,
fieldName: "tags",
fieldValue1: $"category{Constants.ReservedEqualsChar}pyt'hon",
fieldValue2: $"year{Constants.ReservedEqualsChar}2023",
fieldIsCollection: true,
limit: 5);
Console.WriteLine("Count: " + records.Count + $" ({(records.Count == 1 ? "OK" : "ERROR, should be 1")})");
foreach (MemoryRecord rec in records)
{
Console.WriteLine(" - " + rec.Id);
Console.WriteLine(" " + rec.Payload.FirstOrDefault().Value);
}
// Search by tags
records = await SearchByFieldValueAsync(Index,
fieldName: "tags",
fieldValue1: $"category{Constants.ReservedEqualsChar}pyt'hon",
fieldValue2: $"year{Constants.ReservedEqualsChar}1999",
fieldIsCollection: true,
limit: 5);
Console.WriteLine("Count: " + records.Count + $" ({(records.Count == 0 ? "OK" : "ERROR, should be 0")})");
foreach (MemoryRecord rec in records)
{
Console.WriteLine(" - " + rec.Id);
Console.WriteLine(" " + rec.Payload.FirstOrDefault().Value);
}
// Delete the record
await DeleteRecordAsync(Index, recordId1);
await DeleteRecordAsync(Index, recordId2);
}
// ===============================================================================================
private static async Task CreateIndexAsync(string name)
{
Console.WriteLine("\n== CREATE INDEX ==\n");
var indexSchema = new SearchIndex(name)
{
Fields = new List<SearchField>(),
VectorSearch = new VectorSearch
{
Profiles =
{
new VectorSearchProfile(VectorSearchProfileName, VectorSearchConfigName)
},
Algorithms =
{
new HnswAlgorithmConfiguration(VectorSearchConfigName)
{
Parameters = new HnswParameters
{
Metric = VectorSearchAlgorithmMetric.Cosine
}
}
}
}
};
indexSchema.Fields.Add(new SearchField("id", SearchFieldDataType.String)
{
IsKey = true,
IsFilterable = true,
IsFacetable = false,
IsSortable = false,
IsSearchable = true,
});
indexSchema.Fields.Add(new SimpleField("tags", SearchFieldDataType.Collection(SearchFieldDataType.String))
{
IsKey = false,
IsFilterable = true,
IsFacetable = false,
IsSortable = false,
});
indexSchema.Fields.Add(new SearchField("payload", SearchFieldDataType.String)
{
IsKey = false,
IsFilterable = true,
IsFacetable = false,
IsSortable = false,
IsSearchable = true,
});
indexSchema.Fields.Add(new SearchField("embedding", SearchFieldDataType.Collection(SearchFieldDataType.Single))
{
IsKey = false,
IsFilterable = false,
IsSearchable = true,
IsFacetable = false,
IsSortable = false,
VectorSearchDimensions = EmbeddingSize,
VectorSearchProfileName = VectorSearchProfileName,
});
try
{
Response<SearchIndex>? response = await s_adminClient.CreateIndexAsync(indexSchema);
Console.WriteLine("Status: " + response.GetRawResponse().Status);
Console.WriteLine("IsError: " + response.GetRawResponse().IsError);
Console.WriteLine("Content: " + response.GetRawResponse().Content);
Console.WriteLine("Name: " + response.Value.Name);
}
catch (RequestFailedException e) when (e.Message.Contains("already exists"))
{
Console.WriteLine("Index already exists");
}
}
// ===============================================================================================
private static async Task<string> InsertRecordAsync(string index,
string externalId, Dictionary<string, object> payload, TagCollection tags, Embedding embedding)
{
Console.WriteLine("\n== INSERT ==\n");
var client = s_adminClient.GetSearchClient(index);
var record = new MemoryRecord
{
Id = externalId,
Vector = embedding,
// Owner = "userAB",
Tags = tags,
Payload = payload
};
AzureAISearchMemoryRecord localRecord = AzureAISearchMemoryRecord.FromMemoryRecord(record);
Console.WriteLine($"CREATING {localRecord.Id}\n");
var response = await client.IndexDocumentsAsync(
IndexDocumentsBatch.Upload(new[] { localRecord }),
new IndexDocumentsOptions { ThrowOnAnyError = true });
Console.WriteLine("Status: " + response.GetRawResponse().Status);
Console.WriteLine("IsError: " + response.GetRawResponse().IsError);
Console.WriteLine("Content: " + response.GetRawResponse().Content);
Console.WriteLine("[Results] Status: " + response.Value.Results.FirstOrDefault()?.Status);
Console.WriteLine("[Results] Key: " + response.Value.Results.FirstOrDefault()?.Key);
Console.WriteLine("[Results] Succeeded: " + (response.Value.Results.FirstOrDefault()?.Succeeded ?? false ? "true" : "false"));
Console.WriteLine("[Results] ErrorMessage: " + response.Value.Results.FirstOrDefault()?.ErrorMessage);
return response.Value.Results.FirstOrDefault()?.Key ?? string.Empty;
}
// ===============================================================================================
private static async Task<IList<MemoryRecord>> SearchByFieldValueAsync(
string index,
string fieldName,
bool fieldIsCollection,
string fieldValue1,
string fieldValue2,
int limit)
{
Console.WriteLine("\n== FILTER SEARCH ==\n");
var client = s_adminClient.GetSearchClient(index);
fieldValue1 = fieldValue1.Replace("'", "''", StringComparison.Ordinal);
fieldValue2 = fieldValue2.Replace("'", "''", StringComparison.Ordinal);
SearchOptions options = new()
{
Filter = fieldIsCollection
? $"{fieldName}/any(s: s eq '{fieldValue1}') and {fieldName}/any(s: s eq '{fieldValue2}')"
: $"{fieldName} eq '{fieldValue1}' or {fieldName} eq '{fieldValue2}')",
Size = limit
};
Response<SearchResults<AzureAISearchMemoryRecord>>? searchResult = null;
try
{
searchResult = await client.SearchAsync<AzureAISearchMemoryRecord>(null, options);
}
catch (RequestFailedException e) when (e.Status == 404)
{
Console.WriteLine("Search returned 404: {0}", e.Message);
}
var results = new List<MemoryRecord>();
if (searchResult == null) { return results; }
await foreach (SearchResult<AzureAISearchMemoryRecord>? doc in searchResult.Value.GetResultsAsync())
{
results.Add(doc.Document.ToMemoryRecord());
}
return results;
}
// ===============================================================================================
private static async Task DeleteRecordAsync(string index, string recordId)
{
Console.WriteLine("\n== DELETE ==\n");
var client = s_adminClient.GetSearchClient(index);
Console.WriteLine($"DELETING {recordId}\n");
Response<IndexDocumentsResult>? response = await client.DeleteDocumentsAsync("id", new List<string> { recordId });
Console.WriteLine("Status: " + response.GetRawResponse().Status);
Console.WriteLine("IsError: " + response.GetRawResponse().IsError);
Console.WriteLine("Content: " + response.GetRawResponse().Content);
Console.WriteLine("[Results] Status: " + response.Value.Results.FirstOrDefault()?.Status);
Console.WriteLine("[Results] Key: " + response.Value.Results.FirstOrDefault()?.Key);
Console.WriteLine("[Results] Succeeded: " + (response.Value.Results.FirstOrDefault()?.Succeeded ?? false ? "true" : "false"));
Console.WriteLine("[Results] ErrorMessage: " + response.Value.Results.FirstOrDefault()?.ErrorMessage);
}
}