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-09 21:03:29 +00:00
|
|
|
public async Task<StringIdPagedItems<KnowledgeCollectionData>> GetKnowledgeCollectionData(string collectionName, KnowledgeFilter filter)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var db = GetVectorDb();
|
|
|
|
|
return await db.GetCollectionData(collectionName, filter);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning($"Error when getting knowledge collection data ({collectionName}). {ex.Message}\r\n{ex.InnerException}");
|
|
|
|
|
return new StringIdPagedItems<KnowledgeCollectionData>();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-09 22:39:54 +00:00
|
|
|
public async Task<IEnumerable<KnowledgeRetrievalResult>> SearchKnowledge(string collectionName, KnowledgeRetrievalOptions 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();
|
|
|
|
|
var fields = !options.Fields.IsNullOrEmpty() ? options.Fields : new List<string> { KnowledgePayloadName.Text, KnowledgePayloadName.Answer };
|
|
|
|
|
var found = await db.Search(collectionName, vector, fields, limit: options.Limit ?? 5, confidence: options.Confidence ?? 0.5f, withVector: options.WithVector);
|
2024-08-09 21:03:29 +00:00
|
|
|
|
2024-08-13 18:30:06 +00:00
|
|
|
var results = found.Select(x => new KnowledgeRetrievalResult
|
|
|
|
|
{
|
|
|
|
|
Data = x.Data,
|
|
|
|
|
Score = x.Score,
|
|
|
|
|
Vector = x.Vector
|
|
|
|
|
}).ToList();
|
|
|
|
|
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}");
|
|
|
|
|
return new List<KnowledgeRetrievalResult>();
|
|
|
|
|
}
|
2024-08-09 21:03:29 +00:00
|
|
|
}
|
|
|
|
|
}
|