BotSharp/src/Plugins/BotSharp.Plugin.Qdrant/QdrantDb.cs

259 lines
8.1 KiB
C#
Raw Normal View History

2024-08-06 22:43:11 +00:00
using BotSharp.Abstraction.Utilities;
2024-08-15 23:19:10 +00:00
using BotSharp.Abstraction.VectorStorage.Models;
2024-09-12 22:48:47 +00:00
using Google.Protobuf.WellKnownTypes;
2024-09-10 19:02:25 +00:00
using Microsoft.Extensions.Logging;
2023-11-14 01:25:25 +00:00
using Qdrant.Client;
using Qdrant.Client.Grpc;
2023-06-18 02:56:22 +00:00
namespace BotSharp.Plugin.Qdrant;
public class QdrantDb : IVectorDb
{
2024-01-06 03:24:13 +00:00
private QdrantClient _client;
2023-06-18 02:56:22 +00:00
private readonly QdrantSetting _setting;
2023-06-27 23:36:50 +00:00
private readonly IServiceProvider _services;
2024-09-10 19:02:25 +00:00
private readonly ILogger<QdrantDb> _logger;
2023-06-27 23:36:50 +00:00
public QdrantDb(
QdrantSetting setting,
2024-09-10 19:02:25 +00:00
ILogger<QdrantDb> logger,
2023-06-27 23:36:50 +00:00
IServiceProvider services)
2023-06-18 02:56:22 +00:00
{
_setting = setting;
2024-09-10 19:02:25 +00:00
_logger = logger;
2023-06-27 23:36:50 +00:00
_services = services;
2024-01-06 03:24:13 +00:00
}
2024-08-31 00:31:18 +00:00
public string Provider => "Qdrant";
2024-01-06 03:24:13 +00:00
private QdrantClient GetClient()
{
if (_client == null)
{
_client = new QdrantClient
(
host: _setting.Url,
2024-07-02 14:52:16 +00:00
https: true,
2024-01-06 03:24:13 +00:00
apiKey: _setting.ApiKey
);
}
return _client;
2023-06-18 02:56:22 +00:00
}
2024-09-10 19:02:25 +00:00
public async Task<bool> CreateCollection(string collectionName, int dimension)
2024-08-29 19:30:47 +00:00
{
var client = GetClient();
var exist = await DoesCollectionExist(client, collectionName);
if (exist) return false;
2024-09-10 19:02:25 +00:00
try
2024-08-29 19:30:47 +00:00
{
2024-09-10 19:02:25 +00:00
// Create a new collection
await client.CreateCollectionAsync(collectionName, new VectorParams()
{
Size = (ulong)dimension,
Distance = Distance.Cosine
});
return true;
}
catch (Exception ex)
{
_logger.LogWarning($"Error when create collection (Name: {collectionName}, Dimension: {dimension}).");
return false;
}
2024-08-29 19:30:47 +00:00
}
public async Task<bool> DeleteCollection(string collectionName)
{
var client = GetClient();
var exist = await DoesCollectionExist(client, collectionName);
if (!exist) return false;
await client.DeleteCollectionAsync(collectionName);
return true;
}
2024-08-08 22:15:51 +00:00
public async Task<IEnumerable<string>> GetCollections()
2023-06-18 02:56:22 +00:00
{
// List all the collections
2024-07-02 14:52:16 +00:00
var collections = await GetClient().ListCollectionsAsync();
2023-11-14 01:25:25 +00:00
return collections.ToList();
2023-06-18 02:56:22 +00:00
}
2024-08-23 16:25:44 +00:00
public async Task<StringIdPagedItems<VectorCollectionData>> GetPagedCollectionData(string collectionName, VectorFilter filter)
2024-08-06 22:43:11 +00:00
{
var client = GetClient();
var exist = await DoesCollectionExist(client, collectionName);
if (!exist)
2024-08-06 22:43:11 +00:00
{
2024-08-15 23:19:10 +00:00
return new StringIdPagedItems<VectorCollectionData>();
2024-08-06 22:43:11 +00:00
}
2024-08-28 22:45:33 +00:00
// Build query filter
Filter? queryFilter = null;
if (!filter.SearchPairs.IsNullOrEmpty())
{
var conditions = filter.SearchPairs.Select(x => new Condition
{
Field = new FieldCondition
{
Key = x.Key,
Match = new Match { Text = x.Value },
}
});
queryFilter = new Filter
{
Should =
{
conditions
}
};
}
2024-09-12 22:48:47 +00:00
// Build payload selector
WithPayloadSelector? payloadSelector = null;
if (!filter.IncludedPayloads.IsNullOrEmpty())
{
payloadSelector = new WithPayloadSelector
{
Enable = true,
Include = new PayloadIncludeSelector
{
Fields = { filter.IncludedPayloads.ToArray() }
}
};
}
2024-08-28 22:45:33 +00:00
var totalPointCount = await client.CountAsync(collectionName, filter: queryFilter);
2024-08-07 16:50:23 +00:00
var response = await client.ScrollAsync(collectionName, limit: (uint)filter.Size,
2024-08-28 22:45:33 +00:00
offset: !string.IsNullOrWhiteSpace(filter.StartId) ? new PointId { Uuid = filter.StartId } : null,
filter: queryFilter,
2024-09-12 22:48:47 +00:00
payloadSelector: payloadSelector,
2024-08-06 22:43:11 +00:00
vectorsSelector: filter.WithVector);
2024-08-28 22:45:33 +00:00
2024-08-15 23:19:10 +00:00
var points = response?.Result?.Select(x => new VectorCollectionData
2024-08-06 22:43:11 +00:00
{
Id = x.Id?.Uuid ?? string.Empty,
2024-08-15 03:46:01 +00:00
Data = x.Payload.ToDictionary(x => x.Key, x => x.Value.StringValue),
2024-08-06 22:43:11 +00:00
Vector = filter.WithVector ? x.Vectors?.Vector?.Data?.ToArray() : null
2024-08-15 23:19:10 +00:00
})?.ToList() ?? new List<VectorCollectionData>();
2024-08-06 22:43:11 +00:00
2024-08-15 23:19:10 +00:00
return new StringIdPagedItems<VectorCollectionData>
2024-08-06 22:43:11 +00:00
{
Count = totalPointCount,
NextId = response?.NextPageOffset?.Uuid,
Items = points
};
}
2024-08-23 16:25:44 +00:00
public async Task<IEnumerable<VectorCollectionData>> GetCollectionData(string collectionName, IEnumerable<Guid> ids,
bool withPayload = false, bool withVector = false)
{
if (ids.IsNullOrEmpty()) return Enumerable.Empty<VectorCollectionData>();
var client = GetClient();
var exist = await DoesCollectionExist(client, collectionName);
if (!exist)
{
return Enumerable.Empty<VectorCollectionData>();
}
var pointIds = ids.Select(x => new PointId { Uuid = x.ToString() }).Distinct().ToList();
var points = await client.RetrieveAsync(collectionName, pointIds, withPayload, withVector);
return points.Select(x => new VectorCollectionData
{
Id = x.Id?.Uuid ?? string.Empty,
Data = x.Payload?.ToDictionary(x => x.Key, x => x.Value.StringValue) ?? new(),
Vector = x.Vectors?.Vector?.Data?.ToArray()
});
}
public async Task<bool> Upsert(string collectionName, Guid id, float[] vector, string text, Dictionary<string, string>? payload = null)
2023-06-18 02:56:22 +00:00
{
// Insert vectors
2024-07-02 14:52:16 +00:00
var point = new PointStruct()
2023-06-18 02:56:22 +00:00
{
2024-07-02 14:52:16 +00:00
Id = new PointId()
2023-11-14 01:25:25 +00:00
{
Uuid = id.ToString()
2024-07-02 14:52:16 +00:00
},
Vectors = vector,
2024-08-06 22:43:11 +00:00
Payload =
2024-07-17 21:03:46 +00:00
{
2024-08-06 19:01:26 +00:00
{ KnowledgePayloadName.Text, text }
2024-07-17 21:03:46 +00:00
}
2024-07-02 14:52:16 +00:00
};
2023-06-27 23:36:50 +00:00
2024-07-17 21:03:46 +00:00
if (payload != null)
2024-07-02 14:52:16 +00:00
{
2024-07-17 21:03:46 +00:00
foreach (var item in payload)
{
point.Payload.Add(item.Key, item.Value);
}
2024-07-02 14:52:16 +00:00
}
2024-07-17 21:03:46 +00:00
var client = GetClient();
var result = await client.UpsertAsync(collectionName, points: new List<PointStruct>
2024-07-02 14:52:16 +00:00
{
point
});
2024-07-17 21:03:46 +00:00
return result.Status == UpdateStatus.Completed;
2023-06-18 02:56:22 +00:00
}
2024-08-15 23:19:10 +00:00
public async Task<IEnumerable<VectorCollectionData>> Search(string collectionName, float[] vector,
2024-08-15 03:46:01 +00:00
IEnumerable<string>? fields, int limit = 5, float confidence = 0.5f, bool withVector = false)
2023-06-18 02:56:22 +00:00
{
2024-08-15 23:19:10 +00:00
var results = new List<VectorCollectionData>();
2024-08-13 18:26:57 +00:00
2024-07-17 21:03:46 +00:00
var client = GetClient();
2024-08-13 18:26:57 +00:00
var exist = await DoesCollectionExist(client, collectionName);
if (!exist)
{
return results;
}
2023-06-27 23:36:50 +00:00
2024-08-28 22:45:33 +00:00
var payloadSelector = new WithPayloadSelector { Enable = true };
if (fields != null)
{
payloadSelector.Include = new PayloadIncludeSelector { Fields = { fields.ToArray() } };
}
var points = await client.SearchAsync(collectionName,
2024-08-28 22:45:33 +00:00
vector,
limit: (ulong)limit,
scoreThreshold: confidence,
payloadSelector: payloadSelector,
vectorsSelector: withVector);
2024-08-15 03:46:01 +00:00
2024-08-28 22:45:33 +00:00
results = points.Select(x => new VectorCollectionData
{
2024-08-28 22:45:33 +00:00
Id = x.Id.Uuid,
Data = x.Payload.ToDictionary(x => x.Key, x => x.Value.StringValue),
Score = x.Score,
Vector = x.Vectors?.Vector?.Data?.ToArray()
}).ToList();
return results;
2023-06-18 02:56:22 +00:00
}
2024-08-08 22:15:51 +00:00
2024-09-10 19:02:25 +00:00
public async Task<bool> DeleteCollectionData(string collectionName, List<Guid> ids)
2024-08-08 22:15:51 +00:00
{
2024-09-10 19:02:25 +00:00
if (ids.IsNullOrEmpty()) return false;
2024-08-08 22:15:51 +00:00
var client = GetClient();
2024-09-10 19:02:25 +00:00
var result = await client.DeleteAsync(collectionName, ids);
2024-08-08 22:15:51 +00:00
return result.Status == UpdateStatus.Completed;
}
private async Task<bool> DoesCollectionExist(QdrantClient client, string collectionName)
{
return await client.CollectionExistsAsync(collectionName);
}
2023-06-18 02:56:22 +00:00
}