-
Notifications
You must be signed in to change notification settings - Fork 4
/
LongTermChatMemory.cs
240 lines (213 loc) · 7.7 KB
/
LongTermChatMemory.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#nullable enable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Mochineko.ChatGPT_API;
using Mochineko.LLMAgent.Summarization;
using Mochineko.Relent.Result;
using TiktokenSharp;
using UnityEngine;
namespace Mochineko.LLMAgent.Memory
{
public sealed class LongTermChatMemory : IChatMemory
{
private readonly int maxShortTermMemoriesTokenLength;
private readonly int maxBufferMemoriesTokenLength;
private readonly TikToken tikToken;
private readonly List<Message> prompts = new();
internal IEnumerable<Message> Prompts => prompts.ToArray();
private readonly Queue<Message> shortTermMemories = new();
internal IEnumerable<Message> ShortTermMemories => shortTermMemories.ToArray();
private readonly Queue<Message> bufferMemories = new();
internal IEnumerable<Message> BufferMemories => bufferMemories.ToArray();
private readonly Summarizer summarizer;
private readonly IChatMemoryStore store;
private Message summary;
internal Message Summary => summary;
private readonly object lockObject = new();
public static async UniTask<LongTermChatMemory> InstantiateAsync(
int maxShortTermMemoriesTokenLength,
int maxBufferMemoriesTokenLength,
string apiKey,
Model model,
IChatMemoryStore? store,
CancellationToken cancellationToken)
{
var instance = new LongTermChatMemory(
maxShortTermMemoriesTokenLength,
maxBufferMemoriesTokenLength,
apiKey,
model,
store);
var result = await instance.store.LoadAsync(cancellationToken);
if (result is ISuccessResult<string> success)
{
Debug.Log($"[LLMAgent.Memory] Succeeded to load chat memory from store:{success.Result}");
instance.summary = new Message(Role.System, success.Result);
}
else if (result is IFailureResult<string> failure)
{
Debug.LogError(
$"[LLMAgent.Memory] Failed to load chat memory from store because -> {failure.Message}");
}
else
{
throw new ResultPatternMatchException(nameof(result));
}
return instance;
}
private LongTermChatMemory(
int maxShortTermMemoriesTokenLength,
int maxBufferMemoriesTokenLength,
string apiKey,
Model model,
IChatMemoryStore? store)
{
this.maxShortTermMemoriesTokenLength = maxShortTermMemoriesTokenLength;
this.maxBufferMemoriesTokenLength = maxBufferMemoriesTokenLength;
this.tikToken = TikToken.EncodingForModel(model.ToText());
this.summarizer = new Summarizer(apiKey, model);
this.store = store ?? new NullChatMemoryStore();
this.summary = new Message(Role.System, string.Empty);
}
public IReadOnlyList<Message> Messages
=> prompts
.Concat(new[] { summary })
.Concat(shortTermMemories)
.ToList();
public IReadOnlyList<Message> Conversations
=> new[] { summary }
.Concat(shortTermMemories)
.Concat(bufferMemories)
.ToList();
public int ShortTermMemoriesTokenLength
=> shortTermMemories.TokenLength(tikToken);
public int BufferMemoriesTokenLength
=> bufferMemories.TokenLength(tikToken);
public int SummaryTokenLength
=> summary.TokenLength(tikToken);
public int PromptsTokenLength
=> prompts.TokenLength(tikToken);
public int TotalMemoriesTokenLength
=> PromptsTokenLength
+ SummaryTokenLength
+ ShortTermMemoriesTokenLength;
public async Task AddMessageAsync(Message message, CancellationToken cancellationToken)
{
if (message.Role is Role.System)
{
lock (lockObject)
{
prompts.Add(message);
}
}
else if (message.Role is Role.User)
{
lock (lockObject)
{
shortTermMemories.Enqueue(message);
}
}
else if (message.Role is Role.Assistant)
{
lock (lockObject)
{
shortTermMemories.Enqueue(message);
}
while (ShortTermMemoriesTokenLength > maxShortTermMemoriesTokenLength)
{
bool tryDequeue;
Message? dequeued;
lock (lockObject)
{
tryDequeue = shortTermMemories.TryDequeue(out dequeued);
}
if (tryDequeue)
{
lock (lockObject)
{
bufferMemories.Enqueue(dequeued);
}
if (BufferMemoriesTokenLength > maxBufferMemoriesTokenLength)
{
await SummarizeAsync(cancellationToken);
}
}
}
}
Debug.Log(
$"[LLMAgent.Chat] Update memory by adding {message}, short term:{ShortTermMemoriesTokenLength}, buffer:{BufferMemoriesTokenLength}, summary:{SummaryTokenLength}/{summary.Content}.");
}
private async UniTask SummarizeAsync(CancellationToken cancellationToken)
{
List<Message> buffers;
lock (lockObject)
{
buffers = bufferMemories.ToList();
}
var summarizeResult = await summarizer.SummarizeAsync(
buffers,
cancellationToken);
if (summarizeResult is ISuccessResult<string> summarizeSuccess)
{
Debug.Log(
$"[LLMAgent.Summarization] Succeeded to summarize long term memory:{summarizeSuccess.Result}");
lock (lockObject)
{
summary = new Message(
Role.System,
summarizeSuccess.Result);
}
}
else
{
Debug.LogError(
$"[LLMAgent.Summarization] Failed to summarize long term memory then keep summary and forget buffers:{summary.Content}");
}
lock (lockObject)
{
bufferMemories.Clear();
}
}
public void ClearAllMessages()
{
lock (lockObject)
{
prompts.Clear();
shortTermMemories.Clear();
bufferMemories.Clear();
summary = new Message(Role.System, "");
}
}
public void ClearPrompts()
{
lock (lockObject)
{
prompts.Clear();
}
}
public void ClearShortTermMemory()
{
lock (lockObject)
{
shortTermMemories.Clear();
}
}
public void ClearBufferMemory()
{
lock (lockObject)
{
bufferMemories.Clear();
}
}
public void ClearSummary()
{
lock (lockObject)
{
summary = new Message(Role.System, "");
}
}
}
}