← 研究笔记
工具输出的成本超乎预期:用 headroom 减少 token

工具输出的成本超乎预期:用 headroom 减少 token

我在阻断网络的情况下测试了 headroom,并在将智能体工具输出发送给 LLM 之前对其进行压缩。纯文本没有节省 token;JSON 则减少了 52.9% 的 token。

本文涉及的仓库

headroomlabs-ai/headroom

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

59.4k Python Apache License 2.0

编程智能体读取搜索结果或构建日志时,文本本身就会产生成本。文件列表、重复的日志以及结构相似的 JSON 响应,都会增加这项成本。智能体会把完整的输出传给 LLM。额外的工具输出成本可能高于标价。headroom 会在 LLM 收到输出之前对其进行压缩。我安装了这个库,并测量了压缩带来的减少量。

headroom 是一个 Python 库,会在 LLM 收到工具输出、日志和 RAG 分块之前对其进行压缩,从而减少 token 用量。该项目以 Apache 2.0 License (*1) 发布源代码。

1. 安装

FROM python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'headroom-ai==0.31.0'
ENV TIKTOKEN_CACHE_DIR=/opt/tiktoken-cache
RUN python -c "import tiktoken; tiktoken.encoding_for_model('gpt-4o')"
WORKDIR /work
podman build -t headroom-sandbox .

依赖项使用的分词器(tiktoken)在首次使用时,会通过网络为每个模型名称获取编码定义。在构建过程中网络可用时,我调用了一次,并将 TIKTOKEN_CACHE_DIR 设置为固定路径。没有这个缓存,离线运行就无法获取定义,因此压缩过程无法运行。

2. 遇到阻碍:纯文本无法压缩

我先从重复的纯文本开始。

from headroom import compress

noisy = "\n".join(
    f"[INFO] step {i}: processing item_{i} status=ok elapsed_ms={100+i}"
    for i in range(400)
)
result = compress([{"role": "user", "content": noisy}], model="gpt-4o")
print(f"tokens_saved={result.tokens_saved}")
print(f"compression_ratio={result.compression_ratio:.3f}")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
  -e HEADROOM_OFFLINE=1 -e HEADROOM_TELEMETRY=off -e HEADROOM_UPDATE_CHECK=off \
  -v "$(pwd)":/work -w /work headroom-sandbox python demo.py

-v 选项让容器可以读写指定目录。请在为本实验预留的空目录中运行这条命令。HEADROOM_OFFLINE=1 告诉 headroom 禁用所有后台网络流量,包括更新检查。请将它与 --network none 一起使用,作为第二道保障。

命令输出如下:

tokens_saved=0
compression_ratio=0.000

结果显示没有节省 token。代码按原样正常运行,问题在于输入的形态。headroom 的文档将核心压缩器 SmartCrusher 描述为面向由字典组成的 JSON 数组。它不会检测任意纯文本中的重复内容。我需要测试智能体工具输出实际使用的格式:来自搜索结果和 API 响应的 JSON 数组。

3. 尝试压缩 JSON 数组

我改用一个 JSON 数组,模拟工具输出中反复出现的结构。

import json
from headroom import compress

records = [
    {"path": f"src/module_{i}/handler.py", "line": 42, "status": "ok", "size_bytes": 1024 + i}
    for i in range(300)
]
tool_output = json.dumps(records)

result = compress([{"role": "tool", "content": tool_output}], model="gpt-4o")
print(f"original_chars={len(tool_output)}")
print(f"tokens_saved={result.tokens_saved}")
print(f"compression_ratio={result.compression_ratio:.3f}")

我在阻断网络的情况下运行了同一条 podman run 命令。命令输出如下:

original_chars=25990
tokens_saved=5086
compression_ratio=0.529

这 300 条记录具有近乎相同的结构,结果显示 token 数量减少了 52.9%。我保留了 --network none,测试没有额外调用 LLM API。压缩器完全依靠本地结构分析。

除了核心压缩器之外,headroom 还包含一个专用于代码的压缩器,通过 AST 分析支持多种语言,此外还提供图像压缩,以及多个智能体之间的上下文共享。这次试验测量的是核心压缩器的压缩效果。

在传给 LLM 之前裁剪工具输出

在决定智能体应该读取什么之前,我会同时查看输入的形态和内容。同样的信息,作为纯文本传给 LLM,还是先为压缩做准备,所消耗的 token 数可能不同。你可以增加一步,在把工具输出传给 LLM 之前先对其进行裁剪。

来源

*1 headroom (GitHub), https://github.com/headroomlabs-ai/headroom, Apache 2.0 License