This commit is contained in:
2026-10-28 00:08:26 +03:30
parent 34539cd764
commit 5f518b86b2
3 changed files with 130 additions and 74 deletions
+74
View File
@@ -0,0 +1,74 @@
using System;
using xCommons.Extensions;
using System.Numerics.Tensors;
using xExceptions.Constants;
namespace xAiModels.Helpers
{
public static class VectorHelper
{
/// <summary>
/// Normalize a Vector ...
/// </summary>
/// <param name="vector"></param>
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;
}
}
/// <summary>
/// Similarity Check ...
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
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;
}
}
}
+1
View File
@@ -308,6 +308,7 @@ namespace xAiModels.Interfaces
/// <param name="text"></param> /// <param name="text"></param>
/// <param name="embedding"></param> /// <param name="embedding"></param>
/// <param name="metadata"></param> /// <param name="metadata"></param>
/// <param name="type"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task UpsertVectorAsync( Task UpsertVectorAsync(
+55 -74
View File
@@ -2,6 +2,7 @@ using System;
using System.Linq; using System.Linq;
using xModels.Dtos; using xModels.Dtos;
using System.Threading; using System.Threading;
using xAiModels.Helpers;
using xAiModels.Constants; using xAiModels.Constants;
using xCommons.Extensions; using xCommons.Extensions;
using xAiModels.Extensions; using xAiModels.Extensions;
@@ -12,7 +13,6 @@ using System.Threading.Tasks;
using xCommons.Configurations; using xCommons.Configurations;
using System.Linq.Expressions; using System.Linq.Expressions;
using xDataService.Extensions; using xDataService.Extensions;
using System.Numerics.Tensors;
using xAiModels.Providers.Hubs; using xAiModels.Providers.Hubs;
using xAiModels.Interfaces.Dtos; using xAiModels.Interfaces.Dtos;
using xStringService.Interfaces; using xStringService.Interfaces;
@@ -1307,6 +1307,7 @@ namespace xAiModels.Providers
/// <param name="text"></param> /// <param name="text"></param>
/// <param name="embedding"></param> /// <param name="embedding"></param>
/// <param name="metadata"></param> /// <param name="metadata"></param>
/// <param name="type"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task UpsertVectorAsync( public async Task UpsertVectorAsync(
@@ -1402,26 +1403,34 @@ namespace xAiModels.Providers
// //
// Load Candidates (Restricted by Prefix / Type when Provided) ... // Load Candidates (Restricted by Prefix / Type when Provided) ...
var predicate = BuildVectorPredicate(identifierPrefix, type); var predicateExp = BuildVectorPredicateExpression(identifierPrefix, type);
IEnumerable<XAiVector> candidates; IAsyncEnumerable<XAiVector> candidates;
if (predicate.IsNull()) if (predicateExp.IsNull())
{ {
candidates = await vectorRepository.GetAllAsync( //
ignoreSoftDeleteds: true, candidates = vectorRepository
cancellationToken: cancellationToken .GetAllAsAsyncEnumerable(
); ignoreSoftDeleteds: true,
orderBuilder: null,
includeBuilder: null
);
} }
else else
{ {
candidates = await vectorRepository.FindManyAsync( //
predicate: predicate, candidates = (await vectorRepository
ignoreSoftDeleteds: true, .FindManyAsync(
cancellationToken: cancellationToken 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 ... // Validate Vector ...
@@ -1430,13 +1439,6 @@ namespace xAiModels.Providers
continue; continue;
} }
//
// Check Cancellation Token ...
if (cancellationToken.IsCancellationRequested)
{
break;
}
// //
// Ignore Unsame Vectors ... // Ignore Unsame Vectors ...
var embd = vector.Embedding.AsEmbedding(); var embd = vector.Embedding.AsEmbedding();
@@ -1450,7 +1452,7 @@ namespace xAiModels.Providers
// //
// Calculate Cosine Similarity Score ... // Calculate Cosine Similarity Score ...
var score = ComputeCosineSimilarity(queryVector, embd); var score = VectorHelper.CosineSimilarity(queryVector, embd);
if (score < minScore) if (score < minScore)
{ {
continue; continue;
@@ -1605,7 +1607,7 @@ namespace xAiModels.Providers
var vectors = await vectorRepository.FindManyAsync( var vectors = await vectorRepository.FindManyAsync(
ignoreSoftDeleteds: true, ignoreSoftDeleteds: true,
cancellationToken: cancellationToken, cancellationToken: cancellationToken,
predicate: BuildVectorPredicate(identifierPrefix, type) predicate: BuildVectorPredicateExpression(identifierPrefix, type)
); );
// //
@@ -1649,7 +1651,7 @@ namespace xAiModels.Providers
var vectors = await vectorRepository.FindManyAsync( var vectors = await vectorRepository.FindManyAsync(
ignoreSoftDeleteds: true, ignoreSoftDeleteds: true,
cancellationToken: cancellationToken, cancellationToken: cancellationToken,
predicate: BuildVectorPredicate(identifierPrefix, type) predicate: BuildVectorPredicateExpression(identifierPrefix, type)
); );
var toRemove = (vectors ?? []).ToList(); var toRemove = (vectors ?? []).ToList();
if (!toRemove.HasChild()) if (!toRemove.HasChild())
@@ -1670,41 +1672,6 @@ namespace xAiModels.Providers
var result = toRemove.Count; var result = toRemove.Count;
return result; return result;
} }
/// <summary>
/// Build Database Predicate for Vectors by Optional Identifier Prefix and Type ...
/// Returns null when no Filter Provided ...
/// </summary>
/// <param name="identifierPrefix"></param>
/// <param name="type"></param>
/// <returns></returns>
private static Expression<Func<XAiVector, bool>> 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 #endregion
// //
@@ -2354,27 +2321,41 @@ namespace xAiModels.Providers
} }
/// <summary> /// <summary>
/// Search Similarity ... /// Build Database Predicate Expression for Vectors by Optional Identifier Prefix and Type ...
/// Returns null when no Filter Provided ...
/// </summary> /// </summary>
/// <param name="a"></param> /// <param name="identifierPrefix"></param>
/// <param name="b"></param> /// <param name="type"></param>
/// <returns></returns> /// <returns></returns>
private float ComputeCosineSimilarity(float[] a, float[] b) private Expression<Func<XAiVector, bool>> BuildVectorPredicateExpression(
string identifierPrefix,
string type
)
{ {
// //
// Validate ... Expression<Func<XAiVector, bool>> result = null;
if (a.Length != b.Length)
{
XException.InvalidArgs.Throw();
}
// //
// Check Similarity ... var hasType = !type.IsNullOrEmpty();
var result = TensorPrimitives var hasPrefix = !identifierPrefix.IsNullOrEmpty();
.CosineSimilarity(
a.AsSpan(), //
b.AsSpan() 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; return result;