Compare commits
1
Commits
34539cd764
...
5f518b86b2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f518b86b2 |
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,7 @@ namespace xAiModels.Interfaces
|
||||
/// <param name="text"></param>
|
||||
/// <param name="embedding"></param>
|
||||
/// <param name="metadata"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task UpsertVectorAsync(
|
||||
|
||||
@@ -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
|
||||
/// <param name="text"></param>
|
||||
/// <param name="embedding"></param>
|
||||
/// <param name="metadata"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
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<XAiVector> candidates;
|
||||
if (predicate.IsNull())
|
||||
var predicateExp = BuildVectorPredicateExpression(identifierPrefix, type);
|
||||
IAsyncEnumerable<XAiVector> 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;
|
||||
}
|
||||
|
||||
/// <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
|
||||
|
||||
//
|
||||
@@ -2354,27 +2321,41 @@ namespace xAiModels.Providers
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Search Similarity ...
|
||||
/// Build Database Predicate Expression for Vectors by Optional Identifier Prefix and Type ...
|
||||
/// Returns null when no Filter Provided ...
|
||||
/// </summary>
|
||||
/// <param name="a"></param>
|
||||
/// <param name="b"></param>
|
||||
/// <param name="identifierPrefix"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
private float ComputeCosineSimilarity(float[] a, float[] b)
|
||||
private Expression<Func<XAiVector, bool>> BuildVectorPredicateExpression(
|
||||
string identifierPrefix,
|
||||
string type
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
Expression<Func<XAiVector, bool>> 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;
|
||||
|
||||
Reference in New Issue
Block a user