forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVectorStoreTextSearchTestBase.cs
More file actions
259 lines (231 loc) · 11.1 KB
/
VectorStoreTextSearchTestBase.cs
File metadata and controls
259 lines (231 loc) · 11.1 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
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.InMemory;
using Microsoft.SemanticKernel.Data;
using Microsoft.SemanticKernel.Embeddings;
namespace SemanticKernel.UnitTests.Data;
#pragma warning disable CA1052 // Static holder types should be Static or NotInheritable
#pragma warning disable RCS1102 // Make class static
public class VectorStoreTextSearchTestBase
#pragma warning restore RCS1102 // Make class static
#pragma warning restore CA1052 // Static holder types should be Static or NotInheritable
{
/// <summary>
/// Create a <see cref="VectorStoreTextSearch{TRecord}"/> from a <see cref="IVectorSearchable{TRecord}"/>.
/// </summary>
[Obsolete("VectorStoreTextSearch with ITextEmbeddingGenerationService is obsolete")]
public static async Task<VectorStoreTextSearch<DataModelWithRawEmbedding>> CreateVectorStoreTextSearchWithEmbeddingGenerationServiceAsync()
{
using var vectorStore = new InMemoryVectorStore();
var vectorSearchable = vectorStore.GetCollection<Guid, DataModelWithRawEmbedding>("records");
var stringMapper = new DataModelTextSearchStringMapper();
var resultMapper = new DataModelTextSearchResultMapper();
using var embeddingService = new MockTextEmbeddingGenerator();
await AddRecordsAsync(vectorSearchable, (ITextEmbeddingGenerationService)embeddingService);
var sut = new VectorStoreTextSearch<DataModelWithRawEmbedding>(vectorSearchable, (ITextEmbeddingGenerationService)embeddingService, stringMapper, resultMapper);
return sut;
}
/// <summary>
/// Create a <see cref="VectorStoreTextSearch{TRecord}"/> from a <see cref="IVectorSearchable{TRecord}"/>.
/// </summary>
public static async Task<VectorStoreTextSearch<DataModelWithRawEmbedding>> CreateVectorStoreTextSearchWithEmbeddingGeneratorAsync()
{
using var vectorStore = new InMemoryVectorStore();
var vectorSearchable = vectorStore.GetCollection<Guid, DataModelWithRawEmbedding>("records");
var stringMapper = new DataModelTextSearchStringMapper();
var resultMapper = new DataModelTextSearchResultMapper();
using var embeddingService = new MockTextEmbeddingGenerator();
await AddRecordsAsync(vectorSearchable, (IEmbeddingGenerator<string, Embedding<float>>)embeddingService);
var sut = new VectorStoreTextSearch<DataModelWithRawEmbedding>(vectorSearchable, (IEmbeddingGenerator<string, Embedding<float>>)embeddingService, stringMapper, resultMapper);
return sut;
}
/// <summary>
/// Create a <see cref="VectorStoreTextSearch{TRecord}"/> from a <see cref="IVectorSearchable{TRecord}"/>.
/// </summary>
public static async Task<VectorStoreTextSearch<DataModel>> CreateVectorStoreTextSearchAsync()
{
using var embeddingGenerator = new MockTextEmbeddingGenerator();
using var vectorStore = new InMemoryVectorStore(new() { EmbeddingGenerator = embeddingGenerator });
var vectorSearch = vectorStore.GetCollection<Guid, DataModel>("records");
var stringMapper = new DataModelTextSearchStringMapper();
var resultMapper = new DataModelTextSearchResultMapper();
await AddRecordsAsync(vectorSearch);
var sut = new VectorStoreTextSearch<DataModel>(vectorSearch, stringMapper, resultMapper);
return sut;
}
/// <summary>
/// Add sample records to the vector store record collection.
/// </summary>
public static async Task AddRecordsAsync(
VectorStoreCollection<Guid, DataModel> recordCollection,
int? count = 10)
{
await recordCollection.EnsureCollectionExistsAsync();
for (var i = 0; i < count; i++)
{
DataModel dataModel = new()
{
Key = Guid.NewGuid(),
Text = $"Record {i}",
Tag = i % 2 == 0 ? "Even" : "Odd",
Embedding = $"Record {i}"
};
await recordCollection.UpsertAsync(dataModel);
}
}
public static async Task AddRecordsAsync(
VectorStoreCollection<Guid, DataModelWithRawEmbedding> recordCollection,
IEmbeddingGenerator<string, Embedding<float>> embeddingService,
int? count = 10)
{
await recordCollection.EnsureCollectionExistsAsync();
for (var i = 0; i < count; i++)
{
DataModelWithRawEmbedding dataModel = new()
{
Key = Guid.NewGuid(),
Text = $"Record {i}",
Tag = i % 2 == 0 ? "Even" : "Odd",
Embedding = (await embeddingService.GenerateAsync($"Record {i}")).Vector
};
await recordCollection.UpsertAsync(dataModel);
}
}
/// <summary>
/// Add sample records to the vector store record collection.
/// </summary>
[Obsolete("Temporary test for obsolete ITextEmbeddingGenerationService.")]
public static async Task AddRecordsAsync(
VectorStoreCollection<Guid, DataModelWithRawEmbedding> recordCollection,
ITextEmbeddingGenerationService embeddingService,
int? count = 10)
{
await recordCollection.EnsureCollectionExistsAsync();
for (var i = 0; i < count; i++)
{
DataModelWithRawEmbedding dataModel = new()
{
Key = Guid.NewGuid(),
Text = $"Record {i}",
Tag = i % 2 == 0 ? "Even" : "Odd",
Embedding = await embeddingService.GenerateEmbeddingAsync($"Record {i}")
};
await recordCollection.UpsertAsync(dataModel);
}
}
/// <summary>
/// String mapper which converts a DataModel to a string.
/// </summary>
public sealed class DataModelTextSearchStringMapper : ITextSearchStringMapper
{
/// <inheritdoc />
public string MapFromResultToString(object result)
=> result switch
{
DataModel dataModel => dataModel.Text,
DataModelWithRawEmbedding dataModelWithRawEmbedding => dataModelWithRawEmbedding.Text,
DataModelWithTags dataModelWithTags => dataModelWithTags.Text,
_ => throw new ArgumentException("Invalid result type.")
};
}
/// <summary>
/// Result mapper which converts a DataModel to a TextSearchResult.
/// </summary>
public sealed class DataModelTextSearchResultMapper : ITextSearchResultMapper
{
/// <inheritdoc />
public TextSearchResult MapFromResultToTextSearchResult(object result)
=> result switch
{
DataModel dataModel => new TextSearchResult(value: dataModel.Text) { Name = dataModel.Key.ToString() },
DataModelWithRawEmbedding dataModelWithRawEmbedding => new TextSearchResult(value: dataModelWithRawEmbedding.Text) { Name = dataModelWithRawEmbedding.Key.ToString() },
DataModelWithTags dataModelWithTags => new TextSearchResult(value: dataModelWithTags.Text) { Name = dataModelWithTags.Key.ToString() },
_ => throw new ArgumentException("Invalid result type.")
};
}
/// <summary>
/// Mock implementation of <see cref="ITextEmbeddingGenerationService"/>.
/// </summary>
#pragma warning disable CS0618 // Type or member is obsolete
public sealed class MockTextEmbeddingGenerator : IEmbeddingGenerator<string, Embedding<float>>, ITextEmbeddingGenerationService
#pragma warning restore CS0618 // Type or member is obsolete
{
public Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync(IEnumerable<string> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default)
=> Task.FromResult(new GeneratedEmbeddings<Embedding<float>>([new(new float[] { 0, 1, 2, 3 })]));
public void Dispose() { }
public object? GetService(Type serviceType, object? serviceKey = null) => null;
/// <inheritdoc />
public IReadOnlyDictionary<string, object?> Attributes { get; } = ReadOnlyDictionary<string, object?>.Empty;
/// <inheritdoc />
public Task<IList<ReadOnlyMemory<float>>> GenerateEmbeddingsAsync(IList<string> data, Kernel? kernel = null, CancellationToken cancellationToken = default)
{
IList<ReadOnlyMemory<float>> result = [new float[] { 0, 1, 2, 3 }];
return Task.FromResult(result);
}
}
/// <summary>
/// Sample model class that represents a record entry.
/// </summary>
/// <remarks>
/// Note that each property is decorated with an attribute that specifies how the property should be treated by the vector store.
/// This allows us to create a collection in the vector store and upsert and retrieve instances of this class without any further configuration.
/// </remarks>
#pragma warning disable CA1812 // Avoid uninstantiated internal classes
public sealed class DataModel
#pragma warning restore CA1812 // Avoid uninstantiated internal classes
{
[VectorStoreKey]
public Guid Key { get; init; }
[VectorStoreData]
public required string Text { get; init; }
[VectorStoreData(IsIndexed = true)]
public required string Tag { get; init; }
[VectorStoreVector(1536)]
public string? Embedding { get; init; }
}
/// <summary>
/// Sample model class that represents a record entry.
/// </summary>
/// <remarks>
/// Note that each property is decorated with an attribute that specifies how the property should be treated by the vector store.
/// This allows us to create a collection in the vector store and upsert and retrieve instances of this class without any further configuration.
/// </remarks>
#pragma warning disable CA1812 // Avoid uninstantiated internal classes
public sealed class DataModelWithRawEmbedding
#pragma warning restore CA1812 // Avoid uninstantiated internal classes
{
[VectorStoreKey]
public Guid Key { get; init; }
[VectorStoreData]
public required string Text { get; init; }
[VectorStoreData(IsIndexed = true)]
public required string Tag { get; init; }
[VectorStoreVector(1536)]
public ReadOnlyMemory<float> Embedding { get; init; }
}
/// <summary>
/// Sample model class for testing collection-based filtering (AnyTagEqualTo).
/// </summary>
#pragma warning disable CA1812 // Avoid uninstantiated internal classes
public sealed class DataModelWithTags
#pragma warning restore CA1812 // Avoid uninstantiated internal classes
{
[VectorStoreKey]
public Guid Key { get; init; }
[VectorStoreData]
public required string Text { get; init; }
[VectorStoreData(IsIndexed = true)]
public required string Tag { get; init; }
[VectorStoreData(IsIndexed = true)]
public required IReadOnlyList<string> Tags { get; init; }
[VectorStoreVector(1536)]
public string? Embedding { get; init; }
}
}