-
Notifications
You must be signed in to change notification settings - Fork 5
/
memory_example.ts
260 lines (231 loc) · 8.68 KB
/
memory_example.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
import { v4 as uuidv4 } from "uuid";
import { CreateUserRequest, Message, NotFoundError } from "../../src/api";
import { ZepClient } from "../../src";
// @ts-ignore
import { history } from "./chat_shoe_store_history";
function sleep(ms: number) {
const date = Date.now();
let currentDate = 0;
do {
currentDate = Date.now();
} while (currentDate - date < ms);
}
async function main() {
const projectApiKey = process.env.ZEP_API_KEY;
const client = new ZepClient({
apiKey: projectApiKey,
});
// Create a user
const userId = uuidv4();
const userRequest: CreateUserRequest = {
userId: `amy${userId}`,
metadata: { role: "admin" },
email: "amy@acme.com",
firstName: "Amy",
lastName: "Wu",
};
const user = await client.user.add(userRequest);
console.debug("Created user ", user);
// Example session ID
const sessionID = uuidv4();
// Add session associated with the above user
try {
await client.memory.addSession({
sessionId: sessionID,
metadata: { foo: "bar" },
userId: user.userId,
});
console.debug("Adding new session ", sessionID);
} catch (error) {
console.debug("Got error:", error);
}
// Get session
try {
const session = await client.memory.getSession(sessionID);
console.debug("Retrieved session ", session);
} catch (error) {
console.debug("Got error:", error);
}
// Add memory. We could do this in a batch, but we'll do it one by one rather to
// ensure that summaries and other artifacts are generated correctly.
try {
for (const { role, role_type, content } of history) {
await client.memory.add(sessionID, {
messages: [{ role, roleType: role_type, content }],
});
}
console.debug("Added new memory for session ", sessionID);
} catch (error) {
console.debug("Got error:", error);
}
try {
// Synthesize a question from most recent messages.
// Useful for RAG apps.
// This is faster than using an LLM chain.
console.debug("\n---Synthesize a question from most recent messages");
const { question } = await client.memory.synthesizeQuestion(sessionID, { lastNMessages: 3 });
console.debug(`Question: ${question}`);
} catch (error) {
console.debug("Got error:", error);
}
try {
// Classify the session.
// Useful for semantic routing, filtering, and many other use cases.
console.debug("\n---Classify the session");
const classes = ["low spender <$50", "medium spender >=$50, <$100", "high spender >=$100", "unknown"];
const classification = await client.memory.classifySession(sessionID, {
name: "spender_category",
classes,
persist: true,
});
console.debug(`${classification.class} Classification Result: ${classification.name}`);
} catch (error) {
console.debug("Got error:", error);
}
console.log("Sleeping for 5 seconds to let background tasks complete...");
sleep(5000); // Sleep for 5 seconds
console.log("Done sleeping!");
// Get newly added memory
try {
console.debug("Getting memory for newly added memory with sessionid ", sessionID);
const memory = await client.memory.get(sessionID);
console.log("Memory: ", JSON.stringify(memory));
if (memory?.messages) {
memory.messages.forEach((message) => {
console.debug(JSON.stringify(message));
});
}
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
// get session messages
let sessionMessages: Message[] = [];
try {
const sessionMessagesResult = await client.memory.getSessionMessages(sessionID, { limit: 10, cursor: 1 });
console.debug("Session messages: ", JSON.stringify(sessionMessagesResult));
if (sessionMessagesResult?.messages) {
sessionMessages = sessionMessagesResult.messages;
}
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
const firstSessionsMessageId = sessionMessages[0].uuid;
// Update session message metadata
try {
const metadata = { metadata: { foo: "bar" } };
if (firstSessionsMessageId) {
const updatedMessage = await client.memory.updateMessageMetadata(sessionID, firstSessionsMessageId, {
metadata: metadata,
});
console.debug("Updated message: ", JSON.stringify(updatedMessage));
}
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
// Get session message
try {
if (firstSessionsMessageId) {
const message = await client.memory.getSessionMessage(sessionID, firstSessionsMessageId);
console.debug("Session message: ", JSON.stringify(message));
}
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
// Search messages in memory
try {
const searchText = "Name some books that are about dystopian futures.";
console.debug("Searching memory...", searchText);
const searchResults = await client.memory.search(sessionID, {
metadata: {
where: {
and: [
{
jsonpath: '$.system.entities[*] ? (@.Label == "WORK_OF_ART")',
},
{
jsonpath: '$.system.entities[*] ? (@.Name like_regex "^parable*" flag "i")',
},
],
},
},
text: searchText,
});
searchResults.forEach((searchResult) => {
console.debug("Search Result: ", JSON.stringify(searchResult.message));
console.debug("Search Result Score: ", JSON.stringify(searchResult.score));
});
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
// Search messages in memory with MMR and lambda=0.6
try {
const searchText = "Name some books that are about dystopian futures.";
console.debug("Searching memory with MMR...", searchText);
const searchResults = await client.memory.search(sessionID, {
text: searchText,
searchType: "mmr",
mmrLambda: 0.6,
limit: 3,
});
searchResults.forEach((searchResult) => {
console.debug("Search Result: ", JSON.stringify(searchResult.message));
console.debug("Search Result Score: ", JSON.stringify(searchResult.score));
});
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
// Search summaries in memory with MMR and lambda=0.6
try {
const searchText = "Name some books that are about dystopian futures.";
console.debug("Searching summaries with MMR...", searchText);
const searchResults = await client.memory.search(sessionID, {
text: searchText,
searchScope: "summary",
searchType: "mmr",
mmrLambda: 0.6,
limit: 3,
});
searchResults.forEach((searchResult) => {
console.debug("Search Result: ", JSON.stringify(searchResult.summary));
console.debug("Search Result Score: ", JSON.stringify(searchResult.score));
});
} catch (error) {
if (error instanceof NotFoundError) {
console.error("Session not found:", error.message);
} else {
console.error("Got error:", error);
}
}
// End session - this will trigger summarization and other background tasks on the completed session
try {
await client.memory.endSession(sessionID);
console.debug("Ended session: ", sessionID);
} catch (error) {
console.debug("Got error:", error);
}
}
main();