Our basic agent forgets everything between sessions. Let's fix that.
const sessions = new Map();
async function chat(sessionId: string, userMessage: string) {
if (!sessions.has(sessionId)) sessions.set(sessionId, []);
const messages = sessions.get(sessionId);
messages.push({ role: "user", content: userMessage });
const response = await runAgentLoop(messages, tools);
messages.push({ role: "assistant", content: response });
return response;
}
import { readFileSync, writeFileSync } from "fs";
function saveSession(id: string, messages: any[]) {
writeFileSync(`./sessions/${id}.json`, JSON.stringify(messages));
}
function loadSession(id: string): any[] {
try { return JSON.parse(readFileSync(`./sessions/${id}.json`, "utf-8")); }
catch { return []; }
}
// After each turn, store the key facts:
await vectorDB.add({
text: `User asked about ${topic}. Key facts: ${facts}`,
metadata: { userId, timestamp, sessionId }
});
// Before responding, recall relevant memories:
const memories = await vectorDB.query(userMessage, { topK: 3 });
| Need | Solution | Complexity |
|---|---|---|
| Remember within a session | In-memory array | Low |
| Resume after restart | File/DB persistence | Low-Medium |
| Recall from any past chat | Vector DB (Chroma) | Medium |
| Learn preferences over time | User profiles + vector search | Medium-High |