概述
Headroom (headroomlabs-ai/headroom) 是一个 AI agent 上下文压缩层(Context Compression Layer),能自动压缩 Agent 读取的 tool output、日志、文件等内容,在不影响准确性的前提下节省 60–95% 的输入 tokens。
本项目已成功集成到 OpenClaw 中,作为 ContextEngine 插件运行。
相关说明
- 仓库: github.com/headroomlabs-ai/headroom
- 文档: headroom-docs.vercel.app
- 许可证: Apache 2.0
[toc]
概述
Headroom 是一款 AI 代理的上下文压缩层。它位于 AI 代理与 LLM 之间(或作为代理的 ContextEngine 插件),实时压缩传递给大模型的内容——尤其是 tool call 的输出、搜索结果、代码库浏览、日志等——然后才送到 LLM。
核心原理
- 压缩不失真:对于不需要完全保真的内容(搜索结果列表、文件列表、JSON 数据等)进行摘要式压缩
- 代码和 grep 不压缩:Python 源码、grep 匹配行等重要内容保持原样
- 代理无关设计:支持 OpenClaw、Claude Code、Codex、Cline 等多种 Agent
安装与集成
安装 Headroom
pipx install "headroom-ai"
pipx inject "headroom-ai" "headroom-ai[proxy]"与 OpenClaw 集成
Headroom 通过 OpenClaw 的 ContextEngine 插件系统集成。
方式 A:从本地 npm 包安装(推荐)
# 构建 openclaw 插件(从 headroom repo)
cd /path/to/headroom/plugins/openclaw
npm install && npm run build
# 安装到 OpenClaw
openclaw plugins install /path/to/dist --force方式 B:自动集成(headroom wrap openclaw,可能需要 GitHub 连接)
headroom wrap openclaw⚠️
headroom wrap openclaw在某些环境可能失败(如私有 npm 仓库无法解析headroom-ai/openclaw规格)。推荐使用方式 A。
配置说明
集成后 openclaw.json 中会新增:
{
"plugins": {
"slots": { "contextEngine": "headroom" },
"entries": {
"headroom": {
"enabled": true,
"config": {
"proxyUrl": "http://127.0.0.1:8787",
"proxyPort": 8787,
"autoStart": false,
"pythonPath": "~/.local/share/uv/tools/headroom-ai/bin/python"
}
}
}
}
}❗ 插件配置只支持以下属性:
enabled、proxyUrl、proxyPort、autoStart、pythonPath。 不支持startupTimeoutMs、gatewayProviderIds。配置这些不支持属性会导致 OpenClaw 配置验证警告。
配置项说明
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
enabled | boolean | true | 是否启用插件 |
proxyUrl | string | http://127.0.0.1:8787 | Headroom Proxy 地址 |
proxyPort | number | 8787 | Proxy 端口 |
autoStart | boolean | false | 是否让 OpenClaw 自动启动 proxy(推荐 proxy 独立管理) |
pythonPath | string | — | Python 解释器路径(使用 uv 时:~/.local/share/uv/tools/headroom-ai/bin/python) |
启动 Proxy
方式一:手动启动(临时)
headroom proxy --port 8787方式二:使用自定义 API 上游
当上游是自定义 Anthropic 兼容 API 而非官方 api.anthropic.com 时:
ANTHROPIC_API_KEY="sk-..." headroom proxy \
--port 8787 \
--host 127.0.0.1 \
--anthropic-api-url "https://你的-api-地址"重要:
--anthropic-api-url必须通过 CLI 参数传入,环境变量ANTHROPIC_TARGET_API_URL可能不生效ANTHROPIC_API_KEY环境变量用于 proxy 自身的认证,但不会自动转发给上游- 客户端请求时必须显式传递
x-api-keyHeader,proxy 会透传到上游- 上游的 nginx/gateway 可能对请求格式有严格要求(如需要
anthropic-versionHeader)
端到端测试命令
# 获取 API Key
API_KEY="sk-..." # 替换为真实 key
# 测试 Proxy 转发
curl -s -X POST http://127.0.0.1:8787/v1/messages \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $API_KEY" \
-d '{"model":"claude-sonnet-4-6","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}'方式三:systemd 用户服务(开机自启 + 崩溃自动恢复,推荐)
# 1. 创建 service 文件
mkdir -p ~/.config/systemd/user/
cat > ~/.config/systemd/user/headroom-proxy.service << 'SERVICEOF'
[Unit]
Description=Headroom AI Context Compression Proxy
Documentation=https://github.com/nicholasgriffintn/headroom
After=network.target
[Service]
Type=simple
ExecStart=%h/.local/bin/headroom proxy \
--port 8787 \
--host 127.0.0.1 \
--anthropic-api-url https://你的-api-地址
Environment=ANTHROPIC_API_KEY=sk-你的-key
Restart=always
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/tmp
[Install]
WantedBy=default.target
SERVICEOF
# 2. 启用并启动(自定义 API 上游版本)
systemctl --user daemon-reload
systemctl --user enable headroom-proxy
systemctl --user start headroom-proxy
# 3. 验证
systemctl --user status headroom-proxy
curl http://localhost:8787/health💡 说明:
--anthropic-api-url:指定上游 API 地址(非官方时必填)Environment=ANTHROPIC_API_KEY:设置 API Key(用于 proxy 自身认证)Restart=always:崩溃后自动恢复(RestartSec=5延迟 5 秒)NoNewPrivileges+ProtectSystem=strict:安全加固- 如使用官方 API,可省略
--anthropic-api-url和--host 127.0.0.1- API Key 也可放在独立的 EnvironmentFile 中统一管理
bash# 用 EnvironmentFile 替代,便于 key 集中管理 mkdir -p ~/.config/headroom echo 'ANTHROPIC_API_KEY=sk-...' > ~/.config/headroom/env chmod 600 ~/.config/headroom/env # 然后在 service 中: EnvironmentFile=%h/.config/headroom/env
方式四:screen / tmux 保持后台运行(临时)
screen -dmS headroom headroom proxy --port 8787 --anthropic-api-url "https://..."压缩测试实例
自定义 API 上游实测(本机)
上游:https://claudecode-internal.geelib.360.cn,模型:claude-sonnet-4-6
| 负载类型 | 压缩前 | 压缩后 | 节省率 | 算法 |
|---|---|---|---|---|
| 50 条搜索结果(878 tokens) | 878 | 669 | 23.8% | router:text |
| 简短问候(9 tokens — 低于 min_tokens_to_crush) | 9 | 9 | 0% | router:noop |
本地端到端测试命令
# 1. 测试压缩效果(不转发请求)
curl -s -X POST http://127.0.0.1:8787/v1/compress \
-H "Content-Type: application/json" \
-d '{ "model": "claude-sonnet-4-6", "messages": [...] }'
# 2. 端到端请求(压缩 → 转发 → 获取回复)
curl -s -X POST http://127.0.0.1:8787/v1/messages \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $API_KEY" \
-d @request.json | python3 -c "
import json, sys
d = json.load(sys.stdin)
print(f'回复: {d["content"][0]["text"][:100]}...')
print(f'Input: {d["usage"]["input_tokens"]}, Output: {d["usage"]["output_tokens"]}')
"
# 3. 查看实时统计
curl -s http://127.0.0.1:8787/stats | python3 -c "
import json, sys
d = json.load(sys.stdin)
s = d.get('summary',{})
c = d.get('compression',{})
print(f'总API请求: {s.get(\"api_requests\",0)}')
print(f'压缩次数: {c.get(\"requests_compressed\",0)}')
print(f'总节省tokens: {c.get(\"total_tokens_removed\",0)}')
print(f'缓存条目: {d.get(\"compression\",{}).get(\"ccr_entries\",0)}')
"🔑 关键经验:
- Headroom proxy 的
ANTHROPIC_API_KEY环境变量不会自动转发为上游的x-api-keyHeader,客户端请求时需自行添加- 设置
--anthropic-api-url时必须用 CLI 参数而非环境变量- 使用
uv tool install安装后,二进制在~/.local/bin/headroom- 安装时省略
[ml]extras 可避免下载 GPU/CUDA 依赖- 上游若有 nginx 前置,可能需要
anthropic-versionHeader 才能正确路由
systemd 服务管理常用命令
# 查看状态
systemctl --user status headroom-proxy
# 查看实时日志
journalctl --user -u headroom-proxy -f -n 50
# 重启
systemctl --user restart headroom-proxy
# 停止
systemctl --user stop headroom-proxy
# 关闭开机自启
systemctl --user disable headroom-proxy
# 开机自启并自动登录(需启用 linger)
sudo loginctl enable-linger $USER注意:systemd user service 在用户未登录时不会自启。如果需要 headless 服务器场景(SSH 重启后无人登录),执行
sudo loginctl enable-linger $USER让服务在后台持续运行。
方式三:screen / tmux 保持后台运行
screen -dmS headroom headroom proxy --port 8787验证
curl -s http://localhost:8787/stats | python3 -m json.tool | grep api_requests压缩性能数据
通用压缩场景
| 场景 | 压缩前 (tokens) | 压缩后 (tokens) | 节省率 |
|---|---|---|---|
| Code search (100 results) | 17,765 | 1,408 | 92% |
| SRE incident debugging | 65,694 | 5,118 | 92% |
| GitHub issue triage | 54,174 | 14,761 | 73% |
| Codebase exploration | 78,502 | 41,254 | 47% |
按内容类型细分
| 内容类型 | 原始 tokens | 压缩后 | 节省率 | 延迟 |
|---|---|---|---|---|
| JSON array (100 items) | 3,163 | 297 | 90.6% | 1ms |
| JSON array (500 items) | 9,526 | 1,614 | 83.1% | 2ms |
| Shell output (200 lines) | 3,238 | 469 | 85.5% | 1ms |
| Build log (200 lines) | 2,412 | 148 | 93.9% | 1ms |
| Python source (~480 lines) | 2,958 | 2,958 | 0% (pass-through) | <1ms |
| grep results (150 hits) | 2,624 | 2,624 | 0% (pass-through) | <1ms |
准确性基准
| Benchmark | Baseline | Headroom | 差异 |
|---|---|---|---|
| GSM8K (数学) | 0.870 | 0.870 | ±0.000 |
| TruthfulQA | 0.530 | 0.560 | +0.030 |
| SQuAD (QA) | 97% | 97% | ±0% |
| BFCL (Function Call) | 32% | 19% | -13%(需关注) |
自定义 API 上游实测数据(2026-07-15)
上游:https://claudecode-internal.geelib.360.cn(定制 Anthropic 兼容 API)
| 负载 | 压缩前 | 压缩后 | 节省率 | 算法 | 说明 |
|---|---|---|---|---|---|
| 50 条搜索结果(结构化文本) | 878 | 669 | 23.8% | router:text | 中等负载,router:text 自动选择 |
| 简短问候 | 9 | 9 | 0% | router:noop | 短于 min_tokens_to_crush(25) |
关键配置
# 启动命令(自定义上游)
ANTHROPIC_API_KEY="sk-..." headroom proxy \
--port 8787 \
--host 127.0.0.1 \
--anthropic-api-url "https://claudecode-internal.geelib.360.cn"认证方式
| 方式 | 能否通过 Proxy | 说明 |
|---|---|---|
x-api-key Header | ✅ 透传 | Proxy 原样转发到上游,上游 nginx 验证 |
ANTHROPIC_API_KEY 环境变量 | ❌ 不转发 | 仅用于 Proxy 本地认证流程,不会加到请求 Header |
本地实测数据
在本地环境使用 Headroom proxy 对真实 API 负载的测试结果:
| 压缩策略 | 压缩次数 | 节省 tokens | 说明 |
|---|---|---|---|
| SmartCrusher (JSON) | 9 | 6,080 | 🏆 主力,JSON 智能压缩 |
| Kompress v2 (文本) | 2 | 974 | 通用文本压缩 |
| Log (日志) | 1 | 134 | 日志行压缩 |
| router:text | 1 | 209 | 自定义 API 上游实测,23.8% |
| text / code_aware / search | 13 | — | 小数据 pass-through |
合计:26 次压缩,节省 7,397 tokens(含自定义 API 测试数据)
自定义 API 部署经验总结
- CLI 参数 > 环境变量:
--anthropic-api-url必须 CLI 传入,ANTHROPIC_TARGET_API_URL环境变量不生效 x-api-key由客户端传递:Proxy 不会自动从ANTHROPIC_API_KEYenv var 取出填入请求 Headeruv tool install替代pipx:Debian 的 externally-managed Python 环境需用uv;二进制在~/.local/bin/headroom- 跳过 GPU 依赖:安装
headroom-ai[proxy](不加[ml]),避免 CUDA/torch 下载 - 验证上游健康:
curl http://127.0.0.1:8787/health→status=healthy, ready=true - systemd 最佳实践:
Restart=always+NoNewPrivileges=true+ProtectSystem=strict
压缩策略详解
| 策略 | 用途 | 说明 |
|---|---|---|
| SmartCrusher | JSON 数组 | 将长 JSON 列表压缩为摘要(保留关键字段),节省 80–90% 空间 |
| Kompress v2 | 通用文本 | 文本智能摘要,适合长文本段落 |
| text | 常规文本 | 基础文本压缩(短文本 pass-through) |
| code_aware | 代码 | 代码感知压缩(不做压缩,仅结构化处理) |
| search | 搜索结果 | 搜索结果摘要 |
| log | 日志 | 日志行去重与摘要 |
| tabular | 表格数据 | 结构化表格压缩 |
常用命令
# 查看 proxy 状态
headroom doctor
# 查看压缩统计数据
curl http://localhost:8787/stats | python3 -m json.tool
# 查看实时统计数据
curl http://localhost:8787/stats | python3 -c "
import json,sys
d = json.load(sys.stdin)
c = d.get('compressions_by_strategy', {})
t = d.get('tokens_saved_by_strategy', {})
total = sum(t.values())
print(f'总压缩: {sum(c.values())} 次')
print(f'总节省: {total} tokens')
"
# 查看 proxy 实时日志
journalctl --user -u headroom-proxy -n 50
# 重启 proxy
systemctl --user restart headroom-proxy
# 卸载
headroom unwrap openclaw实际使用收益(估算)
经 proxy 转发后,以 Claude Sonnet ($3/Mtok) 计算:
- 每次 code search 节省 ~16,000 tokens = $0.048
- 每次 SRE 调试节省 ~60,000 tokens = $0.18
- 日常使用可减少 40–80% 的输入 token 费用
注意:实际节省取决于工作负载中 tool output 的比例。代码密集型场景效果最好,短对话(<500 tokens)因
min_tokens_to_crush阈值设置会跳过压缩。