@mem0/community
Version:
Community features for Mem0
170 lines (167 loc) • 5.99 kB
JavaScript
'use strict';
var mem0ai = require('mem0ai');
var memory = require('@langchain/core/memory');
var messages = require('@langchain/core/messages');
var chat_memory = require('@langchain/community/memory/chat_memory');
// src/integrations/langchain/mem0.ts
var mem0MemoryContextToSystemPrompt = (memory) => {
if (!memory || !Array.isArray(memory)) {
return "";
}
return memory.filter((m) => m?.memory).map((m) => m.memory).join("\n");
};
var condenseMem0MemoryIntoHumanMessage = (memory) => {
const basePrompt = "These are the memories I have stored. Give more weightage to the question by users and try to answer that first. You have to modify your answer based on the memories I have provided. If the memories are irrelevant you can ignore them. Also don't reply to this section of the prompt, or the memories, they are only for your reference. The MEMORIES of the USER are: \n\n";
const systemPrompt = mem0MemoryContextToSystemPrompt(memory);
return new messages.HumanMessage(`${basePrompt}
${systemPrompt}`);
};
var mem0MemoryToMessages = (memories) => {
if (!memories || !Array.isArray(memories)) {
return [];
}
const messages$1 = [];
const memoryContent = memories.filter((m) => m?.memory).map((m) => m.memory).join("\n");
if (memoryContent) {
messages$1.push(new messages.SystemMessage(memoryContent));
}
memories.forEach((memory) => {
if (memory.messages) {
memory.messages.forEach((msg) => {
const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
if (msg.role === "user") {
messages$1.push(new messages.HumanMessage(content));
} else if (msg.role === "assistant") {
messages$1.push(new messages.AIMessage(content));
} else if (content) {
messages$1.push(new messages.ChatMessage(content, msg.role));
}
});
}
});
return messages$1;
};
var Mem0Memory = class extends chat_memory.BaseChatMemory {
constructor(fields) {
if (!fields.apiKey) {
throw new Error("apiKey is required for Mem0Memory");
}
if (!fields.sessionId) {
throw new Error("sessionId is required for Mem0Memory");
}
super({
returnMessages: fields?.returnMessages ?? false,
inputKey: fields?.inputKey,
outputKey: fields?.outputKey
});
this.memoryKey = "history";
this.humanPrefix = "Human";
this.aiPrefix = "AI";
this.apiKey = fields.apiKey;
this.sessionId = fields.sessionId;
this.humanPrefix = fields.humanPrefix ?? this.humanPrefix;
this.aiPrefix = fields.aiPrefix ?? this.aiPrefix;
this.memoryOptions = fields.memoryOptions ?? {};
this.mem0Options = fields.mem0Options ?? {
apiKey: this.apiKey
};
this.separateMessages = fields.separateMessages ?? false;
try {
this.mem0Client = new mem0ai.MemoryClient({
...this.mem0Options,
apiKey: this.apiKey
});
} catch (error) {
console.error("Failed to initialize Mem0Client:", error);
throw new Error(
"Failed to initialize Mem0Client. Please check your configuration."
);
}
}
get memoryKeys() {
return [this.memoryKey];
}
/**
* Retrieves memories from the Mem0 service and formats them for use
* @param values Input values containing optional search query
* @returns Promise resolving to formatted memory variables
*/
async loadMemoryVariables(values) {
const searchType = values.input ? "search" : "get_all";
let memories = [];
try {
if (searchType === "get_all") {
memories = await this.mem0Client.getAll({
user_id: this.sessionId,
...this.memoryOptions
});
} else {
memories = await this.mem0Client.search(values.input, {
user_id: this.sessionId,
...this.memoryOptions
});
}
} catch (error) {
console.error("Error loading memories:", error);
return this.returnMessages ? { [this.memoryKey]: [] } : { [this.memoryKey]: "" };
}
if (this.returnMessages) {
return {
[this.memoryKey]: this.separateMessages ? mem0MemoryToMessages(memories) : [condenseMem0MemoryIntoHumanMessage(memories)]
};
}
return {
[this.memoryKey]: this.separateMessages ? messages.getBufferString(
mem0MemoryToMessages(memories),
this.humanPrefix,
this.aiPrefix
) : condenseMem0MemoryIntoHumanMessage(memories).content ?? ""
};
}
/**
* Saves the current conversation context to the Mem0 service
* @param inputValues Input messages to be saved
* @param outputValues Output messages to be saved
* @returns Promise resolving when the context has been saved
*/
async saveContext(inputValues, outputValues) {
const input = memory.getInputValue(inputValues, this.inputKey);
const output = memory.getOutputValue(outputValues, this.outputKey);
if (!input || !output) {
console.warn("Missing input or output values, skipping memory save");
return;
}
try {
const messages = [
{
role: "user",
content: `${input}`
},
{
role: "assistant",
content: `${output}`
}
];
await this.mem0Client.add(messages, {
user_id: this.sessionId,
...this.memoryOptions
});
} catch (error) {
console.error("Error saving memory context:", error);
}
await super.saveContext(inputValues, outputValues);
}
/**
* Clears all memories for the current session
* @returns Promise resolving when memories have been cleared
*/
async clear() {
await super.clear();
}
};
exports.Mem0Memory = Mem0Memory;
exports.condenseMem0MemoryIntoHumanMessage = condenseMem0MemoryIntoHumanMessage;
exports.mem0MemoryContextToSystemPrompt = mem0MemoryContextToSystemPrompt;
exports.mem0MemoryToMessages = mem0MemoryToMessages;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map