2023-06-17 02:42:35 +00:00
|
|
|
using BotSharp.Abstraction.Knowledges;
|
|
|
|
|
using BotSharp.Abstraction.Knowledges.Models;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Collections;
|
|
|
|
|
using BotSharp.Abstraction.MLTasks;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Core.Knowledges.Services;
|
|
|
|
|
|
|
|
|
|
public class KnowledgeService : IKnowledgeService
|
|
|
|
|
{
|
|
|
|
|
private readonly ITextEmbedding _textEmbedding;
|
|
|
|
|
private readonly ITextCompletion _textCompletion;
|
2023-06-18 02:56:22 +00:00
|
|
|
private readonly IVectorDb _db;
|
2023-06-17 02:42:35 +00:00
|
|
|
string collectionName = "my_collection";
|
2023-06-18 02:56:22 +00:00
|
|
|
public KnowledgeService(ITextEmbedding textEmbedding,
|
|
|
|
|
ITextCompletion textCompletion,
|
|
|
|
|
IVectorDb db)
|
2023-06-17 02:42:35 +00:00
|
|
|
{
|
|
|
|
|
_textEmbedding = textEmbedding;
|
|
|
|
|
_textCompletion = textCompletion;
|
2023-06-18 02:56:22 +00:00
|
|
|
_db = db;
|
2023-06-17 02:42:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task Feed(KnowledgeFeedModel knowledge)
|
|
|
|
|
{
|
|
|
|
|
var idStart = 0;
|
|
|
|
|
var lines = knowledge.Content.Split(". ");
|
|
|
|
|
lines = lines.Select((x, i) => $"{i+1} {x}").ToArray();
|
|
|
|
|
File.WriteAllLines(collectionName + ".txt", lines);
|
|
|
|
|
|
|
|
|
|
foreach (var line in lines)
|
|
|
|
|
{
|
|
|
|
|
idStart++;
|
2023-06-18 02:56:22 +00:00
|
|
|
await _db.Upsert(collectionName, idStart, _textEmbedding.GetVector(line));
|
2023-06-17 02:42:35 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<string> GetAnswer(string question)
|
|
|
|
|
{
|
|
|
|
|
var vector = _textEmbedding.GetVector(question);
|
|
|
|
|
|
|
|
|
|
// Vector search
|
2023-06-18 02:56:22 +00:00
|
|
|
var result = await _db.Search(collectionName, vector);
|
2023-06-17 02:42:35 +00:00
|
|
|
|
|
|
|
|
var prompt = "";
|
|
|
|
|
var lines = File.ReadAllLines(collectionName + ".txt");
|
2023-06-18 02:56:22 +00:00
|
|
|
foreach (var r in result)
|
2023-06-17 02:42:35 +00:00
|
|
|
{
|
2023-06-18 02:56:22 +00:00
|
|
|
prompt += lines[r - 1] + "\n";
|
2023-06-17 02:42:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
prompt += "###\r\n";
|
|
|
|
|
prompt += "Answer the user's question based on the content provided above, and your reply should be as concise and organized as possible.\r\n";
|
|
|
|
|
prompt += "Q: how to turn on Hood Light? \r\nA: Press the Hood Light keypad to turn the light beneath the hood on or off.\r\n";
|
|
|
|
|
prompt += $"Q: {question}\r\nA: ";
|
|
|
|
|
|
|
|
|
|
var completion = await _textCompletion.GetCompletion(prompt);
|
|
|
|
|
return completion;
|
|
|
|
|
}
|
|
|
|
|
}
|