Thách Thức Của Quản Lý Ngữ Cảnh Trong AI Agents
Các AI agents xử lý các nhiệm vụ phức tạp, nhiều bước thường gặp khó khăn với exploding context windows. Khi các cuộc trò chuyện kéo dài qua nhiều lượt, lịch sử tích lũy làm phình to input, dẫn đến chi phí cao hơn, phản hồi chậm hơn và hiệu suất suy giảm. Tokens tích tụ từ các hướng dẫn lặp lại, reasoning traces trước đó, tool calls và observations, khiến các mô hình khó tập trung vào trạng thái hiện tại.
Vấn đề này đặc biệt nổi bật trong các agentic workflows nơi các agents lặp qua các chu kỳ planning, execution và reflection. Không có quản lý thông minh, các agents mất hiệu quả và có thể hallucinate hoặc lặp lại lỗi do thông tin liên quan bị pha loãng.
Các Nguyên Tắc Cốt Lõi Cho Context Engineering
Để xây dựng các agents đáng tin cậy, hãy áp dụng các thực hành nền tảng sau:
- Minimize Redundancy: Tránh gửi lại các yếu tố tĩnh như system prompts hoặc initial instructions ở mọi lượt.
- Prioritize Relevance: Chỉ bao gồm lịch sử cần thiết cho quyết định hiện tại.
- Structure Data Efficiently: Sử dụng các định dạng như JSON hoặc markdown để làm thông tin dễ quét.
- Leverage External Storage: Offload dữ liệu không quan trọng sang vector stores, files hoặc databases.
Các nguyên tắc này hình thành nền tảng của thiết kế agent hiệu quả, cho phép các tương tác kéo dài hơn mà không có performance cliffs.
Technique 1: Implement Agent State Checkpointing
Một cách tiếp cận mạnh mẽ là duy trì một "agent state" rõ ràng—một bản tóm tắt gọn gàng của các yếu tố chính kéo dài qua các lượt. Điều này thay thế chat history dài dòng bằng một structured snapshot.
Why It Works
Checkpointing captures:
- Current task hoặc goal
- Completed steps và outcomes
- Pending actions
- Key observations hoặc learnings
Điều này giữ context gọn nhẹ (thường dưới 1k tokens) trong khi giữ lại thông tin thiết yếu.
Step-by-Step Implementation
-
Define the State Schema: Sử dụng một JSON object với các fields như
goal,plan,completed_steps,observationsvànext_action. -
Update State Dynamically: Sau mỗi agent cycle, parse response và merge thông tin mới vào state.
-
Inject State into Prompts: Prefix mọi tin nhắn mới với serialized state.
Dưới đây là ví dụ Python thực tế sử dụng Anthropic's SDK. Xem demo đầy đủ trong Anthropic Tools repo hoặc Jupyter notebook.
import json
from typing import Dict, Any
from anthropic import Anthropic
class AgentState:
def __init__(self):
self.goal: str = ""
self.plan: list[str] = []
self.completed_steps: list[Dict[str, Any]] = []
self.observations: list[str] = []
self.pending_tools: list[str] = []
def to_prompt(self) -> str:
return json.dumps({
"goal": self.goal,
"plan": self.plan,
"completed_steps": self.completed_steps,
"observations": self.observations,
"pending_tools": self.pending_tools
}, indent=2)
def update_from_response(self, response: str):
# Parse agent's output to update state
# Example logic: extract completed steps, new observations
pass
# Usage in agent loop
client = Anthropic()
state = AgentState()
state.goal = "Research and summarize latest AI agent trends"
while not state.goal_achieved():
prompt = f"""Current state: {state.to_prompt()}
Continue the task based on this state."""
response = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
state.update_from_response(response.content[0].text)
Mô hình này mở rộng cho các ứng dụng thực tế như research agents hoặc code generators. Trong các bài kiểm tra, nó giảm context 80% trong khi duy trì task success rates.
Technique 2: Selective Memory and Pruning
Không phải tất cả lịch sử đều quan trọng như nhau. Implement selective persistence để chỉ giữ lại high-value traces.
Criteria for Retention
- Success Patterns: Giữ traces nơi tools thành công hoặc insights được thu được.
- Error Lessons: Lưu failures kèm resolutions để tránh lặp lại.
- Recent Context: Ưu tiên các cycles gần nhất.
- Semantic Relevance: Sử dụng embeddings để filter các past states tương tự.
Practical Steps
- Log All Traces: Lưu full interactions bên ngoài.
- Score and Rank: Gán scores dựa trên utility (ví dụ: novelty, impact).
- Prune Aggressively: Giới hạn ở top-K items mỗi category.
Ví dụ pruning function:
def prune_memory(memory: list[Dict], max_items: int = 5) -> list[Dict]:
# Score by length, tool usage, outcome
scored = [(item, score(item)) for item in memory]
scored.sort(key=lambda x: x[1], reverse=True)
return [item for item, _ in scored[:max_items]]
Điều này thêm một lớp intelligence, làm cho agents adaptive theo thời gian.
Technique 3: Hierarchical Task Decomposition
Phân tích các goals phức tạp thành sub-tasks với independent contexts. Một top-level orchestrator quản lý high-level state, trong khi sub-agents xử lý narrow scopes.
Structure Overview
- Level 1: Orchestrator – Giám sát tiến độ, delegates sub-tasks.
- Level 2: Sub-Agents – Focused contexts cho research, coding, v.v.
- Communication: Summaries flow up; states stay isolated.
Lợi ích: Parallelism, fault isolation và context efficiency.
Ứng dụng thực tế: Trong một software dev agent, một sub-agent plans architecture (small context), một sub-agent khác implements modules (fresh context per file).
class HierarchicalAgent:
def __init__(self):
self.orchestrator_state = AgentState()
self.sub_agents = {"research": AgentState(), "code": AgentState()}
def run(self):
# Orchestrator delegates
sub_response = self.sub_agents["research"].execute_task("Gather data")
self.orchestrator_state.observations.append(sub_response.summary)
Technique 4: Tool-Integrated Memory
Enhance tools để read/write agent state trực tiếp. Anthropic's tool use hỗ trợ điều này natively.
Define tools như read_state và write_state:
{
"name": "update_state",
"description": "Update the agent state with new info",
"input_schema": {
"type": "object",
"properties": {
"completed_steps": {"type": "array"},
"observations": {"type": "array"}
}
}
}
Agents self-manage state qua tools, giảm orchestration code của bạn.
Advanced Tips and Best Practices
- Compression Techniques: Tóm tắt long observations bằng secondary model call.
- Versioned States: Track state diffs cho debugging.
- Hybrid Approaches: Kết hợp với RAG cho external knowledge.
- Monitoring: Log token usage per turn để iterate.
Evaluation Metrics
- Context length over time
- Task completion rate
- Cost per task
- Latency
Trong benchmarks, các phương pháp này cắt giảm chi phí 5-10x cho hour-long sessions.
Getting Started
Fork Anthropic agent state example và adapt nó. Bắt đầu đơn giản: checkpoint một research agent, sau đó layer on hierarchy.
Bằng cách mastering context engineering, bạn sẽ deploy các agents xử lý real production workloads một cách đáng tin cậy và kinh tế.
<div style="text-align: center; margin-top: 2rem;"> <a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">Xem Tài Nguyên Đầy Đủ</a> </div>Stay ahead of the AI curve
The most important updates, news, and content — delivered in one weekly newsletter.