💾 Memory Systems
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Hiểu các loại Memory: Short-Term, Long-Term, Entity
✅ Implement Buffer Memory và Summary Memory
✅ Xây dựng Long-Term Memory với Vector Store
✅ Tạo Entity Memory để track user preferences
✅ Kết hợp multiple memory types trong Agent pipeline
✅ Sử dụng Redis cho persistent session memory
Memory giúp agents nhớ context, user preferences, và previous interactions. Bài này cover các memory types và implementation.
🧠 Memory Types
Checkpoint
Agent có những loại Memory nào? Sự khác biệt giữa Short-Term và Long-Term Memory là gì?
📋 Short-Term Memory
Buffer Memory
1// n8n Window Buffer Memory node2// Keeps last N messages in context34// Configuration:5// Session Key: {{ $json.sessionId }} 6// Context Window Length: 107// This preserves the last 10 messages89// Example memory state:10// [11// { role: "user", content: "What products do you have?" },12// { role: "assistant", content: "We have Product A, B, C..." },13// { role: "user", content: "Tell me about Product A" },14// { role: "assistant", content: "Product A is a..." }15// ]Summary Memory
1// When conversation gets long, summarize instead of full buffer2// n8n: Use Code node + OpenAI to compress history34const summarizePrompt = `5Summarize this conversation into key facts and decisions:67${$json.conversationHistory}89Summary (max 200 words):`;1011// Result: "User asked about products. Interested in Product A. 12// Budget: under $500. Prefers blue color."Checkpoint
Buffer Memory và Summary Memory khác nhau như thế nào? Khi nào nên dùng Summary Memory thay vì Buffer?
🔍 Long-Term Memory với Vector Store
1// Save important interactions to vector store2// Code node: Determine if worth saving3function shouldSave(interaction) {4 // Save if contains important information:5 const importantTopics = ["preference", "decision", "problem", "feedback"];6 return importantTopics.some(topic => 7 interaction.toLowerCase().includes(topic)8 );9}1011if (shouldSave($json.userMessage + $json.aiResponse)) {12 return {13 json: {14 content: `User: ${$json.userMessage}\nAssistant: ${$json.aiResponse}`,15 metadata: {16 sessionId: $json.sessionId,17 userId: $json.userId,18 timestamp: new Date().toISOString(),19 topic: $json.detectedTopic20 },21 save: true22 }23 };24}Checkpoint
Vector Store Memory hoạt động như thế nào? Criteria nào để quyết định có lưu interaction vào Long-Term Memory?
👤 Entity Memory
1// Track entities mentioned in conversation2// Code node: Entity extraction34const entityPrompt = `5Extract entities from this conversation:67${$json.conversation}89Return JSON:10{11 "people": [{"name": "...", "role": "...", "notes": "..."}],12 "companies": [{"name": "...", "details": "..."}],13 "products": [{"name": "...", "interest_level": "high/medium/low"}],14 "preferences": [{"key": "...", "value": "..."}]15}`;1617// Store entities in Redis or database per user18// key: entity_${userId}19// Retrieve entities on each new conversationCheckpoint
Entity Memory lưu trữ những loại thông tin nào? Cách extract entities từ conversation ra sao?
🏗️ Memory trong Agent Pipeline
1// Code node: Build memory context2const bufferHistory = $json.recentMessages; // Last 103const longTermResults = $json.vectorSearchResults; // Similar past4const entities = $json.userEntities; // Known facts about user56const memoryContext = `7## Known about this user:8${entities.map(e => `- ${e.key}: ${e.value}`).join('\n')}910## Recent conversation:11${bufferHistory.map(m => `${m.role}: ${m.content}`).join('\n')}1213## Relevant past interactions:14${longTermResults.map(r => r.content).join('\n---\n')}15`;1617return { json: { memoryContext } };Checkpoint
Trong Agent Pipeline, các loại memory được kết hợp theo thứ tự nào? Tại sao cần combine all memory types?
⚡ Redis Memory Implementation
1// Redis for persistent session memory2// n8n Redis Chat Memory node34// Configuration:5// - Redis URL: redis://localhost:63796// - Session Key: user_{{ $json.userId }}7// - TTL: 86400 (24 hours)8// - Max Messages: 50910// Automatically handles:11// - Persistent storage across n8n restarts12// - Session isolation per user13// - Auto-cleanup via TTL| Situation | Recommended Memory |
|---|---|
| Simple chatbot | Buffer Memory (10 msgs) |
| Customer support | Buffer + Entity Memory |
| Knowledge assistant | Buffer + Vector Long-term |
| Personal assistant | All three types |
- Buffer cho immediate context
- Entity cho user preferences/facts
- Vector cho searchable history
Checkpoint
Khi nào nên dùng Redis Memory? Hãy chọn memory strategy phù hợp cho từng use case.
📚 Bài tập thực hành
- Setup Buffer Memory cho chatbot workflow
- Add entity extraction và storage
- Implement long-term memory với vector store
- Build agent với combined memory types
Checkpoint
Bạn đã implement được các loại memory chưa? Agent có nhớ được context từ các conversations trước không?
🚀 Bài tiếp theo
Bài tiếp theo: Planning Agents →
