({
messages,
memoryNames
}: {
messages: Message[];
memoryNames: string[];
})
| 134 | }; |
| 135 | |
| 136 | export const addContextFromMemory = async ({ |
| 137 | messages, |
| 138 | memoryNames |
| 139 | }: { |
| 140 | messages: Message[]; |
| 141 | memoryNames: string[]; |
| 142 | }) => { |
| 143 | try { |
| 144 | // Check if there are no memory names. |
| 145 | const isMemoryAttached = memoryNames.length > 0; |
| 146 | logger('memory', isMemoryAttached, 'Memory attached'); |
| 147 | |
| 148 | // Check if there are no messages. |
| 149 | const messagesExist = messages.length > 0; |
| 150 | |
| 151 | // Return the messages if there are no memory names or messages. |
| 152 | if (!isMemoryAttached || !messagesExist) return; |
| 153 | |
| 154 | // This will be the user prompt. |
| 155 | const lastUserMsg = [...messages] |
| 156 | .reverse() |
| 157 | .find(m => m.role === 'user'); |
| 158 | const userPrompt = lastUserMsg?.content; |
| 159 | |
| 160 | // If there is no user prompt, return the messages. |
| 161 | if (!userPrompt) return; |
| 162 | |
| 163 | // 1- Generate the embeddings of the user prompt. |
| 164 | // Read config to determine which embedding to use. |
| 165 | const config = await loadConfig(); |
| 166 | const useLocalEmbeddings = config.memory?.useLocalEmbeddings || false; |
| 167 | |
| 168 | let embeddings = []; |
| 169 | if (useLocalEmbeddings) { |
| 170 | // Use local embeddings |
| 171 | dlog('Generating local embeddings'); |
| 172 | embeddings = await generateLocalEmbeddings([userPrompt]); |
| 173 | } else { |
| 174 | // Use OpenAI embeddings |
| 175 | dlog('Generating OpenAI embeddings'); |
| 176 | embeddings = await getOpenAIEmbeddings([userPrompt]); |
| 177 | } |
| 178 | |
| 179 | // 2- Get all the memorysets from the db. |
| 180 | const memoryChunks = await getDocumentsFromMemory(memoryNames); |
| 181 | if (memoryChunks.length === 0) return; |
| 182 | |
| 183 | // 3- Get similar chunks from the memorysets. |
| 184 | const similarChunks = cosineSimilaritySearch({ |
| 185 | chunks: memoryChunks, |
| 186 | queryEmbedding: embeddings[0].embedding, |
| 187 | topK: MEMORYSETS.MAX_CHUNKS_ATTACHED_TO_LLM |
| 188 | }); |
| 189 | if (similarChunks.length === 0) return; |
| 190 | logger('memory.similarChunks', similarChunks); |
| 191 | |
| 192 | return similarChunks; |
| 193 | } catch (error: any) { |
no test coverage detected