|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.Extensions.VectorData; |
| 9 | +using Microsoft.Shared.Diagnostics; |
| 10 | + |
| 11 | +namespace Microsoft.Extensions.DataIngestion; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// Writes chunks to the <see cref="VectorStore"/> using the default schema. |
| 15 | +/// </summary> |
| 16 | +/// <typeparam name="T">The type of the chunk content.</typeparam> |
| 17 | +public sealed class VectorStoreWriter<T> : IngestionChunkWriter<T> |
| 18 | +{ |
| 19 | + // The names are lowercase with no special characters to ensure compatibility with various vector stores. |
| 20 | + private const string KeyName = "key"; |
| 21 | + private const string EmbeddingName = "embedding"; |
| 22 | + private const string ContentName = "content"; |
| 23 | + private const string ContextName = "context"; |
| 24 | + private const string DocumentIdName = "documentid"; |
| 25 | + |
| 26 | + private readonly VectorStore _vectorStore; |
| 27 | + private readonly int _dimensionCount; |
| 28 | + private readonly VectorStoreWriterOptions _options; |
| 29 | + private readonly bool _keysAreStrings; |
| 30 | + |
| 31 | + private VectorStoreCollection<object, Dictionary<string, object?>>? _vectorStoreCollection; |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Initializes a new instance of the <see cref="VectorStoreWriter{T}"/> class. |
| 35 | + /// </summary> |
| 36 | + /// <param name="vectorStore">The <see cref="VectorStore"/> to use to store the <see cref="IngestionChunk{T}"/> instances.</param> |
| 37 | + /// <param name="dimensionCount">The number of dimensions that the vector has. This value is required when creating collections.</param> |
| 38 | + /// <param name="options">The options for the vector store writer.</param> |
| 39 | + /// <exception cref="ArgumentNullException">When <paramref name="vectorStore"/> is null.</exception> |
| 40 | + /// <exception cref="ArgumentOutOfRangeException">When <paramref name="dimensionCount"/> is less or equal zero.</exception> |
| 41 | + public VectorStoreWriter(VectorStore vectorStore, int dimensionCount, VectorStoreWriterOptions? options = default) |
| 42 | + { |
| 43 | + _vectorStore = Throw.IfNull(vectorStore); |
| 44 | + _dimensionCount = Throw.IfLessThanOrEqual(dimensionCount, 0); |
| 45 | + _options = options ?? new VectorStoreWriterOptions(); |
| 46 | + |
| 47 | + // Not all vector store support string as the key type, examples: |
| 48 | + // Qdrant: https://github.com/microsoft/semantic-kernel/blob/28ea2f4df872e8fd03ef0792ebc9e1989b4be0ee/dotnet/src/VectorData/Qdrant/QdrantCollection.cs#L104 |
| 49 | + // When https://github.com/microsoft/semantic-kernel/issues/13141 gets released, |
| 50 | + // we need to remove this workaround. |
| 51 | + _keysAreStrings = vectorStore.GetType().Name != "QdrantVectorStore"; |
| 52 | + } |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Gets the underlying <see cref="VectorStoreCollection{TKey,TRecord}"/> used to store the chunks. |
| 56 | + /// </summary> |
| 57 | + /// <remarks> |
| 58 | + /// The collection is initialized when <see cref="WriteAsync(IAsyncEnumerable{IngestionChunk{T}}, CancellationToken)"/> is called for the first time. |
| 59 | + /// </remarks> |
| 60 | + /// <exception cref="InvalidOperationException">The collection has not been initialized yet. |
| 61 | + /// Call <see cref="WriteAsync(IAsyncEnumerable{IngestionChunk{T}}, CancellationToken)"/> first.</exception> |
| 62 | + public VectorStoreCollection<object, Dictionary<string, object?>> VectorStoreCollection |
| 63 | + => _vectorStoreCollection ?? throw new InvalidOperationException("The collection has not been initialized yet. Call WriteAsync first."); |
| 64 | + |
| 65 | + /// <inheritdoc/> |
| 66 | + public override async Task WriteAsync(IAsyncEnumerable<IngestionChunk<T>> chunks, CancellationToken cancellationToken = default) |
| 67 | + { |
| 68 | + _ = Throw.IfNull(chunks); |
| 69 | + |
| 70 | + IReadOnlyList<object>? preExistingKeys = null; |
| 71 | + await foreach (IngestionChunk<T> chunk in chunks.WithCancellation(cancellationToken)) |
| 72 | + { |
| 73 | + if (_vectorStoreCollection is null) |
| 74 | + { |
| 75 | + _vectorStoreCollection = _vectorStore.GetDynamicCollection(_options.CollectionName, GetVectorStoreRecordDefinition(chunk)); |
| 76 | + |
| 77 | + await _vectorStoreCollection.EnsureCollectionExistsAsync(cancellationToken).ConfigureAwait(false); |
| 78 | + } |
| 79 | + |
| 80 | + // We obtain the IDs of the pre-existing chunks for given document, |
| 81 | + // and delete them after we finish inserting the new chunks, |
| 82 | + // to avoid a situation where we delete the chunks and then fail to insert the new ones. |
| 83 | + preExistingKeys ??= await GetPreExistingChunksIdsAsync(chunk.Document, cancellationToken).ConfigureAwait(false); |
| 84 | + |
| 85 | + var key = Guid.NewGuid(); |
| 86 | + Dictionary<string, object?> record = new() |
| 87 | + { |
| 88 | + [KeyName] = _keysAreStrings ? key.ToString() : key, |
| 89 | + [ContentName] = chunk.Content, |
| 90 | + [EmbeddingName] = chunk.Content, |
| 91 | + [ContextName] = chunk.Context, |
| 92 | + [DocumentIdName] = chunk.Document.Identifier, |
| 93 | + }; |
| 94 | + |
| 95 | + if (chunk.HasMetadata) |
| 96 | + { |
| 97 | + foreach (var metadata in chunk.Metadata) |
| 98 | + { |
| 99 | + record[metadata.Key] = metadata.Value; |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + await _vectorStoreCollection.UpsertAsync(record, cancellationToken).ConfigureAwait(false); |
| 104 | + } |
| 105 | + |
| 106 | + if (preExistingKeys?.Count > 0) |
| 107 | + { |
| 108 | + await _vectorStoreCollection!.DeleteAsync(preExistingKeys, cancellationToken).ConfigureAwait(false); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /// <inheritdoc/> |
| 113 | + protected override void Dispose(bool disposing) |
| 114 | + { |
| 115 | + try |
| 116 | + { |
| 117 | + _vectorStoreCollection?.Dispose(); |
| 118 | + } |
| 119 | + finally |
| 120 | + { |
| 121 | + _vectorStore.Dispose(); |
| 122 | + base.Dispose(disposing); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + private VectorStoreCollectionDefinition GetVectorStoreRecordDefinition(IngestionChunk<T> representativeChunk) |
| 127 | + { |
| 128 | + VectorStoreCollectionDefinition definition = new() |
| 129 | + { |
| 130 | + Properties = |
| 131 | + { |
| 132 | + new VectorStoreKeyProperty(KeyName, _keysAreStrings ? typeof(string) : typeof(Guid)), |
| 133 | + |
| 134 | + // By using T as the type here we allow the vector store |
| 135 | + // to handle the conversion from T to the actual vector type it supports. |
| 136 | + new VectorStoreVectorProperty(EmbeddingName, typeof(T), _dimensionCount) |
| 137 | + { |
| 138 | + DistanceFunction = _options.DistanceFunction, |
| 139 | + IndexKind = _options.IndexKind |
| 140 | + }, |
| 141 | + new VectorStoreDataProperty(ContentName, typeof(T)), |
| 142 | + new VectorStoreDataProperty(ContextName, typeof(string)), |
| 143 | + new VectorStoreDataProperty(DocumentIdName, typeof(string)) |
| 144 | + { |
| 145 | + IsIndexed = true |
| 146 | + } |
| 147 | + } |
| 148 | + }; |
| 149 | + |
| 150 | + if (representativeChunk.HasMetadata) |
| 151 | + { |
| 152 | + foreach (var metadata in representativeChunk.Metadata) |
| 153 | + { |
| 154 | + Type propertyType = metadata.Value.GetType(); |
| 155 | + definition.Properties.Add(new VectorStoreDataProperty(metadata.Key, propertyType) |
| 156 | + { |
| 157 | + // We use lowercase storage names to ensure compatibility with various vector stores. |
| 158 | +#pragma warning disable CA1308 // Normalize strings to uppercase |
| 159 | + StorageName = metadata.Key.ToLowerInvariant() |
| 160 | +#pragma warning restore CA1308 // Normalize strings to uppercase |
| 161 | + |
| 162 | + // We could consider indexing for certain keys like classification etc. but for now we leave it as non-indexed. |
| 163 | + // The reason is that not every DB supports it, moreover we would need to expose the ability to configure it. |
| 164 | + }); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + return definition; |
| 169 | + } |
| 170 | + |
| 171 | + private async Task<IReadOnlyList<object>> GetPreExistingChunksIdsAsync(IngestionDocument document, CancellationToken cancellationToken) |
| 172 | + { |
| 173 | + if (!_options.IncrementalIngestion) |
| 174 | + { |
| 175 | + return []; |
| 176 | + } |
| 177 | + |
| 178 | + // Each Vector Store has a different max top count limit, so we use low value and loop. |
| 179 | + const int MaxTopCount = 1_000; |
| 180 | + |
| 181 | + List<object> keys = []; |
| 182 | + int insertedCount; |
| 183 | + do |
| 184 | + { |
| 185 | + insertedCount = 0; |
| 186 | + |
| 187 | + await foreach (var record in _vectorStoreCollection!.GetAsync( |
| 188 | + filter: record => (string)record[DocumentIdName]! == document.Identifier, |
| 189 | + top: MaxTopCount, |
| 190 | + cancellationToken: cancellationToken).ConfigureAwait(false)) |
| 191 | + { |
| 192 | + keys.Add(record[KeyName]!); |
| 193 | + insertedCount++; |
| 194 | + } |
| 195 | + } |
| 196 | + while (insertedCount == MaxTopCount); |
| 197 | + |
| 198 | + return keys; |
| 199 | + } |
| 200 | +} |
0 commit comments