diff --git a/Interfaces/IXAiDataProvider.cs b/Interfaces/IXAiDataProvider.cs
index eea4246..abe9f35 100644
--- a/Interfaces/IXAiDataProvider.cs
+++ b/Interfaces/IXAiDataProvider.cs
@@ -298,5 +298,77 @@ namespace xAiModels.Interfaces
CancellationToken cancellationToken = default
);
#endregion
+
+ //
+ #region Vectors ...
+ ///
+ /// Insert or Update a Single Vector (Matched by Identifier) ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task UpsertVectorAsync(
+ string identifier,
+ string text,
+ ReadOnlyMemory embedding,
+ Dictionary metadata = null,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Insert or Update a Batch of Vectors (Matched by Identifier) ...
+ ///
+ ///
+ ///
+ /// Count of Stored Vectors
+ Task UpsertVectorsAsync(
+ IEnumerable items,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Search Vectors by Cosine Similarity (Top K) ...
+ ///
+ ///
+ ///
+ ///
+ /// Optional: Restrict Search to Vectors whose Identifier Starts with this Prefix
+ ///
+ ///
+ Task> SearchVectorsAsync(
+ ReadOnlyMemory queryEmbedding,
+ int topK = 5,
+ float minScore = 0f,
+ string identifierPrefix = null,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Load Vectors whose Identifier Starts with Specified Prefix ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> LoadVectorsAsync(
+ string identifierPrefix,
+ bool includeEmbedding = false,
+ CancellationToken cancellationToken = default
+ );
+
+ ///
+ /// Remove Vectors whose Identifier Starts with Specified Prefix ...
+ ///
+ ///
+ ///
+ /// Count of Removed Vectors
+ Task RemoveVectorsAsync(
+ string identifierPrefix,
+ CancellationToken cancellationToken = default
+ );
+ #endregion
}
}
\ No newline at end of file
diff --git a/Providers/XAiDataProvider.cs b/Providers/XAiDataProvider.cs
index 14c98a4..fe81612 100644
--- a/Providers/XAiDataProvider.cs
+++ b/Providers/XAiDataProvider.cs
@@ -1301,7 +1301,7 @@ namespace xAiModels.Providers
//
#region Vectors ...
///
- /// Insert or Update ...
+ /// Insert or Update a Single Vector (Matched by Identifier) ...
///
///
///
@@ -1309,7 +1309,7 @@ namespace xAiModels.Providers
///
///
///
- public async Task UpsertAsync(
+ public async Task UpsertVectorAsync(
string identifier,
string text,
ReadOnlyMemory embedding,
@@ -1341,6 +1341,7 @@ namespace xAiModels.Providers
//
exists.Text = text;
exists.Embedding = embedding.ToJSON();
+ exists.Metadata = metadata.IsNullOrDefault() ? exists.Metadata : metadata.ToJSON();
}
else
{
@@ -1363,15 +1364,19 @@ namespace xAiModels.Providers
}
///
- /// Search Cosine Similarity based on Top K ...
+ /// Search Vectors by Cosine Similarity (Top K) ...
///
///
///
+ ///
+ ///
///
///
- public async Task> SearchAsync(
+ public async Task> SearchVectorsAsync(
ReadOnlyMemory queryEmbedding,
int topK = 5,
+ float minScore = 0f,
+ string identifierPrefix = null,
CancellationToken cancellationToken = default
)
{
@@ -1391,8 +1396,26 @@ namespace xAiModels.Providers
var scoredResult = new List<(XAiVectorSearchResult Result, float Score)>();
//
- var vectorsEnumerator = vectorRepository.GetAllAsAsyncEnumerable();
- await foreach (var vector in vectorsEnumerator)
+ // Load Candidates (Restricted by Prefix when Provided) ...
+ IEnumerable candidates;
+ if (identifierPrefix.IsNullOrEmpty())
+ {
+ candidates = await vectorRepository.GetAllAsync(
+ ignoreSoftDeleteds: true,
+ cancellationToken: cancellationToken
+ );
+ }
+ else
+ {
+ candidates = await vectorRepository.FindManyAsync(
+ ignoreSoftDeleteds: true,
+ cancellationToken: cancellationToken,
+ predicate: x => x.Identifier.StartsWith(identifierPrefix)
+ );
+ }
+
+ //
+ foreach (var vector in candidates ?? [])
{
//
// Validate Vector ...
@@ -1422,6 +1445,10 @@ namespace xAiModels.Providers
//
// Calculate Cosine Similarity Score ...
var score = ComputeCosineSimilarity(queryVector, embd);
+ if (score < minScore)
+ {
+ continue;
+ }
//
scoredResult.Add((new XAiVectorSearchResult
@@ -1445,6 +1472,191 @@ namespace xAiModels.Providers
//
return result;
}
+
+ ///
+ /// Insert or Update a Batch of Vectors (Matched by Identifier) ...
+ ///
+ ///
+ ///
+ /// Count of Stored Vectors
+ public async Task UpsertVectorsAsync(
+ IEnumerable items,
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ // Validate & Normalize (Last One Wins on Duplicate Identifiers) ...
+ var validItems = (items ?? [])
+ .Where(x =>
+ !x.IsNullOrDefault() &&
+ !x.Embedding.IsEmpty &&
+ !x.Text.IsNullOrEmpty() &&
+ !x.Identifier.IsNullOrEmpty()
+ )
+ .GroupBy(x => x.Identifier)
+ .Select(g => g.Last())
+ .ToList();
+ if (!validItems.HasChild())
+ {
+ return 0;
+ }
+
+ //
+ // Load Existing Vectors with Same Identifiers ...
+ var identifiers = validItems
+ .Select(x => x.Identifier)
+ .ToList();
+ var existings = await vectorRepository.FindManyAsync(
+ ignoreSoftDeleteds: true,
+ cancellationToken: cancellationToken,
+ predicate: x => identifiers.Contains(x.Identifier)
+ );
+ var existingMap = (existings ?? [])
+ .GroupBy(x => x.Identifier)
+ .ToDictionary(g => g.Key, g => g.First());
+
+ //
+ // Split to Insert / Update ...
+ var toAdd = new List();
+ var toUpdate = new List();
+ foreach (var item in validItems)
+ {
+ //
+ if (existingMap.TryGetValue(item.Identifier, out var exists))
+ {
+ //
+ exists.Text = item.Text;
+ exists.Embedding = item.Embedding.ToJSON();
+ exists.Metadata = item.Metadata.IsNullOrDefault() ? exists.Metadata : item.Metadata.ToJSON();
+ toUpdate.Add(exists);
+ }
+ else
+ {
+ //
+ toAdd.Add(new XAiVector
+ {
+ Text = item.Text,
+ Identifier = item.Identifier,
+ Metadata = item.Metadata.ToJSON(),
+ Embedding = item.Embedding.ToJSON(),
+ Id = item.Id.IsDefaultGuid() ? Guid.NewGuid() : item.Id,
+ });
+ }
+ }
+
+ //
+ if (toUpdate.HasChild())
+ {
+ await vectorRepository.UpdateRangeAsync(
+ items: toUpdate,
+ saveChanges: false,
+ cancellationToken: cancellationToken
+ );
+ }
+ if (toAdd.HasChild())
+ {
+ await vectorRepository.AddRangeAsync(
+ items: toAdd,
+ saveChanges: false,
+ cancellationToken: cancellationToken
+ );
+ }
+
+ //
+ await vectorRepository.SaveChangesAsync(cancellationToken);
+
+ //
+ var result = toAdd.Count + toUpdate.Count;
+ return result;
+ }
+
+ ///
+ /// Load Vectors whose Identifier Starts with Specified Prefix ...
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task> LoadVectorsAsync(
+ string identifierPrefix,
+ bool includeEmbedding = false,
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ // Validate ...
+ if (identifierPrefix.IsNullOrEmpty())
+ {
+ XException.InvalidArgs.Throw();
+ }
+
+ //
+ var vectors = await vectorRepository.FindManyAsync(
+ ignoreSoftDeleteds: true,
+ cancellationToken: cancellationToken,
+ predicate: x => x.Identifier.StartsWith(identifierPrefix)
+ );
+
+ //
+ var result = (vectors ?? [])
+ .Select(v => new XAiVectorDto
+ {
+ Id = v.Id,
+ Text = v.Text,
+ Identifier = v.Identifier,
+ Metadata = v.Metadata.AsMetadat(),
+ Embedding = includeEmbedding ? v.Embedding.AsEmbedding() : null,
+ })
+ .ToList();
+
+ //
+ return result;
+ }
+
+ ///
+ /// Remove Vectors whose Identifier Starts with Specified Prefix ...
+ ///
+ ///
+ ///
+ /// Count of Removed Vectors
+ public async Task RemoveVectorsAsync(
+ string identifierPrefix,
+ CancellationToken cancellationToken = default
+ )
+ {
+ //
+ // Validate ...
+ if (identifierPrefix.IsNullOrEmpty())
+ {
+ XException.InvalidArgs.Throw();
+ }
+
+ //
+ var vectors = await vectorRepository.FindManyAsync(
+ ignoreSoftDeleteds: true,
+ cancellationToken: cancellationToken,
+ predicate: x => x.Identifier.StartsWith(identifierPrefix)
+ );
+ var toRemove = (vectors ?? []).ToList();
+ if (!toRemove.HasChild())
+ {
+ return 0;
+ }
+
+ //
+ // Hard Delete (Vectors are Disposable Data) ...
+ await vectorRepository.RemoveRangeAsync(
+ items: toRemove,
+ softDelete: false,
+ saveChanges: true,
+ cancellationToken: cancellationToken
+ );
+
+ //
+ var result = toRemove.Count;
+ return result;
+ }
+
#endregion
//