2023-06-27 18:31:13 +00:00
|
|
|
using BotSharp.Abstraction.Agents.Models;
|
|
|
|
|
using BotSharp.Abstraction.Conversations.Models;
|
|
|
|
|
using BotSharp.Abstraction.MLTasks;
|
2023-05-27 01:58:31 +00:00
|
|
|
using LLama;
|
|
|
|
|
using System.IO;
|
|
|
|
|
|
2023-06-26 23:08:24 +00:00
|
|
|
namespace BotSharp.Core.Plugins.LLamaSharp;
|
2023-05-27 01:58:31 +00:00
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public class ChatCompletionProvider : IChatCompletion
|
2023-05-27 01:58:31 +00:00
|
|
|
{
|
2023-06-27 19:17:53 +00:00
|
|
|
private IChatModel _model;
|
2023-05-27 01:58:31 +00:00
|
|
|
|
|
|
|
|
|
2023-06-27 19:17:53 +00:00
|
|
|
public ChatCompletionProvider(LlamaAiModel model)
|
|
|
|
|
{
|
|
|
|
|
model.LoadModel();
|
|
|
|
|
_model = model.Model;
|
|
|
|
|
// _model.InitChatPrompt(prompt, "UTF-8");
|
|
|
|
|
// _model.InitChatAntiprompt(new string[] { "user:" });
|
2023-05-27 01:58:31 +00:00
|
|
|
}
|
|
|
|
|
|
2023-05-29 01:06:05 +00:00
|
|
|
public async Task GetChatCompletionsAsync(List<RoleDialogModel> conversations,
|
|
|
|
|
Func<string, Task> onChunkReceived)
|
2023-05-27 01:58:31 +00:00
|
|
|
{
|
|
|
|
|
string totalResponse = "";
|
2023-06-23 04:43:00 +00:00
|
|
|
var content = string.Join("\n ", conversations.Select(x => $"{x.Role}: {x.Text.Replace("user:", "")}")).Trim();
|
2023-06-03 17:01:50 +00:00
|
|
|
content += "\n assistant: ";
|
2023-06-27 19:17:53 +00:00
|
|
|
foreach (var response in _model.Chat(content, "", "UTF-8"))
|
2023-05-27 01:58:31 +00:00
|
|
|
{
|
2023-05-28 16:30:27 +00:00
|
|
|
Console.Write(response);
|
2023-05-27 01:58:31 +00:00
|
|
|
totalResponse += response;
|
2023-05-28 16:30:27 +00:00
|
|
|
await onChunkReceived(response);
|
2023-05-27 01:58:31 +00:00
|
|
|
}
|
2023-05-28 16:30:27 +00:00
|
|
|
|
|
|
|
|
Console.WriteLine();
|
2023-05-29 01:06:05 +00:00
|
|
|
}
|
|
|
|
|
|
2023-06-27 18:31:13 +00:00
|
|
|
public Task<string> GetChatCompletionsAsync(Agent agent, List<RoleDialogModel> conversations)
|
|
|
|
|
{
|
|
|
|
|
string totalResponse = "";
|
2023-06-27 19:17:53 +00:00
|
|
|
var content = string.Join("\n", conversations.Select(x => $"{x.Role}: {x.Text.Replace("user:", "")}")).Trim();
|
|
|
|
|
content += "\nassistant: ";
|
|
|
|
|
foreach (var response in _model.Chat(content, agent.Instruction, "UTF-8"))
|
2023-05-29 01:06:05 +00:00
|
|
|
{
|
2023-06-27 19:17:53 +00:00
|
|
|
if (response == "\n")
|
2023-05-29 01:06:05 +00:00
|
|
|
{
|
2023-06-27 19:17:53 +00:00
|
|
|
break;
|
2023-05-29 01:06:05 +00:00
|
|
|
}
|
2023-06-27 19:17:53 +00:00
|
|
|
Console.Write(response);
|
|
|
|
|
totalResponse += response;
|
2023-05-29 01:06:05 +00:00
|
|
|
}
|
|
|
|
|
|
2023-06-27 19:17:53 +00:00
|
|
|
return Task.FromResult(totalResponse.Trim());
|
2023-05-27 01:58:31 +00:00
|
|
|
}
|
|
|
|
|
}
|