S-09 · TRACK 03 · PATTERNS

Memory & RAG

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.

Buổi 9 — Chúng ta sẽ đi qua gì?
🚩

01 · Giới hạn context window

Vì sao cần bộ nhớ ngoài context?

🧠

02 · Memory

Working · Episodic · Semantic · Procedural

📚

03 · RAG pipeline

Chunk → embed → retrieve → rerank → generate

🔬

04 · Biến thể RAG

Naive · Hybrid · Multi-hop · GraphRAG · Agentic

🎯

05 · Takeaways

5 điểm nhớ + homework

01

Vì sao cần
Memory & Retrieval?

Context window — tài nguyên hữu hạn

Nhét mọi thứ vào context

• 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.

Memory + RAG

• 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.

02

Pattern 1 · Memory
4 loại bộ nhớ agent

4 loại memory — mượn từ khoa học nhận thức
💬

Working

Scratch pad in-context, chỉ tồn tại trong 1 turn. Draft, tính toán trung gian.

📋

Episodic

Log interaction quá khứ — "user A hôm qua hỏi X". Store SQLite/Postgres.

📚

Semantic

Fact về thế giới & user profile. Store: Vector DB, Graph DB. Bền lâu.

🔧

Procedural

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).

Chọn store — latency × cost × query type
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
03

Pattern 2 · RAG
Pipeline chuẩn 5 bước

RAG pipeline — 5 stage cốt lõi
1

Chunk

Cắt doc thành đoạn 200-800 tokens.

2

Embed

Vector hoá (OpenAI, Voyage, BGE).

3

Retrieve

Similarity top-K ± BM25.

4

Rerank

Cross-encoder chấm lại top-K.

5

Generate

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%.

5 biến thể RAG — tiến hoá
v0

Naive RAG

Chunk → embed → top-K → generate. Cơ bản.

v1

Hybrid + Rerank

Vector + BM25 + cross-encoder. Chuẩn production.

v2

Multi-hop

Retrieve → reason → retrieve lại. Cho câu hỏi phức.

v3

GraphRAG

Extract entity + relation → graph → community summary.

v4

Agentic RAG

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).

04

Thực chiến
Code · Framework · Anti-patterns

Code — Hybrid RAG với rerank
hybrid_rag.py
# 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))
Anti-patterns Memory + RAG
🔢

Chunk quá to

>1500 tokens/chunk ⇒ dense trọn, recall thấp. Chuẩn: 200-800.

🔮

Chỉ dense retrieval

Miss keyword match. Thêm BM25, đặc biệt với ID/mã lỗi.

📈

Top-K quá lớn

K=50 ⇒ context nhồi, model lạc. K=5-10 sau rerank OK.

💰

Store toàn history

Không compress, cost phình. Dùng summarization hoặc TTL.

Case VN 🇳🇻 — 4 ứng dụng Memory + framework
💬

1. Chatbot & AI hội thoại

Short-term giữ mạch chat. Long-term nhớ sở thích & vấn đề cũ ⇒ personalize.

🎯

2. Agent hướng tác vụ

Short-term theo dõi bước & tiến độ. Long-term truy cập user data ngoài context.

🏆

3. Learning & adaptation

Lưu chiến lược thành công + lỗi vào long-term ⇒ agent thích ứng dần.

🚗

4. Hệ tự trị

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).

RAG production — 4 lỗi khiến recall thấp
🔉

Chunk theo trang thô

Cắt cứng 500 token ⇒ câu bị đứt giữa. Dùng recursive/semantic chunking.

💾

Bỏ metadata

Không lưu source, page, section ⇒ không hiển thị citation. User mất niềm tin.

📑

Embedding sai domain

Dùng OpenAI cho VN tiếng Việt ⇒ recall kém. Cân nhắc BGE-M3, Voyage, hay fine-tune.

🌟

Không update index

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).

CLI thực chiến — Memory & RAG

🤖 Claude Code

# 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

⚡ Cursor

# 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

💎 Gemini CLI

# 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.

05

Takeaways
& homework

5 điều nhớ
1

Context window không phải bộ nhớ — cần store ngoài cho long-term.

2

4 loại memory: Working · Episodic · Semantic · Procedural. Mỗi loại chọn store khác.

3

RAG chuẩn = Chunk 500t → embed → hybrid → rerank → generate. Đủ cho 90% use case.

4

Đi từ Naive → Hybrid+Rerank. Chỉ lên GraphRAG/Agentic khi thực sự cần.

5

Đo recall + precision RAG bằng golden dataset. Không đo = không cải thiện được.

Bài tập & chuẩn bị buổi 10
📝

Tự kiểm tra

  • • App bạn có 4 loại memory nào? Store ở đâu?
  • • Dựng Naive RAG với 10 docs sample — đo recall.
  • • Thử thêm BM25 + rerank — recall tăng bao nhiêu?
📚

Đọc trước

  • • A. Gulli — Ch.8 Memory + Ch.14 RAG.
  • • Microsoft — GraphRAG paper.
  • • Anthropic — Contextual retrieval blog.
🔗

Tài liệu VN

  • Kỹ thuật ngữ cảnh Phiên làm việc và Bộ nhớ
  • BỘ NÃO THỨ 2 - LLM WIKI.
  • Cẩm nang thực hành xây dựng HTTM.
Hết buổi 9

Buổi 10 — MCP & A2A
2 giao thức thống trị 2025: Anthropic MCP + Google A2A. Ch.10 + Ch.15 sách Gulli.