MinAI - Về trang chủ
Lý thuyết
4/1335 phút
Đang tải...

Memory Systems

Implement memory systems cho AI Agents - short-term, long-term, entity memory

💾 Memory Systems

0

🎯 Mục tiêu bài học

TB5 min

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.

1

🧠 Memory Types

TB5 min
Diagram
Đang vẽ diagram...

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ì?

2

📋 Short-Term Memory

TB5 min

Buffer Memory

JavaScript
1// n8n Window Buffer Memory node
2// Keeps last N messages in context
3
4// Configuration:
5// Session Key: {{ $json.sessionId }}
6// Context Window Length: 10
7// This preserves the last 10 messages
8
9// 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

JavaScript
1// When conversation gets long, summarize instead of full buffer
2// n8n: Use Code node + OpenAI to compress history
3
4const summarizePrompt = `
5Summarize this conversation into key facts and decisions:
6
7${$json.conversationHistory}
8
9Summary (max 200 words):`;
10
11// 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?

3

🔍 Long-Term Memory với Vector Store

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Save important interactions to vector store
2// Code node: Determine if worth saving
3function 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}
10
11if (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.detectedTopic
20 },
21 save: true
22 }
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?

4

👤 Entity Memory

TB5 min
JavaScript
1// Track entities mentioned in conversation
2// Code node: Entity extraction
3
4const entityPrompt = `
5Extract entities from this conversation:
6
7${$json.conversation}
8
9Return JSON:
10{
11 "people": [{"name": "...", "role": "...", "notes": "..."}],
12 "companies": [{"name": "...", "details": "..."}],
13 "products": [{"name": "...", "interest_level": "high/medium/low"}],
14 "preferences": [{"key": "...", "value": "..."}]
15}`;
16
17// Store entities in Redis or database per user
18// key: entity_${userId}
19// Retrieve entities on each new conversation

Checkpoint

Entity Memory lưu trữ những loại thông tin nào? Cách extract entities từ conversation ra sao?

5

🏗️ Memory trong Agent Pipeline

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Code node: Build memory context
2const bufferHistory = $json.recentMessages; // Last 10
3const longTermResults = $json.vectorSearchResults; // Similar past
4const entities = $json.userEntities; // Known facts about user
5
6const memoryContext = `
7## Known about this user:
8${entities.map(e => `- ${e.key}: ${e.value}`).join('\n')}
9
10## Recent conversation:
11${bufferHistory.map(m => `${m.role}: ${m.content}`).join('\n')}
12
13## Relevant past interactions:
14${longTermResults.map(r => r.content).join('\n---\n')}
15`;
16
17return { 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?

6

⚡ Redis Memory Implementation

TB5 min
JavaScript
1// Redis for persistent session memory
2// n8n Redis Chat Memory node
3
4// Configuration:
5// - Redis URL: redis://localhost:6379
6// - Session Key: user_{{ $json.userId }}
7// - TTL: 86400 (24 hours)
8// - Max Messages: 50
9
10// Automatically handles:
11// - Persistent storage across n8n restarts
12// - Session isolation per user
13// - Auto-cleanup via TTL
Memory Strategy Tips
SituationRecommended Memory
Simple chatbotBuffer Memory (10 msgs)
Customer supportBuffer + Entity Memory
Knowledge assistantBuffer + Vector Long-term
Personal assistantAll 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.

7

📚 Bài tập thực hành

TB5 min
Exercises
  1. Setup Buffer Memory cho chatbot workflow
  2. Add entity extraction và storage
  3. Implement long-term memory với vector store
  4. 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 →