Context Engineering cho LLM: Kỹ Thuật Thiết Kế Ngữ Cảnh

Context Engineering là gì?

Context Engineering là kỷ luật thiết kế, quản lý và tối ưu hóa ngữ cảnh (context) đầu vào cho Large Language Model (LLM) để đạt kết quả chính xác, nhất quán và kiểm soát được. Khác với Prompt Engineering tập trung vào câu hỏi đơn lẻ, Context Engineering xử lý toàn bộ chuỗi thông tin: system prompt, few-shot examples, retrieval-augmented context (RAG), conversation history, tool outputs, và memory state.

Nói đơn giản: Prompt Engineering hỏi “viết prompt nào hay nhất”. Context Engineering hỏi “bao nhiêu thông tin, từ đâu, sắp xếp thế nào, khi nào thêm/bớt để model cho output tốt nhất”.

Tại sao Context Engineering quan trọng?

LLM không “biết” sự thật — chúng chỉ dự đoán token tiếp theo dựa trên distribution điều kiện trên context. Context chất lượng thấp (noisy, irrelevant, contradictory) dẫn đến hallucination, reasoning lỗi, hoặc refusal. Research từ AnthropicBerkeley cho thấy context design ảnh hưởng lớn hơn model size đối với nhiều task thực tế.

Ví dụ thực tế: một chatbot hỗ trợ khách hàng với context chỉ chứa system prompt sẽ trả lời chung chung. Thêm customer history, recent tickets, và product docs vào context — output trở nên chính xác và hữu ích hơn gấp nhiều lần, thậm chí dùng model nhỏ hơn.

Minh họa pipeline context engineering gồm system prompt + RAG retrieval + conversation history + too
Minh họa pipeline context engineering gồm system prompt + RAG retrieval + conversation history + tool output feed vào LLM

Các thành phần cốt lõi của Context Engineering

  1. System Prompt / Instruction Hierarchy: Định nghĩa role, constraints, output format, tool schemas. Dùng hierarchical prompting (system > developer > user) để ưu tiên an toàn. System prompt tốt không chỉ nói model “làm gì” mà còn nói “không làm gì” — ví dụ: “Không bao giờ tiết lộ internal tools names. Luôn dùng structured JSON response.”
  2. Retrieval-Augmented Context (RAG): Chunking strategy, embedding model, reranking, context window budget allocation. Hybrid search (dense + sparse) thường vượt dense-only. Thay vì lấy top-10 chunks, hãy rank theo relevance score và chỉ lấy chunks thực sự liên quan — chất lượng hơn số lượng.
  3. Conversation History Management: Summarization, sliding window, importance scoring. Tránh context overflow và lost-in-the-middle. Một chat 50 turns cũ có thể summarizes thành 3 bullet points thay vì giữ toàn bộ 50 messages.
  4. Tool / Function Calling Schema: JSON Schema chặt chẽ, few-shot tool use examples, error handling loops. Schema rõ ràng giúp model gọi đúng tool, đúng parameters. Ví dụ: schema “search_web” với required “query” + “limit” thay vì optional rỗng.
  5. Memory / State: Episodic (conversation history), semantic (facts about user/project), procedural (how-to knowledge). External vector DB hoặc graph memory cho long-horizon agents. Memory cần version control: fact mới override fact cũ, resolve conflicts tự động.

Kỹ thuật nâng cao

Context Compression

Khi context vượt window limit: selective retrieval (chỉ lấy relevant chunks), summarization (LLM tóm tắt history), token pruning (loại bỏ stopwords, duplicate info). LLMLingua compress 20x với less than 2% performance drop. Trong production, kết hợp summarization per-turn với rolling window là practical — giữ 3 turns gần nhất đầy đủ, tóm tắt turns older.

Dynamic Context Assembly

Thay vì fixed template, assemble context per-query: route query → select relevant tools/memory/retrievers → build minimal sufficient context. Ví dụ: query “triển khai Flask app trên EC2” cần code examples + AWS docs + user’s existing infrastructure, trong khi query “Flask là gì” chỉ cần overview docs.

LangGraphAutoGen hỗ trợ pattern này với graph-based workflow.

Context Evaluation & Observability

Metrics quan trọng: context relevance (precision@k của retrieval), answer faithfulness (claims grounded trong context), token efficiency (output quality per input token). Tools hỗ trợ: Ragas, TruLens, Phoenix.

Biểu đồ so sánh token usage vs accuracy giữa fixed context và dynamic context assembly cho productio
Biểu đồ so sánh token usage vs accuracy giữa fixed context và dynamic context assembly cho production LLM apps

Few-shot Strategy Optimization

Chọn examples cho few-shot không phải ngẫu nhiên. Research cho thấy: examples gần distribution của query hơn → output tốt hơn. Ví dụ: query về JavaScript error → few-shot example cũng nên là JavaScript error debug, không phải Python error debug. Davison et al. dùng nearest-neighbor selection để auto-select examples.

Context Window Budgeting

Mỗi component trong context competition lẫn nhau cho token space. Framework budgeting:

  • System prompt: 200-800 tokens (depends on task complexity)
  • Tool schemas: 500-2000 tokens (nếu dùng function calling)
  • RAG context: 2000-8000 tokens (max_per_query, không always top-20 chunks)
  • Conversation history: 1000-4000 tokens (summarized older turns)
  • Reserve for output: 1000-4000 tokens

Best Practices thực chiến

  • Budget tokens explicitly: Gán quota cho từng component (system=500, RAG=3000, history=1500, tools=1000). Theo dõi token usage mỗi request, alert nếu vượt quota.
  • Structure over prose: Dùng XML/JSON tags (<context>, <example>, <constraint>) thay vì natural language rambling — model parse structure tốt hơn 30-40% theo research.
  • Few-shot grounded in retrieved docs: Examples phải dùng cùng format và domain với retrieved context, tránh distribution shift.
  • Iterative refinement loop: LLM self-critique context → identify gaps → retrieve more → re-assemble. Self-RAG pattern cho phép model decide khi nào cần thêm context.
  • Guardrails at context level: PII redaction, toxicity filter, competitor mention block — apply trước khi feed vào model, không rely vào post-processing.
  • Test với adversarial queries: Send “bỏ qua hướng dẫn trên” queries để verify context defense không bypass dễ dàng.

Context Engineering vs Prompt Engineering vs RAG

Khía cạnh Prompt Engineering RAG Context Engineering
Scope Single prompt Retrieval pipeline End-to-end context lifecycle
Stateful Không Có (index) Có (memory + history)
Dynamic Hiếm Query-time Per-turn adaptive
Evaluation Vibe check Retrieval metrics Full pipeline observability
Real-world analogy Viết câu hỏi hay Tìm tài liệu đúng Chuẩn bị cuộc họp hoàn chỉnh

Tools & Frameworks phổ biến

  • LangGraph / LangChain: Graph-based context assembly, checkpointing, human-in-the-loop.
  • LlamaIndex: Data connectors, index structures, query engines. Rất tốt cho retrieval pipeline.
  • AutoGen / CrewAI: Multi-agent context passing, shared memory giữa agents.
  • DSPy: Programmatic prompt optimization, signature-based modules — thay hand-crafted prompt bằng auto-optimized prompt.
  • OpenAI Assistants API / Anthropic Messages API: Built-in thread management + file search + code interpreter — abstract context layer của platform.
  • Mem0: Memory layer cho AI agents, tự động extract và retrieve facts quan trọng từ conversations.

Thách thức hiện tại

  • Context window vs cost trade-off: 128k-1M token windows đắt và chậm; compression chất lượng chưa đủ tin cậy cho high-stakes applications.
  • Lost-in-the-middle: Model bỏ qua middle context segments — cần position-aware retrieval strategies, ưu tiên beginning/end cho critical information.
  • Cross-turn consistency: Memory updates có thể conflict; cần versioning và conflict resolution — ví dụ user thay đổi email, old fact phải update không phải append.
  • Evaluation benchmark thiếu: Chưa có standard benchmark cho context engineering quality, khác với MMLU hay HumanEval cho model capabilities.
  • Debugging opacity: Khó biết chính xác phần nào trong context gây ra bad output — cần observability tool để trace và audit.

Kết luận

Context Engineering là layer abstraction tiếp theo sau Prompt Engineering. Team build LLM app production nên đầu tư: (1) context observability từ ngày 1, (2) modular context assembly pipeline, (3) evaluation loop liên tục. Model sẽ ngày càng mạnh, nhưng context chất lượng thấp vẫn cho output rác — “garbage in, garbage out” vẫn đúng trong kỷ nguyên LLM.

Nguồn tham khảo: Anthropic Constitutional AI, Berkeley LLM Compilation, LLMLingua, Ragas, Self-RAG, Structure prompting research, Davison few-shot selection

Tôi là một lập trình viên IOS. Code chính là IOS nhưng thỉnnh thoảng vẫn đá sang Android hoặc web. Mặc dù không quá thông thạo nhưng tôi sẽ chia sẻ những kiến thức mà mình đã tìm hiểu, áp dụng qua.

Bài viết liên quan

Mixture of Experts (MoE): Kiến trúc token routing cho LLM

Mixture of Experts (MoE) là gì? Kiến trúc AI token routing Mixture of Experts (MoE) là kỹ thuật học máy trong đó nhiều mạng “chuyên gia” (expert) phối hợp xử…

Xem thêm

Graph Neural Network là gì? Hướng dẫn học máy trên dữ liệu đồ thị

Graph Neural Network là gì? Mạng nơ-ron đồ thị (Graph Neural Network) — các node biểu diễn thực thể, cạnh biểu diễn mối quan hệ, dùng để học biểu diễn…

Xem thêm

Speculative Decoding: Kỹ thuật tăng tốc LLM lên 3 lần

Speculative Decoding: Kỹ thuật tăng tốc LLM lên 3 lần Speculative decoding là kỹ thuật tăng tốc sinh văn bản của mô hình ngôn ngữ lớn (LLM) bằng cách dùng…

Xem thêm
0 0 đánh giá
Article Rating
Theo dõi
Thông báo của
guest
0 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất