2024-09-03 17:52:33 +00:00
|
|
|
using BotSharp.Abstraction.VectorStorage.Helpers;
|
|
|
|
|
|
2024-07-17 21:03:46 +00:00
|
|
|
namespace BotSharp.Plugin.KnowledgeBase.Functions;
|
|
|
|
|
|
|
|
|
|
public class KnowledgeRetrievalFn : IFunctionCallback
|
|
|
|
|
{
|
|
|
|
|
public string Name => "knowledge_retrieval";
|
|
|
|
|
|
2024-09-03 17:52:33 +00:00
|
|
|
public string Indication => "searching my brain";
|
|
|
|
|
|
2024-07-17 21:03:46 +00:00
|
|
|
private readonly IServiceProvider _services;
|
|
|
|
|
private readonly KnowledgeBaseSettings _settings;
|
|
|
|
|
|
|
|
|
|
public KnowledgeRetrievalFn(IServiceProvider services, KnowledgeBaseSettings settings)
|
|
|
|
|
{
|
|
|
|
|
_services = services;
|
|
|
|
|
_settings = settings;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> Execute(RoleDialogModel message)
|
|
|
|
|
{
|
|
|
|
|
var args = JsonSerializer.Deserialize<ExtractedKnowledge>(message.FunctionArgs ?? "{}");
|
|
|
|
|
|
2024-08-22 20:23:22 +00:00
|
|
|
var collectionName = _settings.Default.CollectionName ?? KnowledgeCollectionName.BotSharp;
|
2024-09-03 17:52:33 +00:00
|
|
|
var knowledgeService = _services.GetRequiredService<IKnowledgeService>();
|
|
|
|
|
var knowledges = await knowledgeService.SearchVectorKnowledge(args.Question, collectionName, new VectorSearchOptions
|
|
|
|
|
{
|
|
|
|
|
Fields = new List<string> { KnowledgePayloadName.Text, KnowledgePayloadName.Answer },
|
|
|
|
|
Confidence = 0.2f
|
|
|
|
|
});
|
2024-07-17 21:03:46 +00:00
|
|
|
|
2024-08-09 21:03:29 +00:00
|
|
|
if (!knowledges.IsNullOrEmpty())
|
2024-07-25 22:11:51 +00:00
|
|
|
{
|
2024-09-03 17:52:33 +00:00
|
|
|
var answers = knowledges.Select(x => x.ToQuestionAnswer()).ToList();
|
2024-08-09 21:43:16 +00:00
|
|
|
message.Content = string.Join("\r\n\r\n=====\r\n", answers);
|
2024-07-25 22:11:51 +00:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
message.Content = $"I didn't find any useful knowledge related to [{args.Question}]. \r\nCan you tell me the instruction and I'll memorize it.";
|
|
|
|
|
message.StopCompletion = true;
|
|
|
|
|
}
|
2024-07-17 21:03:46 +00:00
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|