| 155 | |
| 156 | /** Build memory context string for system prompt injection */ |
| 157 | export function buildMemoryPrompt(memories: MemoryEntry[]): string { |
| 158 | if (memories.length === 0) return ''; |
| 159 | |
| 160 | const grouped: Record<string, string[]> = {}; |
| 161 | for (const m of memories) { |
| 162 | if (!grouped[m.category]) grouped[m.category] = []; |
| 163 | grouped[m.category].push(m.content); |
| 164 | } |
| 165 | |
| 166 | const categoryLabels: Record<string, string> = { |
| 167 | fact: 'Facts about the user', |
| 168 | preference: 'User preferences', |
| 169 | event: 'Key events', |
| 170 | emotion: 'Emotional moments', |
| 171 | other: 'Other memories', |
| 172 | }; |
| 173 | |
| 174 | let prompt = '\n\n## Your memories about the user\n'; |
| 175 | prompt += |
| 176 | 'The following are things you remember from previous conversations. Use them naturally — do not explicitly tell the user you are reading from memory.\n\n'; |
| 177 | |
| 178 | for (const [cat, items] of Object.entries(grouped)) { |
| 179 | prompt += `### ${categoryLabels[cat] || cat}\n`; |
| 180 | for (const item of items) { |
| 181 | prompt += `- ${item}\n`; |
| 182 | } |
| 183 | prompt += '\n'; |
| 184 | } |
| 185 | |
| 186 | prompt += |
| 187 | 'When you learn something new and important about the user, use the save_memory tool to remember it.\n'; |
| 188 | |
| 189 | return prompt; |
| 190 | } |