2024-08-09 21:03:29 +00:00
|
|
|
namespace BotSharp.Plugin.KnowledgeBase.Services;
|
|
|
|
|
|
|
|
|
|
public partial class KnowledgeService
|
|
|
|
|
{
|
2024-08-13 18:26:57 +00:00
|
|
|
public async Task<IEnumerable<string>> GetKnowledgeCollections()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var db = GetVectorDb();
|
|
|
|
|
return await db.GetCollections();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning($"Error when getting knowledge collections. {ex.Message}\r\n{ex.InnerException}");
|
|
|
|
|
return Enumerable.Empty<string>();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-15 03:46:01 +00:00
|
|
|
public async Task<StringIdPagedItems<KnowledgeSearchResult>> GetKnowledgeCollectionData(string collectionName, KnowledgeFilter filter)
|
2024-08-09 21:03:29 +00:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var db = GetVectorDb();
|
2024-08-15 03:46:01 +00:00
|
|
|
var pagedResult = await db.GetCollectionData(collectionName, filter);
|
|
|
|
|
return new StringIdPagedItems<KnowledgeSearchResult>
|
|
|
|
|
{
|
|
|
|
|
Count = pagedResult.Count,
|
|
|
|
|
Items = pagedResult.Items.Select(x => KnowledgeSearchResult.CopyFrom(x)),
|
|
|
|
|
NextId = pagedResult.NextId,
|
|
|
|
|
};
|
2024-08-09 21:03:29 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning($"Error when getting knowledge collection data ({collectionName}). {ex.Message}\r\n{ex.InnerException}");
|
2024-08-15 03:46:01 +00:00
|
|
|
return new StringIdPagedItems<KnowledgeSearchResult>();
|
2024-08-09 21:03:29 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-15 03:46:01 +00:00
|
|
|
public async Task<IEnumerable<KnowledgeSearchResult>> SearchKnowledge(string collectionName, KnowledgeSearchOptions options)
|
2024-08-09 21:03:29 +00:00
|
|
|
{
|
2024-08-13 18:30:06 +00:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var textEmbedding = GetTextEmbedding();
|
|
|
|
|
var vector = await textEmbedding.GetVectorAsync(options.Text);
|
2024-08-09 21:03:29 +00:00
|
|
|
|
2024-08-13 18:30:06 +00:00
|
|
|
// Vector search
|
|
|
|
|
var db = GetVectorDb();
|
2024-08-15 03:46:01 +00:00
|
|
|
var found = await db.Search(collectionName, vector, options.Fields, limit: options.Limit ?? 5, confidence: options.Confidence ?? 0.5f, withVector: options.WithVector);
|
2024-08-09 21:03:29 +00:00
|
|
|
|
2024-08-15 03:46:01 +00:00
|
|
|
var results = found.Select(x => KnowledgeSearchResult.CopyFrom(x)).ToList();
|
2024-08-13 18:30:06 +00:00
|
|
|
return results;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
2024-08-09 21:03:29 +00:00
|
|
|
{
|
2024-08-13 18:30:06 +00:00
|
|
|
_logger.LogWarning($"Error when searching knowledge ({collectionName}). {ex.Message}\r\n{ex.InnerException}");
|
2024-08-15 03:46:01 +00:00
|
|
|
return new List<KnowledgeSearchResult>();
|
2024-08-13 18:30:06 +00:00
|
|
|
}
|
2024-08-09 21:03:29 +00:00
|
|
|
}
|
|
|
|
|
}
|