Agent nhớ được gì, tra được đâu? Short/long-term memory, vector DB, embedding, re-ranking, GraphRAG, Agentic RAG. Chapter 8 + 14 sách Gulli.
Vì sao cần bộ nhớ ngoài context?
Working · Episodic · Semantic · Procedural
Chunk → embed → retrieve → rerank → generate
Naive · Hybrid · Multi-hop · GraphRAG · Agentic
5 điểm nhớ + homework
• Context window 200k — tưởng nhiều nhưng nhồi 100 file DB là hết.
• Lost in the middle — thông tin giữa context bị bỏ sót.
• Token cost — mỗi turn tính đủ, bill phình.
• Không nhớ liên phiên — user login lại, agent quên hết.
• Knowledge cutoff — không có fact mới.
• Chỉ nhét top-K liên quan mỗi turn.
• Long-term memory — user profile, preference qua phiên.
• Store ngoài context: SQLite, Vector DB, Graph DB, filesystem.
• Retrieve on-demand — giảm cost 5-20 lần.
• Update dễ: index doc mới ⇒ agent biết fact mới.
Anthropic (2024): "Context engineering" là kỹ năng quan trọng nhất khi build agent production — quản lý cái gì always-in, cái gì on-demand.
Scratch pad in-context, chỉ tồn tại trong 1 turn. Draft, tính toán trung gian.
Log interaction quá khứ — "user A hôm qua hỏi X". Store SQLite/Postgres.
Fact về thế giới & user profile. Store: Vector DB, Graph DB. Bền lâu.
Skill, tool, cách làm. Store: Skill catalog, MCP server list.
Claude Code = CLAUDE.md (procedural) + memory files (semantic) + turn history (working) + session log (episodic).
| Store | Ưu điểm | Nhược điểm | Dùng cho |
|---|---|---|---|
| Filesystem (MD/JSON) | Đơn giản, git-able, audit dễ | Không semantic search | Procedural, CLAUDE.md |
| SQLite / Postgres | Query SQL, transaction | Không similarity search | Episodic, user profile |
| Vector DB (Pinecone, Qdrant, Weaviate) | Semantic search nhanh | Setup phức tạp, cost | Semantic, RAG chunks |
| pgvector | SQL + vector cùng chỗ | Không tối ưu như dedicated | Trung bình traffic |
| Graph DB (Neo4j) | Truy vấn quan hệ tốt | Query language khó | GraphRAG, ontology |
Cắt doc thành đoạn 200-800 tokens.
Vector hoá (OpenAI, Voyage, BGE).
Similarity top-K ± BM25.
Cross-encoder chấm lại top-K.
Stuff top-N vào prompt, sinh.
3 stage hay quên: chunking strategy, hybrid (vector+BM25), reranker. Có 3 cái này ⇒ RAG recall tăng 20-40%.
Chunk → embed → top-K → generate. Cơ bản.
Vector + BM25 + cross-encoder. Chuẩn production.
Retrieve → reason → retrieve lại. Cho câu hỏi phức.
Extract entity + relation → graph → community summary.
Agent tự quyết query, retrieve, re-query. Có tool.
Đi từ Naive. Chỉ leo lên GraphRAG/Agentic khi Hybrid+Rerank vẫn không đủ (thường gặp ở domain enterprise 100k+ doc).
# Index (offline) chunks = chunk_recursive(doc, size=500, overlap=50) vectors = embed_model.embed_batch(chunks) vector_db.upsert(chunks, vectors) bm25_index.index(chunks) # Query (online) def retrieve(query: str, k: int = 20, top_n: int = 5): # Hybrid: vector + BM25 qv = embed_model.embed(query) vec_hits = vector_db.search(qv, k=k) bm25_hits = bm25_index.search(query, k=k) candidates = merge_dedupe(vec_hits, bm25_hits) # RRF fusion # Rerank với cross-encoder scored = reranker.score(query, candidates) return sorted(scored, key=lambda x: x.score, reverse=True)[:top_n] # Generate context = "\n---\n".join([c.text for c in retrieve(user_q)]) answer = llm.generate(prompt=RAG_TEMPLATE.format(context=context, q=user_q))
>1500 tokens/chunk ⇒ dense trọn, recall thấp. Chuẩn: 200-800.
Miss keyword match. Thêm BM25, đặc biệt với ID/mã lỗi.
K=50 ⇒ context nhồi, model lạc. K=5-10 sau rerank OK.
Không compress, cost phình. Dùng summarization hoặc TTL.
Short-term giữ mạch chat. Long-term nhớ sở thích & vấn đề cũ ⇒ personalize.
Short-term theo dõi bước & tiến độ. Long-term truy cập user data ngoài context.
Lưu chiến lược thành công + lỗi vào long-term ⇒ agent thích ứng dần.
Robot / xe tự lái: bản đồ, tuyến đường, hành vi đã học — đều là memory.
| Framework | Short-term | Long-term |
|---|---|---|
| LangChain | ConversationBufferMemory |
External store (Vector DB) |
| LangGraph | State object | Store JSON theo namespace + key |
| Google ADK | Session State | MemoryService, Vertex Memory Bank |
| Claude Code | Turn history + CLAUDE.md | Memory files + Skill catalog |
Tổng hợp từ Cẩm nang thực hành xây dựng HTTM (VN Gulli Ch.8).
Cắt cứng 500 token ⇒ câu bị đứt giữa. Dùng recursive/semantic chunking.
Không lưu source, page, section ⇒ không hiển thị citation. User mất niềm tin.
Dùng OpenAI cho VN tiếng Việt ⇒ recall kém. Cân nhắc BGE-M3, Voyage, hay fine-tune.
Doc mới không index ⇒ agent trả cũ. Cần pipeline sync định kỳ + change detection.
Golden rule: đo recall & precision bằng bộ query có nhãn TRƯỚC khi tối ưu. Thay đổi chunking / embedding chỉ có giá trị nếu có metric baseline.
Tham chiếu: Kỹ thuật ngữ cảnh Phiên làm việc & Bộ nhớ + BỘ NÃO THỨ 2 - LLM WIKI (VN).
# Project memory touch CLAUDE.md # Ghi convention, style, # context dự án ở đây # User memory (all repos) # Linux/mac: ~/.claude/CLAUDE.md # Windows: %USERPROFILE%\.claude\ CLAUDE.md # Auto-memory (per session) claude # /memory → xem/edit # # Note tự save # RAG qua MCP Vector DB claude mcp add pgvector \ -- npx @modelcontext/\ pgvector-mcp # Skill với embedded KB mkdir .claude/skills/docs
# Rules = memory dài hạn mkdir .cursor/rules # style.mdc: coding style # domain.mdc: business rules # tech.mdc: framework choice # Auto-indexing codebase # Cursor tự embed # Settings → Codebase # → Enable indexing # RAG context @-mention # @docs → tài liệu external # @web → search live # @git → commit history # Docs custom (RAG) # Settings → Docs # Add URL → auto crawl # User rules (all repos) # Settings → Rules → User
# Project memory touch GEMINI.md # Context tự load mỗi turn # Global memory # Linux/mac: ~/.gemini/GEMINI.md # Windows: %USERPROFILE%\.gemini\ GEMINI.md # Save memory trong chat gemini # /memory add "user thích TS" # /memory show # Context caching # Long context tự cache # giảm cost 75% trên hit # RAG file lớn gemini -a docs/ \ -p "Tìm section X"
Hệ thống memory tương đương: Claude CLAUDE.md · Cursor .cursor/rules/*.mdc · Gemini GEMINI.md. Nên commit vào git để cả team dùng chung.
RAG chuyên nghiệp: đừng dùng codebase-indexing built-in cho KB nghiệp vụ — setup Vector DB (pgvector, Qdrant) + wire qua MCP cho cả 3 CLI.
Context window không phải bộ nhớ — cần store ngoài cho long-term.
4 loại memory: Working · Episodic · Semantic · Procedural. Mỗi loại chọn store khác.
RAG chuẩn = Chunk 500t → embed → hybrid → rerank → generate. Đủ cho 90% use case.
Đi từ Naive → Hybrid+Rerank. Chỉ lên GraphRAG/Agentic khi thực sự cần.
Đo recall + precision RAG bằng golden dataset. Không đo = không cải thiện được.