-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathsummarize_conversation.ts
392 lines (353 loc) · 13 KB
/
summarize_conversation.ts
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import { composeContext, getModelSettings } from "@elizaos/core";
import { generateText, splitChunks, trimTokens } from "@elizaos/core";
import { getActorDetails } from "@elizaos/core";
import { parseJSONObjectFromText } from "@elizaos/core";
import {
Action,
ActionExample,
Content,
HandlerCallback,
IAgentRuntime,
Media,
Memory,
ModelClass,
State,
} from "@elizaos/core";
export const summarizationTemplate = `# Summarized so far (we are adding to this)
{{currentSummary}}
# Current conversation chunk we are summarizing (includes attachments)
{{memoriesWithAttachments}}
Summarization objective: {{objective}}
# Instructions: Summarize the conversation so far. Return the summary. Do not acknowledge this request, just summarize and continue the existing summary if there is one. Capture any important details to the objective. Only respond with the new summary text.
Your response should be extremely detailed and include any and all relevant information.`;
export const dateRangeTemplate = `# Messages we are summarizing (the conversation is continued after this)
{{recentMessages}}
# Instructions: {{senderName}} is requesting a summary of the conversation. Your goal is to determine their objective, along with the range of dates that their request covers.
The "objective" is a detailed description of what the user wants to summarize based on the conversation. If they just ask for a general summary, you can either base it off the converation if the summary range is very recent, or set the object to be general, like "a detailed summary of the conversation between all users".
The "start" and "end" are the range of dates that the user wants to summarize, relative to the current time. The start and end should be relative to the current time, and measured in seconds, minutes, hours and days. The format is "2 days ago" or "3 hours ago" or "4 minutes ago" or "5 seconds ago", i.e. "<integer> <unit> ago".
If you aren't sure, you can use a default range of "0 minutes ago" to "2 hours ago" or more. Better to err on the side of including too much than too little.
Your response must be formatted as a JSON block with this structure:
\`\`\`json
{
"objective": "<What the user wants to summarize>",
"start": "0 minutes ago",
"end": "2 hours ago"
}
\`\`\`
`;
const getDateRange = async (
runtime: IAgentRuntime,
message: Memory,
state: State
) => {
state = (await runtime.composeState(message)) as State;
const context = composeContext({
state,
template: dateRangeTemplate,
});
for (let i = 0; i < 5; i++) {
const response = await generateText({
runtime,
context,
modelClass: ModelClass.SMALL,
});
console.log("response", response);
// try parsing to a json object
const parsedResponse = parseJSONObjectFromText(response) as {
objective: string;
start: string | number;
end: string | number;
} | null;
// see if it contains objective, start and end
if (parsedResponse) {
if (
parsedResponse.objective &&
parsedResponse.start &&
parsedResponse.end
) {
// TODO: parse start and end into timestamps
const startIntegerString = (
parsedResponse.start as string
).match(/\d+/)?.[0];
const endIntegerString = (parsedResponse.end as string).match(
/\d+/
)?.[0];
// parse multiplier
const multipliers = {
second: 1 * 1000,
minute: 60 * 1000,
hour: 3600 * 1000,
day: 86400 * 1000,
};
const startMultiplier = (parsedResponse.start as string).match(
/second|minute|hour|day/
)?.[0];
const endMultiplier = (parsedResponse.end as string).match(
/second|minute|hour|day/
)?.[0];
const startInteger = startIntegerString
? parseInt(startIntegerString)
: 0;
const endInteger = endIntegerString
? parseInt(endIntegerString)
: 0;
// multiply by multiplier
const startTime =
startInteger *
multipliers[startMultiplier as keyof typeof multipliers];
console.log("startTime", startTime);
const endTime =
endInteger *
multipliers[endMultiplier as keyof typeof multipliers];
console.log("endTime", endTime);
// get the current time and subtract the start and end times
parsedResponse.start = Date.now() - startTime;
parsedResponse.end = Date.now() - endTime;
return parsedResponse;
}
}
}
};
const summarizeAction = {
name: "SUMMARIZE_CONVERSATION",
similes: [
"RECAP",
"RECAP_CONVERSATION",
"SUMMARIZE_CHAT",
"SUMMARIZATION",
"CHAT_SUMMARY",
"CONVERSATION_SUMMARY",
],
description: "Summarizes the conversation and attachments.",
validate: async (
runtime: IAgentRuntime,
message: Memory,
_state: State
) => {
if (message.content.source !== "discord") {
return false;
}
// only show if one of the keywords are in the message
const keywords: string[] = [
"summarize",
"summarization",
"summary",
"recap",
"report",
"overview",
"review",
"rundown",
"wrap-up",
"brief",
"debrief",
"abstract",
"synopsis",
"outline",
"digest",
"abridgment",
"condensation",
"encapsulation",
"essence",
"gist",
"main points",
"key points",
"key takeaways",
"bulletpoint",
"highlights",
"tldr",
"tl;dr",
"in a nutshell",
"bottom line",
"long story short",
"sum up",
"sum it up",
"short version",
"bring me up to speed",
"catch me up",
];
return keywords.some((keyword) =>
message.content.text.toLowerCase().includes(keyword.toLowerCase())
);
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
options: any,
callback: HandlerCallback
) => {
state = (await runtime.composeState(message)) as State;
const callbackData: Content = {
text: "", // fill in later
action: "SUMMARIZATION_RESPONSE",
source: message.content.source,
attachments: [],
};
const { roomId } = message;
// 1. extract date range from the message
const dateRange = await getDateRange(runtime, message, state);
if (!dateRange) {
console.error("Couldn't get date range from message");
return;
}
console.log("dateRange", dateRange);
const { objective, start, end } = dateRange;
// 2. get these memories from the database
const memories = await runtime.messageManager.getMemories({
roomId,
// subtract start from current time
start: parseInt(start as string),
end: parseInt(end as string),
count: 10000,
unique: false,
});
const actors = await getActorDetails({
runtime: runtime as IAgentRuntime,
roomId,
});
const actorMap = new Map(actors.map((actor) => [actor.id, actor]));
const formattedMemories = memories
.map((memory) => {
const attachments = memory.content.attachments
?.map((attachment: Media) => {
return `---\nAttachment: ${attachment.id}\n${attachment.description}\n${attachment.text}\n---`;
})
.join("\n");
return `${actorMap.get(memory.userId)?.name ?? "Unknown User"} (${actorMap.get(memory.userId)?.username ?? ""}): ${memory.content.text}\n${attachments}`;
})
.join("\n");
let currentSummary = "";
const modelSettings = getModelSettings(
runtime.character.modelProvider,
ModelClass.SMALL
);
const chunkSize = modelSettings.maxOutputTokens - 1000;
const chunks = await splitChunks(formattedMemories, chunkSize, 0);
const _datestr = new Date().toUTCString().replace(/:/g, "-");
state.memoriesWithAttachments = formattedMemories;
state.objective = objective;
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
state.currentSummary = currentSummary;
state.currentChunk = chunk;
const template = await trimTokens(
summarizationTemplate,
chunkSize + 500,
runtime
);
const context = composeContext({
state,
// make sure it fits, we can pad the tokens a bit
template,
});
const summary = await generateText({
runtime,
context,
modelClass: ModelClass.SMALL,
});
currentSummary = currentSummary + "\n" + summary;
}
if (!currentSummary) {
console.error("No summary found, that's not good!");
return;
}
callbackData.text = currentSummary.trim();
if (
callbackData.text &&
(currentSummary.trim()?.split("\n").length < 4 ||
currentSummary.trim()?.split(" ").length < 100)
) {
callbackData.text = `Here is the summary:
\`\`\`md
${currentSummary.trim()}
\`\`\`
`;
await callback(callbackData);
} else if (currentSummary.trim()) {
const summaryFilename = `content/conversation_summary_${Date.now()}`;
await runtime.cacheManager.set(summaryFilename, currentSummary);
// save the summary to a file
await callback(
{
...callbackData,
text: `I've attached the summary of the conversation from \`${new Date(parseInt(start as string)).toString()}\` to \`${new Date(parseInt(end as string)).toString()}\` as a text file.`,
},
[summaryFilename]
);
} else {
console.warn(
"Empty response from summarize conversation action, skipping"
);
}
return callbackData;
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "```js\nconst x = 10\n```",
},
},
{
user: "{{user1}}",
content: {
text: "can you give me a detailed report on what we're talking about?",
},
},
{
user: "{{user2}}",
content: {
text: "sure, no problem, give me a minute to get that together for you",
action: "SUMMARIZE",
},
},
],
[
{
user: "{{user1}}",
content: {
text: "please summarize the conversation we just had and include this blogpost i'm linking (Attachment: b3e12)",
},
},
{
user: "{{user2}}",
content: {
text: "sure, give me a sec",
action: "SUMMARIZE",
},
},
],
[
{
user: "{{user1}}",
content: {
text: "Can you summarize what moon and avf are talking about?",
},
},
{
user: "{{user2}}",
content: {
text: "Yeah, just hold on a second while I get that together for you...",
action: "SUMMARIZE",
},
},
],
[
{
user: "{{user1}}",
content: {
text: "i need to write a blog post about farming, can you summarize the discussion from a few hours ago?",
},
},
{
user: "{{user2}}",
content: {
text: "no problem, give me a few minutes to read through everything",
action: "SUMMARIZE",
},
},
],
] as ActionExample[][],
} as Action;
export default summarizeAction;