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

494 lines
16 KiB
C#
Raw Normal View History

2025-03-12 21:33:20 +00:00
using BotSharp.Abstraction.Options;
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;
2025-03-12 21:33:20 +00:00
using BotSharp.Plugin.Qdrant.Models;
using Microsoft.Extensions.DependencyInjection;
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;
2025-03-12 21:33:20 +00:00
using System.Net.Http;
using System.Net.Mime;
using System.Text.Json;
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;
2025-03-12 21:33:20 +00:00
private readonly BotSharpOptions _options;
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,
2025-03-12 21:33:20 +00:00
BotSharpOptions options,
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;
2025-03-12 21:33:20 +00:00
_options = options;
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
}
2025-03-12 21:33:20 +00:00
#region Collection
2024-09-24 20:34:47 +00:00
public async Task<bool> DoesCollectionExist(string collectionName)
2024-08-29 19:30:47 +00:00
{
var client = GetClient();
2024-09-24 20:34:47 +00:00
return await client.CollectionExistsAsync(collectionName);
}
public async Task<bool> CreateCollection(string collectionName, int dimension)
{
var exist = await DoesCollectionExist(collectionName);
2024-08-29 19:30:47 +00:00
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
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-09-10 19:02:25 +00:00
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)
{
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-08-29 19:30:47 +00:00
if (!exist) return false;
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-08-29 19:30:47 +00:00
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
}
2025-03-12 21:33:20 +00:00
#endregion
2023-06-18 02:56:22 +00:00
2025-03-12 21:33:20 +00:00
#region Collection data
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
{
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(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-09-24 20:34:47 +00:00
var client = GetClient();
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,
Data = x.Payload.ToDictionary(p => p.Key, p => p.Value.KindCase switch
{
Value.KindOneofCase.StringValue => p.Value.StringValue,
Value.KindOneofCase.BoolValue => p.Value.BoolValue,
Value.KindOneofCase.IntegerValue => p.Value.IntegerValue,
_ => new object()
}),
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)
{
2024-09-24 20:34:47 +00:00
if (ids.IsNullOrEmpty())
{
return Enumerable.Empty<VectorCollectionData>();
}
var exist = await DoesCollectionExist(collectionName);
2024-08-23 16:25:44 +00:00
if (!exist)
{
return Enumerable.Empty<VectorCollectionData>();
}
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-08-23 16:25:44 +00:00
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(p => p.Key, p => p.Value.KindCase switch
{
Value.KindOneofCase.StringValue => p.Value.StringValue,
Value.KindOneofCase.BoolValue => p.Value.BoolValue,
Value.KindOneofCase.IntegerValue => p.Value.IntegerValue,
_ => new object()
}) ?? new(),
2024-08-23 16:25:44 +00:00
Vector = x.Vectors?.Vector?.Data?.ToArray()
});
}
public async Task<bool> Upsert(string collectionName, Guid id, float[] vector, string text, Dictionary<string, object>? 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)
{
2024-10-07 18:10:48 +00:00
var value = item.Value?.ToString();
if (value == null) continue;
if (bool.TryParse(value, out var b))
{
point.Payload[item.Key] = b;
}
2024-10-07 18:10:48 +00:00
else if (byte.TryParse(value, out var int8))
{
point.Payload[item.Key] = int8;
}
2024-10-07 18:10:48 +00:00
else if (short.TryParse(value, out var int16))
{
point.Payload[item.Key] = int16;
}
2024-10-07 18:10:48 +00:00
else if (int.TryParse(value, out var int32))
{
point.Payload[item.Key] = int32;
}
2024-10-07 18:10:48 +00:00
else if (long.TryParse(value, out var int64))
{
point.Payload[item.Key] = int64;
}
2024-10-07 18:10:48 +00:00
else if (float.TryParse(value, out var f32))
{
point.Payload[item.Key] = f32;
}
2024-10-07 18:10:48 +00:00
else if (double.TryParse(value, out var f64))
{
point.Payload[item.Key] = f64;
}
2024-10-07 18:10:48 +00:00
else if (DateTime.TryParse(value, out var dt))
{
point.Payload[item.Key] = dt.ToUniversalTime().ToString("o");
}
2024-10-07 18:10:48 +00:00
else
{
point.Payload[item.Key] = value;
}
2024-07-17 21:03:46 +00:00
}
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-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-08-13 18:26:57 +00:00
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() } };
}
2024-09-24 20:34:47 +00:00
var client = GetClient();
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(p => p.Key, p => p.Value.KindCase switch
{
Value.KindOneofCase.StringValue => p.Value.StringValue,
Value.KindOneofCase.BoolValue => p.Value.BoolValue,
Value.KindOneofCase.IntegerValue => p.Value.IntegerValue,
_ => new object()
}),
2024-08-28 22:45:33 +00:00
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-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-09-18 21:17:54 +00:00
if (!exist)
{
return false;
}
2024-09-24 20:34:47 +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;
}
2024-09-18 21:17:54 +00:00
public async Task<bool> DeleteCollectionAllData(string collectionName)
{
2024-09-24 20:34:47 +00:00
var exist = await DoesCollectionExist(collectionName);
2024-09-18 21:17:54 +00:00
if (!exist)
{
return false;
}
2024-09-24 20:34:47 +00:00
var client = GetClient();
2024-09-18 21:17:54 +00:00
var result = await client.DeleteAsync(collectionName, new Filter());
return result.Status == UpdateStatus.Completed;
}
2025-03-12 21:33:20 +00:00
#endregion
#region Snapshots
public async Task<IEnumerable<VectorCollectionSnapshot>> GetCollectionSnapshots(string collectionName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return Enumerable.Empty<VectorCollectionSnapshot>();
}
var client = GetClient();
var data = await client.ListSnapshotsAsync(collectionName);
var snapshots = data.Select(x => new VectorCollectionSnapshot
{
Name = x.Name,
Size = x.Size,
CreatedTime = x.CreationTime.ToDateTime(),
CheckSum = x.Checksum
});
return snapshots;
}
public async Task<VectorCollectionSnapshot?> CreateCollectionShapshot(string collectionName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return null;
}
var client = GetClient();
var desc = await client.CreateSnapshotAsync(collectionName);
if (desc == null)
{
return null;
}
return new VectorCollectionSnapshot
{
Name = desc.Name,
Size = desc.Size,
CreatedTime = desc.CreationTime.ToDateTime(),
CheckSum = desc.Checksum
};
}
public async Task<BinaryData> DownloadCollectionSnapshot(string collectionName, string snapshotFileName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return BinaryData.Empty;
}
var domain = $"https://{_setting.Url}:6333";
var url = $"{domain}/collections/{collectionName}/snapshots/{snapshotFileName}";
var http = _services.GetRequiredService<IHttpClientFactory>();
using (var client = http.CreateClient())
{
try
{
var uri = new Uri(url);
var message = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = uri
};
client.DefaultRequestHeaders.Add("api-key", _setting.ApiKey);
var rawResponse = await client.SendAsync(message);
rawResponse.EnsureSuccessStatusCode();
using var contentStream = await rawResponse.Content.ReadAsStreamAsync();
return BinaryData.FromStream(contentStream);
}
catch (Exception ex)
{
_logger.LogError($"Error when downloading Qdrant snapshot (Endpoint: {url}, Snapshot: {snapshotFileName}). {ex.Message}\r\n{ex.InnerException}");
return BinaryData.Empty;
}
}
}
public async Task<bool> RecoverCollectionFromShapshot(string collectionName, string snapshotFileName, BinaryData snapshotData)
{
var domain = $"https://{_setting.Url}:6333";
var url = $"{domain}/collections/{collectionName}/snapshots/upload";
var http = _services.GetRequiredService<IHttpClientFactory>();
using (var client = http.CreateClient())
{
try
{
var uri = new Uri(url);
var data = new MultipartFormDataContent
{
{ new StringContent(snapshotFileName), "name" },
{ new StringContent(MediaTypeNames.Application.Octet), "type" },
{ new StreamContent(snapshotData.ToStream()), "snapshot", snapshotFileName }
};
var message = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri,
Content = data
};
client.DefaultRequestHeaders.Add("api-key", _setting.ApiKey);
var rawResponse = await client.SendAsync(message);
rawResponse.EnsureSuccessStatusCode();
var responseStr = await rawResponse.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<RecoverFromSnapshotResponse>(responseStr, _options.JsonSerializerOptions);
return response?.Result == true;
}
catch (Exception ex)
{
_logger.LogError($"Error when uploading Qdrant snapshot (Endpoint: {url}, Snapshot: {snapshotFileName}). {ex.Message}\r\n{ex.InnerException}");
return false;
}
}
}
public async Task<bool> DeleteCollectionShapshot(string collectionName, string snapshotName)
{
var exist = await DoesCollectionExist(collectionName);
if (!exist)
{
return false;
}
try
{
var client = GetClient();
await client.DeleteSnapshotAsync(collectionName, snapshotName);
return true;
}
catch
{
return false;
}
}
#endregion
2023-06-18 02:56:22 +00:00
}