// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
namespace MCPServer;
///
/// Extensions for vector stores.
///
public static class VectorStoreExtensions
{
///
/// Delegate to create a record from a string.
///
/// Type of the record key.
/// Type of the record.
public delegate TRecord CreateRecordFromString(string text, ReadOnlyMemory vector) where TKey : notnull;
///
/// Create a from a list of strings by:
///
/// The data type of the record key.
/// The data type of the record.
/// The instance of used to create the collection.
/// The name of the collection.
/// The list of strings to create records from.
/// The text embedding generation service.
/// The delegate which can create a record for each string and its embedding.
/// The created collection.
public static async Task> CreateCollectionFromListAsync(
this VectorStore vectorStore,
string collectionName,
string[] entries,
IEmbeddingGenerator> embeddingGenerator,
CreateRecordFromString createRecord)
where TKey : notnull
where TRecord : class
{
// Get and create collection if it doesn't exist.
var collection = vectorStore.GetCollection(collectionName);
await collection.EnsureCollectionExistsAsync().ConfigureAwait(false);
// Create records and generate embeddings for them.
var tasks = entries.Select(entry => Task.Run(async () =>
{
var record = createRecord(entry, (await embeddingGenerator.GenerateAsync(entry).ConfigureAwait(false)).Vector);
await collection.UpsertAsync(record).ConfigureAwait(false);
}));
await Task.WhenAll(tasks).ConfigureAwait(false);
return collection;
}
}