-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
zep.ts
247 lines (216 loc) Β· 6.71 KB
/
zep.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
import { Memory, Message, NotFoundError, ZepClient } from "@getzep/zep-js";
import {
InputValues,
OutputValues,
MemoryVariables,
getInputValue,
getOutputValue,
} from "@langchain/core/memory";
import {
getBufferString,
AIMessage,
BaseMessage,
ChatMessage,
HumanMessage,
SystemMessage,
} from "@langchain/core/messages";
import { BaseChatMemory, BaseChatMemoryInput } from "./chat_memory.js";
/**
* Interface defining the structure of the input data for the ZepMemory
* class. It includes properties like humanPrefix, aiPrefix, memoryKey,
* baseURL, sessionId, and apiKey.
*/
export interface ZepMemoryInput extends BaseChatMemoryInput {
humanPrefix?: string;
aiPrefix?: string;
memoryKey?: string;
baseURL: string;
sessionId: string;
// apiKey is optional.
apiKey?: string;
}
/**
* Class used to manage the memory of a chat session, including loading
* and saving the chat history, and clearing the memory when needed. It
* uses the ZepClient to interact with the Zep service for managing the
* chat session's memory.
* @example
* ```typescript
* const sessionId = randomUUID();
* const zepURL = "http://your-zep-url";
*
* // Initialize ZepMemory with session ID, base URL, and API key
* const memory = new ZepMemory({
* sessionId,
* baseURL: zepURL,
* apiKey: "change_this_key",
* });
*
* // Create a ChatOpenAI model instance with specific parameters
* const model = new ChatOpenAI({
* modelName: "gpt-3.5-turbo",
* temperature: 0,
* });
*
* // Create a ConversationChain with the model and memory
* const chain = new ConversationChain({ llm: model, memory });
*
* // Example of calling the chain with an input
* const res1 = await chain.call({ input: "Hi! I'm Jim." });
* console.log({ res1 });
*
* // Follow-up call to the chain to demonstrate memory usage
* const res2 = await chain.call({ input: "What did I just say my name was?" });
* console.log({ res2 });
*
* // Output the session ID and the current state of memory
* console.log("Session ID: ", sessionId);
* console.log("Memory: ", await memory.loadMemoryVariables({}));
*
* ```
*/
export class ZepMemory extends BaseChatMemory implements ZepMemoryInput {
humanPrefix = "Human";
aiPrefix = "AI";
memoryKey = "history";
baseURL: string;
sessionId: string;
zepClientPromise: Promise<ZepClient>;
private readonly zepInitFailMsg = "ZepClient is not initialized";
constructor(fields: ZepMemoryInput) {
super({
returnMessages: fields?.returnMessages ?? false,
inputKey: fields?.inputKey,
outputKey: fields?.outputKey,
});
this.humanPrefix = fields.humanPrefix ?? this.humanPrefix;
this.aiPrefix = fields.aiPrefix ?? this.aiPrefix;
this.memoryKey = fields.memoryKey ?? this.memoryKey;
this.baseURL = fields.baseURL;
this.sessionId = fields.sessionId;
this.zepClientPromise = ZepClient.init(this.baseURL, fields.apiKey);
}
get memoryKeys() {
return [this.memoryKey];
}
/**
* Method that retrieves the chat history from the Zep service and formats
* it into a list of messages.
* @param values Input values for the method.
* @returns Promise that resolves with the chat history formatted into a list of messages.
*/
async loadMemoryVariables(values: InputValues): Promise<MemoryVariables> {
// use either lastN provided by developer or undefined to use the
// server preset.
// Wait for ZepClient to be initialized
const zepClient = await this.zepClientPromise;
if (!zepClient) {
throw new Error(this.zepInitFailMsg);
}
const lastN = values.lastN ?? undefined;
let memory: Memory | null = null;
try {
memory = await zepClient.memory.getMemory(this.sessionId, lastN);
} catch (error) {
// eslint-disable-next-line no-instanceof/no-instanceof
if (error instanceof NotFoundError) {
const result = this.returnMessages
? { [this.memoryKey]: [] }
: { [this.memoryKey]: "" };
return result;
} else {
throw error;
}
}
let messages: BaseMessage[] =
memory && memory.summary?.content
? [new SystemMessage(memory.summary.content)]
: [];
if (memory) {
messages = messages.concat(
memory.messages.map((message) => {
const { content, role } = message;
if (role === this.humanPrefix) {
return new HumanMessage(content);
} else if (role === this.aiPrefix) {
return new AIMessage(content);
} else {
// default to generic ChatMessage
return new ChatMessage(content, role);
}
})
);
}
if (this.returnMessages) {
return {
[this.memoryKey]: messages,
};
}
return {
[this.memoryKey]: getBufferString(
messages,
this.humanPrefix,
this.aiPrefix
),
};
}
/**
* Method that saves the input and output messages to the Zep service.
* @param inputValues Input messages to be saved.
* @param outputValues Output messages to be saved.
* @returns Promise that resolves when the messages have been saved.
*/
async saveContext(
inputValues: InputValues,
outputValues: OutputValues
): Promise<void> {
const input = getInputValue(inputValues, this.inputKey);
const output = getOutputValue(outputValues, this.outputKey);
// Create new Memory and Message instances
const memory = new Memory({
messages: [
new Message({
role: this.humanPrefix,
content: `${input}`,
}),
new Message({
role: this.aiPrefix,
content: `${output}`,
}),
],
});
// Wait for ZepClient to be initialized
const zepClient = await this.zepClientPromise;
if (!zepClient) {
throw new Error(this.zepInitFailMsg);
}
// Add the new memory to the session using the ZepClient
if (this.sessionId) {
try {
await zepClient.memory.addMemory(this.sessionId, memory);
} catch (error) {
console.error("Error adding memory: ", error);
}
}
// Call the superclass's saveContext method
await super.saveContext(inputValues, outputValues);
}
/**
* Method that deletes the chat history from the Zep service.
* @returns Promise that resolves when the chat history has been deleted.
*/
async clear(): Promise<void> {
// Wait for ZepClient to be initialized
const zepClient = await this.zepClientPromise;
if (!zepClient) {
throw new Error(this.zepInitFailMsg);
}
try {
await zepClient.memory.deleteMemory(this.sessionId);
} catch (error) {
console.error("Error deleting session: ", error);
}
// Clear the superclass's chat history
await super.clear();
}
}