diff --git a/Helpers/VectorHelper.cs b/Helpers/VectorHelper.cs new file mode 100644 index 0000000..82d7e19 --- /dev/null +++ b/Helpers/VectorHelper.cs @@ -0,0 +1,74 @@ +using System; +using xCommons.Extensions; +using System.Numerics.Tensors; +using xExceptions.Constants; + +namespace xAiModels.Helpers +{ + public static class VectorHelper + { + /// + /// Normalize a Vector ... + /// + /// + public static void Normalize(float[] vector) + { + // + // Validate ... + if (vector.IsNull() || !vector.HasChild()) + { + return; + } + + // + float sum = 0f; + foreach (var value in vector) + { + sum += value * value; + } + + // + float norm = MathF.Sqrt(sum); + if (norm <= 1e-9f) + { + return; + } + + // + for (int i = 0; i < vector.Length; i++) + { + vector[i] /= norm; + } + } + + /// + /// Similarity Check ... + /// + /// + /// + /// + public static float CosineSimilarity( + float[] a, + float[] b + ) + { + // + // Validate ... + if (a.Length != b.Length) + { + XException.InvalidArgs.Throw(); + } + + // + // Check Similarity ... + var result = TensorPrimitives + .CosineSimilarity( + a.AsSpan(), + b.AsSpan() + ); + + // + return result; + } + } +} \ No newline at end of file diff --git a/Interfaces/IXAiDataProvider.cs b/Interfaces/IXAiDataProvider.cs index 21bbdc7..70bd5d3 100644 --- a/Interfaces/IXAiDataProvider.cs +++ b/Interfaces/IXAiDataProvider.cs @@ -308,6 +308,7 @@ namespace xAiModels.Interfaces /// /// /// + /// /// /// Task UpsertVectorAsync( diff --git a/Providers/XAiDataProvider.cs b/Providers/XAiDataProvider.cs index 28ef684..97327e7 100644 --- a/Providers/XAiDataProvider.cs +++ b/Providers/XAiDataProvider.cs @@ -2,6 +2,7 @@ using System; using System.Linq; using xModels.Dtos; using System.Threading; +using xAiModels.Helpers; using xAiModels.Constants; using xCommons.Extensions; using xAiModels.Extensions; @@ -12,7 +13,6 @@ using System.Threading.Tasks; using xCommons.Configurations; using System.Linq.Expressions; using xDataService.Extensions; -using System.Numerics.Tensors; using xAiModels.Providers.Hubs; using xAiModels.Interfaces.Dtos; using xStringService.Interfaces; @@ -1307,6 +1307,7 @@ namespace xAiModels.Providers /// /// /// + /// /// /// public async Task UpsertVectorAsync( @@ -1402,26 +1403,34 @@ namespace xAiModels.Providers // // Load Candidates (Restricted by Prefix / Type when Provided) ... - var predicate = BuildVectorPredicate(identifierPrefix, type); - IEnumerable candidates; - if (predicate.IsNull()) + var predicateExp = BuildVectorPredicateExpression(identifierPrefix, type); + IAsyncEnumerable candidates; + if (predicateExp.IsNull()) { - candidates = await vectorRepository.GetAllAsync( - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); + // + candidates = vectorRepository + .GetAllAsAsyncEnumerable( + ignoreSoftDeleteds: true, + orderBuilder: null, + includeBuilder: null + ); } else { - candidates = await vectorRepository.FindManyAsync( - predicate: predicate, - ignoreSoftDeleteds: true, - cancellationToken: cancellationToken - ); + // + candidates = (await vectorRepository + .FindManyAsync( + predicate: predicateExp, + ignoreSoftDeleteds: true, + orderBuilder: null, + includeBuilder: null, + cancellationToken: cancellationToken + )) + .ToAsyncEnumerable(); } // - foreach (var vector in candidates ?? []) + await foreach (var vector in candidates.WithCancellation(cancellationToken)) { // // Validate Vector ... @@ -1430,13 +1439,6 @@ namespace xAiModels.Providers continue; } - // - // Check Cancellation Token ... - if (cancellationToken.IsCancellationRequested) - { - break; - } - // // Ignore Unsame Vectors ... var embd = vector.Embedding.AsEmbedding(); @@ -1450,7 +1452,7 @@ namespace xAiModels.Providers // // Calculate Cosine Similarity Score ... - var score = ComputeCosineSimilarity(queryVector, embd); + var score = VectorHelper.CosineSimilarity(queryVector, embd); if (score < minScore) { continue; @@ -1605,7 +1607,7 @@ namespace xAiModels.Providers var vectors = await vectorRepository.FindManyAsync( ignoreSoftDeleteds: true, cancellationToken: cancellationToken, - predicate: BuildVectorPredicate(identifierPrefix, type) + predicate: BuildVectorPredicateExpression(identifierPrefix, type) ); // @@ -1649,7 +1651,7 @@ namespace xAiModels.Providers var vectors = await vectorRepository.FindManyAsync( ignoreSoftDeleteds: true, cancellationToken: cancellationToken, - predicate: BuildVectorPredicate(identifierPrefix, type) + predicate: BuildVectorPredicateExpression(identifierPrefix, type) ); var toRemove = (vectors ?? []).ToList(); if (!toRemove.HasChild()) @@ -1670,41 +1672,6 @@ namespace xAiModels.Providers var result = toRemove.Count; return result; } - - /// - /// Build Database Predicate for Vectors by Optional Identifier Prefix and Type ... - /// Returns null when no Filter Provided ... - /// - /// - /// - /// - private static Expression> BuildVectorPredicate( - string identifierPrefix, - string type - ) - { - // - var hasType = !type.IsNullOrEmpty(); - var hasPrefix = !identifierPrefix.IsNullOrEmpty(); - - // - if (hasPrefix && hasType) - { - return x => x.Identifier.StartsWith(identifierPrefix) && x.Type == type; - } - if (hasPrefix) - { - return x => x.Identifier.StartsWith(identifierPrefix); - } - if (hasType) - { - return x => x.Type == type; - } - - // - return null; - } - #endregion // @@ -2354,27 +2321,41 @@ namespace xAiModels.Providers } /// - /// Search Similarity ... + /// Build Database Predicate Expression for Vectors by Optional Identifier Prefix and Type ... + /// Returns null when no Filter Provided ... /// - /// - /// + /// + /// /// - private float ComputeCosineSimilarity(float[] a, float[] b) + private Expression> BuildVectorPredicateExpression( + string identifierPrefix, + string type + ) { // - // Validate ... - if (a.Length != b.Length) - { - XException.InvalidArgs.Throw(); - } + Expression> result = null; // - // Check Similarity ... - var result = TensorPrimitives - .CosineSimilarity( - a.AsSpan(), - b.AsSpan() - ); + var hasType = !type.IsNullOrEmpty(); + var hasPrefix = !identifierPrefix.IsNullOrEmpty(); + + // + if (hasPrefix && hasType) + { + // + result = x => x.Identifier + .StartsWith(identifierPrefix) && x.Type == type; + } + else if (hasPrefix) + { + // + result = x => x.Identifier + .StartsWith(identifierPrefix); + } + else if (hasType) + { + result = x => x.Type == type; + } // return result;