Context Engineering
Quản lý context window hiệu quả — tránh poisoning, distraction và context overload
Context Engineering Là Gì?
Context Engineering = nghệ thuật quản lý thông tin trong context window của LLM. Agent càng phức tạp, context càng lớn và càng khó quản lý.
Prompt Engineering là craft một prompt tốt. Context Engineering là thiết kế hệ thống quản lý toàn bộ thông tin agent nhận được.
Các Loại Context
| Loại | Mô tả | Ví dụ |
|---|---|---|
| System | Instructions cố định | System prompt, role, rules |
| User | Input từ người dùng | Messages, files, preferences |
| Tool Results | Kết quả từ tool calls | API responses, DB queries |
| Memory | Info từ past interactions | Conversation history, user profile |
| Scratchpad | Working notes | Agent’s internal reasoning |
Chiến Lược Quản Lý Context
1. Agent Scratchpad
Agent lưu “ghi chú nháp” để tổ chức suy nghĩ:
import { generateText, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod";
let scratchpad: string[] = [];
const addNote = tool({
description: "Lưu ghi chú quan trọng vào scratchpad để tham khảo sau",
parameters: z.object({
note: z.string(),
category: z.enum(["fact", "question", "decision", "todo"])
}),
execute: async ({ note, category }) => {
scratchpad.push(`[${category}] ${note}`);
return { saved: true, totalNotes: scratchpad.length };
}
});
const result = await generateText({
model: openai("gpt-4o"),
system: `Bạn là research agent. Sử dụng scratchpad để tổ chức thông tin.
Ghi chú mọi thông tin quan trọng trước khi kết luận.
Current scratchpad:
${scratchpad.join("\n")}`,
tools: { addNote, searchWeb },
maxSteps: 10,
prompt: "Nghiên cứu về AI agent frameworks trends 2025"
});
2. Context Summarization
Khi context quá dài, tóm tắt để giữ trọng tâm:
async function summarizeContext(
messages: Message[],
maxTokens: number = 2000
): Promise<string> {
const tokenCount = estimateTokens(messages);
if (tokenCount < maxTokens) {
return messages.map(m => m.content).join("\n");
}
// Tóm tắt messages cũ, giữ messages gần đây
const oldMessages = messages.slice(0, -5);
const recentMessages = messages.slice(-5);
const { text: summary } = await generateText({
model: openai("gpt-4o-mini"),
prompt: `Tóm tắt ngắn gọn cuộc hội thoại sau, giữ lại thông tin quan trọng:
${oldMessages.map(m => `${m.role}: ${m.content}`).join("\n")}`
});
return `[Tóm tắt lịch sử]: ${summary}\n\n[Gần đây]:\n${recentMessages.map(m => m.content).join("\n")}`;
}
3. Multi-Agent Context Sharing
Trong hệ thống multi-agent, mỗi agent có context riêng. Chia sẻ context cần có chọn lọc:
interface SharedContext {
facts: string[]; // Thông tin đã xác minh
decisions: string[]; // Quyết định đã đưa ra
constraints: string[]; // Ràng buộc
}
async function passContext(
fromAgent: string,
toAgent: string,
fullContext: Message[]
): Promise<SharedContext> {
const { object } = await generateObject({
model: openai("gpt-4o-mini"),
schema: z.object({
facts: z.array(z.string()),
decisions: z.array(z.string()),
constraints: z.array(z.string())
}),
prompt: `Trích xuất thông tin quan trọng từ context của ${fromAgent} để pass cho ${toAgent}:
${fullContext.map(m => m.content).join("\n")}`
});
return object;
}
4. Tool Loadout Management
Quá nhiều tools = agent bị confused. Research cho thấy < 30 tools là tối ưu:
// Thay vì load TẤT CẢ tools
const allTools = { tool1, tool2, /* ... */ tool50 };
// Chọn tools phù hợp cho từng task
async function selectTools(task: string) {
const { object } = await generateObject({
model: openai("gpt-4o-mini"),
schema: z.object({
selectedTools: z.array(z.string()).max(10)
}),
prompt: `Từ danh sách tools, chọn tối đa 10 tools phù hợp nhất cho task:
Task: ${task}
Available: ${Object.keys(allTools).join(", ")}`
});
return object.selectedTools.reduce((acc, name) => {
acc[name] = allTools[name];
return acc;
}, {});
}
Context Failures
1. Context Poisoning
Agent nhận thông tin sai → lưu vào memory → quyết định sai liên tục.
// Phòng tránh: Validate trước khi lưu
async function validateBeforeSaving(info: string, source: string) {
const { object } = await generateObject({
model: openai("gpt-4o-mini"),
schema: z.object({
isReliable: z.boolean(),
confidence: z.number(),
concerns: z.array(z.string())
}),
prompt: `Đánh giá độ tin cậy:
Thông tin: ${info}
Nguồn: ${source}`
});
if (object.isReliable && object.confidence > 0.7) {
await saveToMemory(info);
}
}
2. Context Distraction
Quá nhiều thông tin không liên quan → agent mất focus.
Giải pháp: Summarization định kỳ + relevant context filtering.
3. Context Confusion
Tools quá nhiều hoặc descriptions giống nhau → agent chọn tool sai.
Giải pháp: Tool loadout management + clear descriptions.
4. Context Clash
Thông tin mâu thuẫn từ nhiều sources.
Giải pháp: Conflict resolution + source ranking.
Tổng Kết
- Context Engineering > Prompt Engineering khi xây agents phức tạp
- Scratchpad giúp agent tổ chức suy nghĩ
- Summarization giữ context ngắn gọn và tập trung
- Tool loadout < 30 tools cho performance tối ưu
- Phòng tránh 4 failures: poisoning, distraction, confusion, clash