OpenClaw lightContext指南:少烧Token,多办事
上下文窗口是AI Agent的命脉,也是钱包的出血点。lightContext模式就像给你的Agent开了"省油模式"——同样跑100公里,油耗砍掉一半。
💡 lightContext是什么
lightContext是OpenClaw的一种运行模式,通过精简上下文来降低Token消耗和响应延迟。适用于简单、重复、标准化的任务场景。
对比标准模式
| 特性 | 标准模式 | lightContext模式 |
|---|---|---|
| 上下文加载 | 完整会话历史+所有Skills | 核心指令+当前Skill |
| Token消耗 | 高 | 低(减少40-60%) |
| 响应速度 | 标准 | 快(提升30-50%) |
| 任务复杂度 | 支持复杂多步任务 | 适合单一明确任务 |
| 上下文感知 | 完整记忆 | 最小化记忆 |
⚡ 启用lightContext
# 配置文件启用
# openclaw.yaml
agent:
lightContext: true
# 运行时启用
openclaw gateway start --light-context
# 特定Skill启用
openclaw skill run my-skill --light-context
# cron任务启用
# 在cron配置中:
payload:
kind: "agentTurn"
message: "执行每日报告"
lightContext: true
Agent级别配置
# openclaw.yaml
agents:
- name: "fast-responder"
model: "gpt-4o-mini"
lightContext: true
toolsAllow: ["web_search", "web_fetch"]
- name: "deep-thinker"
model: "claude-sonnet-4-20250514"
lightContext: false
thinking: "high"
⚙️ 工作原理
lightContext通过以下方式精简上下文:
1. 历史消息压缩
只保留最近N条消息,而非完整会话历史。旧消息按优先级选择性保留摘要。
2. Skills按需加载
不预加载所有Skills的SKILL.md,仅在触发时加载当前任务相关的Skill。
3. System Prompt精简
使用精简版的系统指令,移除冗长的背景说明和示例。
4. 工具权限限制
只暴露任务必需的工具,减少工具列表的Token占用。
# lightContext模式下的上下文结构
{
"system": "精简版指令(~500 tokens)",
"skills": ["当前任务Skill(~300 tokens)"],
"tools": ["必需工具列表(~100 tokens)"],
"messages": ["最近3条消息(~500 tokens)"],
"total": "~1400 tokens"
}
# 标准模式的上下文结构
{
"system": "完整指令(~2000 tokens)",
"skills": ["所有Skills(~5000 tokens)"],
"tools": ["全部工具(~500 tokens)"],
"messages": ["完整历史(~3000 tokens)"],
"total": "~10500 tokens"
}
🎯 适用场景
✅ 推荐使用lightContext
- 定时任务(cron jobs)- 标准化、重复性任务
- 简单查询 - "今天天气"、"翻译这句话"
- 快速响应场景 - 需要低延迟的交互
- 成本敏感场景 - 大量简单请求
- 独立子任务 - 无需上下文记忆的任务
❌ 不推荐使用lightContext
- 复杂多步任务 - 需要记住之前步骤
- 长对话场景 - 客服、咨询类应用
- 创意写作 - 需要丰富的上下文参考
- 调试排错 - 需要完整的执行历史
- 跨任务协作 - 多个任务之间有依赖关系
📝 配置参数详解
# openclaw.yaml - lightContext完整配置
lightContext:
# 是否启用
enabled: true
# 保留的历史消息数量
maxMessages: 3
# 是否压缩旧消息为摘要
compressHistory: true
# Skills加载策略:on-demand | all | none
skillLoading: "on-demand"
# 工具白名单(仅暴露这些工具)
toolsAllow: ["web_search", "web_fetch", "write"]
# 是否启用记忆检索
memoryRetrieval: false
# 最大上下文Token数
maxContextTokens: 2000
# 是否保留用户画像
keepUserPersona: true
📊 性能对比
基于1000次相同任务的测试数据:
| 指标 | 标准模式 | lightContext | 提升 |
|---|---|---|---|
| 平均Token消耗 | 8,500 | 3,200 | -62% |
| 平均响应时间 | 4.2秒 | 2.1秒 | -50% |
| 单次请求成本 | $0.017 | $0.006 | -65% |
| 成功率 | 99.8% | 99.6% | ≈ |
测试任务:简单信息查询类任务,模型为claude-sonnet-4-20250514
✨ 最佳实践
混合模式策略
根据任务类型动态切换模式:
# openclaw.yaml - 模型路由配置
models:
routing:
# 简单任务 → lightContext + 快模型
- trigger: "翻译|总结|查询|搜索"
model: "gpt-4o-mini"
lightContext: true
# 复杂任务 → 标准模式 + 强模型
- trigger: "代码|分析|设计|创作"
model: "claude-sonnet-4-20250514"
lightContext: false
定时任务优化
# cron任务默认使用lightContext
cron:
jobs:
- name: "daily-report"
schedule: { kind: "cron", expr: "0 8 * * *" }
payload:
kind: "agentTurn"
message: "生成每日报告"
lightContext: true
model: "gpt-4o-mini"
监控与调优
- 监控Token消耗,评估lightContext效果
- 对比两种模式的任务成功率
- 根据实际场景调整maxMessages参数
- 定期审查toolsAllow白名单是否合理