File size: 4,707 Bytes
f0743f4 | 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 | import { Types } from 'mongoose';
import logger from '~/config/winston';
import type * as t from '~/types';
/**
* Formats a date in YYYY-MM-DD format
*/
const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
};
// Factory function that takes mongoose instance and returns the methods
export function createMemoryMethods(mongoose: typeof import('mongoose')) {
/**
* Creates a new memory entry for a user
* Throws an error if a memory with the same key already exists
*/
async function createMemory({
userId,
key,
value,
tokenCount = 0,
}: t.SetMemoryParams): Promise<t.MemoryResult> {
try {
if (key?.toLowerCase() === 'nothing') {
return { ok: false };
}
const MemoryEntry = mongoose.models.MemoryEntry;
const existingMemory = await MemoryEntry.findOne({ userId, key });
if (existingMemory) {
throw new Error('Memory with this key already exists');
}
await MemoryEntry.create({
userId,
key,
value,
tokenCount,
updated_at: new Date(),
});
return { ok: true };
} catch (error) {
throw new Error(
`Failed to create memory: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
}
}
/**
* Sets or updates a memory entry for a user
*/
async function setMemory({
userId,
key,
value,
tokenCount = 0,
}: t.SetMemoryParams): Promise<t.MemoryResult> {
try {
if (key?.toLowerCase() === 'nothing') {
return { ok: false };
}
const MemoryEntry = mongoose.models.MemoryEntry;
await MemoryEntry.findOneAndUpdate(
{ userId, key },
{
value,
tokenCount,
updated_at: new Date(),
},
{
upsert: true,
new: true,
},
);
return { ok: true };
} catch (error) {
throw new Error(
`Failed to set memory: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
}
}
/**
* Deletes a specific memory entry for a user
*/
async function deleteMemory({ userId, key }: t.DeleteMemoryParams): Promise<t.MemoryResult> {
try {
const MemoryEntry = mongoose.models.MemoryEntry;
const result = await MemoryEntry.findOneAndDelete({ userId, key });
return { ok: !!result };
} catch (error) {
throw new Error(
`Failed to delete memory: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
}
}
/**
* Gets all memory entries for a user
*/
async function getAllUserMemories(
userId: string | Types.ObjectId,
): Promise<t.IMemoryEntryLean[]> {
try {
const MemoryEntry = mongoose.models.MemoryEntry;
return (await MemoryEntry.find({ userId }).lean()) as t.IMemoryEntryLean[];
} catch (error) {
throw new Error(
`Failed to get all memories: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
}
}
/**
* Gets and formats all memories for a user in two different formats
*/
async function getFormattedMemories({
userId,
}: t.GetFormattedMemoriesParams): Promise<t.FormattedMemoriesResult> {
try {
const memories = await getAllUserMemories(userId);
if (!memories || memories.length === 0) {
return { withKeys: '', withoutKeys: '', totalTokens: 0 };
}
const sortedMemories = memories.sort(
(a, b) => new Date(a.updated_at!).getTime() - new Date(b.updated_at!).getTime(),
);
const totalTokens = sortedMemories.reduce((sum, memory) => {
return sum + (memory.tokenCount || 0);
}, 0);
const withKeys = sortedMemories
.map((memory, index) => {
const date = formatDate(new Date(memory.updated_at!));
const tokenInfo = memory.tokenCount ? ` [${memory.tokenCount} tokens]` : '';
return `${index + 1}. [${date}]. ["key": "${memory.key}"]${tokenInfo}. ["value": "${memory.value}"]`;
})
.join('\n\n');
const withoutKeys = sortedMemories
.map((memory, index) => {
const date = formatDate(new Date(memory.updated_at!));
return `${index + 1}. [${date}]. ${memory.value}`;
})
.join('\n\n');
return { withKeys, withoutKeys, totalTokens };
} catch (error) {
logger.error('Failed to get formatted memories:', error);
return { withKeys: '', withoutKeys: '', totalTokens: 0 };
}
}
return {
setMemory,
createMemory,
deleteMemory,
getAllUserMemories,
getFormattedMemories,
};
}
export type MemoryMethods = ReturnType<typeof createMemoryMethods>;
|