-
Notifications
You must be signed in to change notification settings - Fork 414
/
Copy pathStatelessChatService.cs
56 lines (47 loc) · 1.72 KB
/
StatelessChatService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using LLama.Common;
using Microsoft.AspNetCore.Http;
using System.Text;
using static LLama.LLamaTransforms;
namespace LLama.WebAPI.Services
{
public class StatelessChatService
{
private readonly LLamaContext _context;
private readonly ChatSession _session;
public StatelessChatService(IConfiguration configuration)
{
var @params = new Common.ModelParams(configuration["ModelPath"]!)
{
ContextSize = 512,
};
// todo: share weights from a central service
using var weights = LLamaWeights.LoadFromFile(@params);
_context = new LLamaContext(weights, @params);
// TODO: replace with a stateless executor
_session = new ChatSession(new InteractiveExecutor(_context))
.WithOutputTransform(new LLamaTransforms.KeywordTextOutputStreamTransform(new string[] { "User:", "Assistant:" }, redundancyLength: 8))
.WithHistoryTransform(new HistoryTransform());
}
public async Task<string> SendAsync(ChatHistory history)
{
var result = _session.ChatAsync(history, new InferenceParams()
{
AntiPrompts = new string[] { "User:" },
});
var sb = new StringBuilder();
await foreach (var r in result)
{
Console.Write(r);
sb.Append(r);
}
return sb.ToString();
}
}
public class HistoryTransform : DefaultHistoryTransform
{
public override string HistoryToText(IChatHistory history)
{
return base.HistoryToText(history) + "\n Assistant:";
}
}
}