Series 3 - Bài 6: RAG trong Agent Context
RAG không phải magic bullet. Nó shift vấn đề từ context size sang retrieval quality. Bài này phân tích khi nào RAG thực sự cần và khi nào nó là over-engineering.
Tập này đang được chuẩn bị, quay lại sau nhé.
Retrieval-Augmented Generation (RAG) được đề cập như giải pháp cho mọi vấn đề memory của LLM. Thực tế phức tạp hơn.
RAG không giải quyết vấn đề memory — nó shift vấn đề từ "làm sao fit knowledge vào context" sang "làm sao retrieve đúng knowledge". Và retrieval quality không dễ đạt được.
RAG là gì trong Agent Context
RAG Flow trong Agent:
User message: "How should I handle concurrent loan updates?"
│
▼
┌──────────────────────────────────────────────────┐
│ RAG Retrieval Step │
│ │
│ 1. Embed query: vectorize user message │
│ "concurrent loan updates" → [0.23, -0.45, ...]│
│ │
│ 2. Vector search in knowledge base: │
│ Find chunks with similar embedding │
│ │
│ 3. Return top K chunks: │
│ [doc: concurrency patterns, chunk 3] │
│ [doc: Oracle locking guide, chunk 7] │
│ [doc: MSB loan domain rules, chunk 12] │
└──────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────┐
│ Inject vào Context │
│ │
│ [RETRIEVED CONTEXT] │
│ From concurrency patterns: "Use optimistic │
│ locking with version columns for concurrent..." │
│ From Oracle guide: "SELECT FOR UPDATE SKIP │
│ LOCKED allows non-blocking reads..." │
└──────────────────────────────────────────────────┘
│
▼
LLM answer với relevant knowledge
Khi nào RAG thực sự cần
✅ Case 1: Knowledge base lớn không fit vào context
Ví dụ cụ thể:
Company documentation: 500 docs, 2 million tokens
Context window: 200,000 tokens
Không thể inject tất cả → RAG là giải pháp
Ngưỡng thực tế: Nếu knowledge base > 50,000 tokens và user query chỉ cần một phần nhỏ, RAG có lợi.
✅ Case 2: Knowledge thay đổi thường xuyên
API documentation update mỗi sprint
Pricing rules thay đổi mỗi tháng
Customer records cập nhật liên tục
→ Inject static snapshot vào system prompt sẽ stale
→ RAG retrieve real-time từ updated knowledge base
✅ Case 3: Domain-specific knowledge sâu
Regulatory requirements (luật, compliance)
Internal business rules phức tạp
Technical specifications chi tiết
→ LLM không có trong training data
→ Cần explicit retrieval mỗi lần
Khi nào RAG là over-engineering
❌ Case 1: Knowledge base nhỏ
Small knowledge base (< 20,000 tokens):
Inject toàn bộ vào system prompt
Simple, reliable, không cần infrastructure
RAG ở đây: thêm vector DB, embedding model,
retrieval pipeline... cho knowledge có thể
fit trong 20,000 tokens.
→ Overkill hoàn toàn
❌ Case 2: Knowledge cố định và ít thay đổi
Coding conventions của team: 5 trang
Architecture decisions: 10 ADRs
Onboarding guide: 20 pages
→ Inject vào system prompt một lần
→ RAG thêm latency và complexity không cần thiết
❌ Case 3: Retrieval quality khó đảm bảo
Knowledge base không có clear structure
Documents chồng chéo, contradictory
Query intent khó map sang vector space
Ví dụ khó:
Query: "Should I use eager or lazy loading?"
Relevance phụ thuộc vào:
- Context của codebase
- Loại relationship
- Performance requirements
Vector search sẽ retrieve theo semantic similarity
nhưng "đúng" context không thể xác định bằng
embedding similarity đơn thuần.
→ RAG trả về chunks, nhưng chunks có thể không
applicable cho case cụ thể
→ Garbage in, garbage out
Retrieval Quality: Vấn đề cốt lõi
RAG shift problem sang retrieval. Retrieval quality phụ thuộc vào:
1. Chunking strategy:
Bad chunking (by character count):
[Chunk 1] "...the loan processing system uses"
[Chunk 2] "Strategy pattern for payment types. Each"
[Chunk 3] "type implements the PaymentStrategy..."
→ Một concept bị split giữa chunks
→ Vector search sẽ retrieve partial information
Good chunking (by semantic unit):
[Chunk A] Full section về Strategy pattern usage
[Chunk B] Full section về payment type handling
→ Mỗi chunk self-contained
2. Embedding model:
General embedding: tốt cho general queries
Domain-specific: tốt hơn cho technical queries
Multilingual: cần thiết nếu docs tiếng Việt
3. Query preprocessing:
Raw query: "concurrent updates"
Expanded: "concurrent updates optimistic locking
database transactions isolation"
→ Expanded query cho retrieval tốt hơn
4. Re-ranking:
Top 10 by vector similarity
Re-rank by cross-encoder (more accurate)
Use top 3
→ Tốn compute hơn nhưng precision cao hơn
RAG trong Agent vs RAG trong Chatbot
Chatbot RAG:
Single retrieval → generate response
Straightforward, well-studied
Agent RAG:
Multiple retrieval points trong một session
Agent tự quyết định khi nào retrieve
Tool: retrieve_knowledge(query)
LLM gọi tool này khi cần
Complexity thêm:
- Agent có thể retrieve không đúng timing
- Multiple retrieval → token cost tăng
- Kết quả retrieval vào context → context pollution
nếu retrieved content không relevant
Architecture: RAG như một Tool
Trong agent system, RAG phù hợp nhất khi được implement như một tool:
Tool: search_knowledge_base
input: { query: string, max_results: number }
output: relevant chunks với source references
LLM quyết định:
- Khi nào cần gọi (không phải mỗi turn)
- Query nào để dùng
- Có trust results không
Advantages:
- Agent không phải lúc nào cũng RAG
- Chỉ retrieve khi thực sự cần
- LLM có thể refine query nếu first retrieval kém
Trade-off: RAG vs Full Context
Full context injection:
+ Simple, reliable, no retrieval needed
+ LLM thấy full picture
- Limited bởi context window
- Expensive nếu knowledge lớn
RAG:
+ Handle knowledge base không giới hạn
+ Chỉ inject relevant content
- Retrieval quality là bottleneck
- Thêm latency (retrieval step)
- Thêm infrastructure (vector DB, embedding model)
- Có thể miss relevant content nếu retrieval kém
Decision Framework
Knowledge base > 100,000 tokens?
No → Inject vào system prompt, skip RAG
Yes → Continue
Knowledge thay đổi thường xuyên?
No và stable → Inject static, refresh thủ công
Yes → Continue
Retrieval quality có thể đảm bảo?
No → Fix chunking/embedding trước khi deploy
Yes → Implement RAG
Query intent có thể map sang vector space?
No → Consider keyword search hoặc structured retrieval
Yes → Vector RAG phù hợp
Kết luận
- RAG shift vấn đề từ context size sang retrieval quality — không solve, shift.
- Dùng RAG khi: knowledge base lớn (>50K tokens), thay đổi thường xuyên, LLM không có trong training data.
- Không dùng RAG khi: knowledge nhỏ, stable, hoặc retrieval quality khó đảm bảo.
- Chunking strategy quyết định retrieval quality — chunk theo semantic unit, không theo character count.
- Trong agent, RAG phù hợp nhất khi implement như một tool mà LLM gọi khi cần.
- Infrastructure của RAG (vector DB, embedding model, re-ranking) là cost thực — evaluate trước khi commit.