BotSharp/src/Platforms/BotSharp.Platform.LlamaSharp/Handlers/ChatCompletionHandler.cs

54 lines
1.5 KiB
C#
Raw Normal View History

2023-05-27 01:58:31 +00:00
using BotSharp.Abstraction;
2023-05-28 16:30:27 +00:00
using BotSharp.Abstraction.Models;
2023-05-27 01:58:31 +00:00
using BotSharp.Platform.LlamaSharp;
using LLama;
using System;
2023-05-28 16:30:27 +00:00
using System.Collections.Generic;
2023-05-27 01:58:31 +00:00
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace BotSharp.Platform.Local.Handlers;
public class ChatCompletionHandler : IChatCompletionHandler
{
private readonly IChatModel _model;
private readonly LlamaSharpSettings _settings;
public ChatCompletionHandler(LlamaSharpSettings settings)
{
_settings = settings;
_model = new LLamaModel(new LLamaParams(model: _settings.ModelPath,
n_ctx: 512,
interactive: true,
repeat_penalty: 1.0f,
verbose_prompt: false));
if (!string.IsNullOrEmpty(settings.InstructionFile))
{
var prompt = File.ReadAllText(settings.InstructionFile);
_model.InitChatPrompt(prompt, "UTF-8");
}
_model.InitChatAntiprompt(new string[] { "User:" });
}
2023-05-28 16:30:27 +00:00
public async Task GetChatCompletionsAsync(string text,
Func<string> GetInstruction,
Func<List<RoleDialogModel>> GetChatHistory,
Func<string, Task> onChunkReceived,
Func<Task> onChunkCompleted)
2023-05-27 01:58:31 +00:00
{
string totalResponse = "";
foreach (var response in _model.Chat(text, "", "UTF-8"))
{
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();
await onChunkCompleted();
2023-05-27 01:58:31 +00:00
}
}