Context Window Management
Context Window Management 是在 LLM 有限的上下文窗口内最大化信息密度的工程实践,包括 token 预算分配、截断策略和压缩技术。
#type / concept
#status / evergreen
#tech / ai
[!info] related notes
Context Window Management
一句话定义
Context Window Management 是在 LLM 有限的上下文窗口(如 128K token)内最大化信息密度的工程实践。不是”把所有东西都塞进去”,而是”把最重要的东西放进去”。
核心原理
Token 预算分配
上下文窗口 (128K token) =
System Prompt (1-2K)
+ 用户画像 (0.5-1K)
+ 结构化状态 (1-2K)
+ 对话摘要 (0.5-1K)
+ 最近消息 (5-10K)
+ 检索知识 (3-5K)
+ 工具结果 (2-5K)
+ 当前用户输入 (0.5-1K)
+ 预留给输出 (4-8K)
─────────────────
总计: ~15-35K (远低于 128K)
Python 实现
class ContextWindowManager:
def __init__(self, max_tokens: int = 128000, output_reserve: int = 8000):
self.max_tokens = max_tokens
self.output_reserve = output_reserve
self.available_tokens = max_tokens - output_reserve
def allocate(self, components: dict[str, tuple[str, int]]) -> dict[str, str]:
"""
分配 token 预算
components: {"system_prompt": (content, max_tokens), ...}
"""
result = {}
remaining = self.available_tokens
# 按优先级分配
priority_order = [
"system_prompt", # 最高优先级
"current_input", # 当前用户输入
"structured_state", # 结构化状态
"recent_messages", # 最近消息
"retrieved_knowledge",# 检索知识
"tool_results", # 工具结果
"conversation_summary",# 对话摘要
"user_profile", # 用户画像
]
for key in priority_order:
if key in components:
content, max_alloc = components[key]
allocated = min(max_alloc, remaining)
if allocated > 0:
result[key] = self.truncate_to_token(content, allocated)
remaining -= self.count_tokens(result[key])
return result
def count_tokens(self, text: str) -> int:
"""估算 token 数(简化版)"""
return len(text) // 4 # 粗略估算
常见设计模式
1. 固定预算
每个组件分配固定的 token 上限。
2. 动态预算
根据对话阶段动态调整。信息收集阶段给工具结果更多空间,生成阶段给输出更多空间。
3. 优先级淘汰
token 不够时,按优先级从低到高淘汰。
常见坑
- 不做预算分配: 所有内容平均分配,重要的被截断
- 不留输出空间: 上下文填满了,LLM 没空间生成回答
- 不做 token 计数: 估算不准导致超限
- 不监控 token 使用: 不知道哪些组件占了多少 token