A developer ran Claude Code unattended over a weekend and woke up to a $400 API bill. A startup's RAG pipeline was quietly burning $2,000/month — not on LLM reasoning, but on context tokens. Tool outputs, retrieval chunks, log files — the LLM was reading everything at full price. The root cause isn't the model. It's context inflation. Headroom is the open-source middleware that compresses everything your AI agent reads before it reaches the LLM.
The 1M+ token context windows that shipped in 2025–2026 are a double-edged sword. Yes, your agent can read an entire codebase. But every turn of a multi-agent conversation re-sends the entire history — and costs grow quadratically:
| Turn | Tokens Sent | Cost (Sonnet) |
|---|---|---|
| Turn 1 | ~2K | $0.006 |
| Turn 10 | ~20K | $0.06 |
| Turn 50 | ~100K | $0.30 |
| Turn 100 | ~200K+ | $0.60+ per message |
The worst offenders aren't your prompts. They're tool outputs: a git diff returning 8,000 tokens of unchanged code, a database query result with 50 identical column headers, a test runner dumping 10,000 lines of passing tests to find one FATAL.
📊 Real demo result: Headroom compresses a test log from 10,144 → 1,260 tokens — the same FATAL error is found, at a fraction of the cost.
Headroom is an open-source context compression layer purpose-built for AI agents. It sits between your application and the LLM API, transparently compressing inputs before they're sent.
pip install "headroom-ai[all]" / npm install headroom-ai| Mode | Command | Use Case |
|---|---|---|
| Proxy | headroom proxy --port 8787 | Zero code changes, any language |
| Agent Wrap | headroom wrap claude | One-command for Claude/Cursor/Aider |
| Library | compress(messages) | Inline in Python or TypeScript |
| MCP Server | headroom mcp install | Any MCP-compatible client |
Headroom doesn't use a single strategy. It routes content through six specialized engines, each optimized for a different data type:
Handles the most common agent data: arrays of dictionaries, nested API responses, structured tool outputs. Removes redundant keys, normalizes whitespace, collapses repetitive structures.
Parses code via abstract syntax trees for Python, JavaScript, Go, Rust, Java, and C++. Strips comments, collapses irrelevant function bodies, preserves interfaces and type signatures.
A HuggingFace model trained specifically on agentic traces. Unlike generic text summarization, it understands tool call patterns, error stack traces, and agent reasoning chains.
A trained ML router achieves 40–90% reduction on images passed through vision-capable models, without degrading the information the LLM needs to reason about them.
The sleeper feature. When you compress a prompt, the text changes — which means Anthropic's and OpenAI's KV cache can't match the prefix anymore. CacheAligner restructures the compressed output to keep the prefix stable, so you get both compression savings and cache hit discounts. Double savings.
When a conversation exceeds the context window, IntelligentContext scores each message by learned importance and fits the highest-value content into the available budget.
Traditional prompt compression is lossy and one-way. Headroom's CCR (Compressed Context Recovery) keeps originals in a local store. If the LLM discovers it needs more detail, it calls headroom_retrieve to decompress specific sections on demand — like lazy-loading for context.
pip install "headroom-ai[all]"
headroom proxy --port 8787
# Point your AI tool's base URL to http://localhost:8787/v1
Works with Claude Code, Cursor, Aider, Copilot — anything that calls an OpenAI-compatible API.
headroom wrap claude # Wraps Claude Code
headroom wrap cursor # Wraps Cursor
headroom wrap aider # Wraps Aider
from headroom import withHeadroom
from anthropic import Anthropic
client = withHeadroom(Anthropic())
# All calls are now automatically compressed
response = client.messages.create(
model="claude-sonnet-4-20250514",
messages=[{"role": "user", "content": "Review this code"}]
)
headroom mcp install
# Registers: headroom_compress, headroom_retrieve, headroom_stats
| Framework | Integration |
|---|---|
| Anthropic / OpenAI SDK | withHeadroom(client) |
| LangChain | HeadroomChatModel(your_llm) |
| Vercel AI SDK | wrapLanguageModel({ middleware: headroomMiddleware() }) |
| LiteLLM | litellm.callbacks = [HeadroomCallback()] |
| Agno | HeadroomAgnoModel(your_model) |
| Feature | Headroom | RTK | lean-ctx | Manual |
|---|---|---|---|---|
| Scope | All context | CLI outputs | CLI+MCP | Conversation |
| Deploy | Proxy/lib/MCP | CLI wrapper | CLI rules | Code changes |
| Local | ✅ | ✅ | ✅ | N/A |
| Reversible | ✅ CCR | ❌ | ❌ | ❌ |
| ML-based | ✅ Kompress | ❌ | ❌ | ❌ |
| Cache-aware | ✅ CacheAligner | ❌ | ❌ | ❌ |
Context compression is becoming a standard layer in the AI agent stack — just like gzip became standard for HTTP. Headroom is the most complete open-source implementation: 6 algorithms, 4 deployment modes, reversible compression, cache-aware optimization, and integrations with every major framework. If you're spending more than $50/month on LLM API calls, the ROI is immediate.
Un desarrollador dejó Claude Code ejecutándose durante el fin de semana y despertó con una factura de API de $400. El pipeline RAG de una startup estaba quemando $2,000/mes silenciosamente — no en razonamiento del LLM, sino en tokens de contexto. Salidas de herramientas, fragmentos de recuperación, archivos de log — el LLM leía todo a precio completo. La causa raíz no es el modelo. Es la inflación de contexto. Headroom es el middleware de código abierto que comprime todo lo que tu agente IA lee antes de que llegue al LLM.
Las ventanas de contexto de 1M+ tokens que llegaron en 2025–2026 son un arma de doble filo. Sí, tu agente puede leer un código fuente completo. Pero cada turno de una conversación multi-agente reenvía todo el historial — y los costos crecen cuadráticamente.
Los peores infractores no son tus prompts. Son las salidas de herramientas: un git diff que devuelve 8,000 tokens de código sin cambios, un resultado de consulta con 50 encabezados de columna idénticos, un runner de tests volcando 10,000 líneas de tests exitosos para encontrar un solo FATAL.
📊 Resultado real: Headroom comprime un log de tests de 10,144 → 1,260 tokens — el mismo error FATAL encontrado, a una fracción del costo.
Headroom es una capa de compresión de contexto de código abierto diseñada específicamente para agentes IA. Se sitúa entre tu aplicación y la API del LLM, comprimiendo las entradas de forma transparente antes de enviarlas.
pip install "headroom-ai[all]"Headroom no utiliza una sola estrategia. Enruta el contenido a través de seis motores especializados, cada uno optimizado para un tipo de datos diferente:
CCR (Compressed Context Recovery) mantiene los originales en un almacén local. Si el LLM necesita más detalle, llama a headroom_retrieve para descomprimir secciones específicas bajo demanda.
pip install "headroom-ai[all]"
headroom proxy --port 8787
# Apunta la URL base de tu herramienta IA a http://localhost:8787/v1
headroom wrap claude # Envuelve Claude Code
headroom wrap cursor # Envuelve Cursor
headroom wrap aider # Envuelve Aider
from headroom import withHeadroom
from anthropic import Anthropic
client = withHeadroom(Anthropic())
# Todas las llamadas se comprimen automáticamente
headroom mcp install
# Registra: headroom_compress, headroom_retrieve, headroom_stats
| Característica | Headroom | RTK | lean-ctx | Manual |
|---|---|---|---|---|
| Alcance | Todo el contexto | Salidas CLI | CLI+MCP | Conversación |
| Local | ✅ | ✅ | ✅ | N/A |
| Reversible | ✅ CCR | ❌ | ❌ | ❌ |
| Basado en ML | ✅ | ❌ | ❌ | ❌ |
| Compatible con caché | ✅ | ❌ | ❌ | ❌ |
La compresión de contexto se está convirtiendo en una capa estándar en el stack de agentes IA — tal como gzip se convirtió en estándar para HTTP. Headroom es la implementación de código abierto más completa. Si gastas más de $50/mes en llamadas a APIs de LLM, el retorno de inversión es inmediato.
Ein Entwickler ließ Claude Code über das Wochenende unbeaufsichtigt laufen und erwachte mit einer API-Rechnung von 400 Dollar. Die RAG-Pipeline eines Startups verbrannte still und leise 2.000 Dollar pro Monat — nicht für LLM-Schlussfolgerungen, sondern für Kontext-Token. Tool-Ausgaben, Retrieval-Fragmente, Logdateien — das LLM las alles zum vollen Preis. Die Ursache ist nicht das Modell. Es ist die Kontextinflation. Headroom ist die Open-Source-Middleware, die alles komprimiert, was Ihr KI-Agent liest, bevor es das LLM erreicht.
Die 1M+-Token-Kontextfenster, die 2025–2026 verfügbar wurden, sind ein zweischneidiges Schwert. Ja, Ihr Agent kann eine gesamte Codebasis lesen. Aber jede Runde einer Multi-Agenten-Konversation sendet den gesamten Verlauf erneut — und die Kosten wachsen quadratisch.
Die größten Übeltäter sind nicht Ihre Prompts. Es sind die Tool-Ausgaben: Ein git diff, das 8.000 Token unveränderten Code zurückgibt, ein Datenbank-Abfrageergebnis mit 50 identischen Spaltenüberschriften, ein Test-Runner, der 10.000 Zeilen bestandener Tests ausgibt, um ein einziges FATAL zu finden.
📊 Reales Ergebnis: Headroom komprimiert ein Testlog von 10.144 → 1.260 Token — derselbe FATAL-Fehler wird gefunden, zu einem Bruchteil der Kosten.
Headroom ist eine Open-Source-Kontextkomprimierungsschicht, die speziell für KI-Agenten entwickelt wurde. Sie befindet sich zwischen Ihrer Anwendung und der LLM-API und komprimiert Eingaben transparent, bevor sie gesendet werden.
pip install "headroom-ai[all]"Headroom verwendet nicht eine einzige Strategie. Es leitet Inhalte durch sechs spezialisierte Engines, die jeweils für einen bestimmten Datentyp optimiert sind:
CCR (Compressed Context Recovery) bewahrt die Originale in einem lokalen Speicher. Wenn das LLM mehr Details benötigt, ruft es headroom_retrieve auf, um bestimmte Abschnitte bei Bedarf zu dekomprimieren.
pip install "headroom-ai[all]"
headroom proxy --port 8787
# Richten Sie die Basis-URL Ihres KI-Tools auf http://localhost:8787/v1
headroom wrap claude # Umhüllt Claude Code
headroom wrap cursor # Umhüllt Cursor
headroom wrap aider # Umhüllt Aider
from headroom import withHeadroom
from anthropic import Anthropic
client = withHeadroom(Anthropic())
# Alle Aufrufe werden jetzt automatisch komprimiert
headroom mcp install
# Registriert: headroom_compress, headroom_retrieve, headroom_stats
| Merkmal | Headroom | RTK | lean-ctx | Manuell |
|---|---|---|---|---|
| Umfang | Gesamter Kontext | CLI-Ausgaben | CLI+MCP | Konversation |
| Lokal | ✅ | ✅ | ✅ | N/A |
| Reversibel | ✅ CCR | ❌ | ❌ | ❌ |
| ML-basiert | ✅ | ❌ | ❌ | ❌ |
| Cache-kompatibel | ✅ | ❌ | ❌ | ❌ |
Kontextkomprimierung wird zur Standardschicht im KI-Agenten-Stack — genau wie gzip zum Standard für HTTP wurde. Headroom ist die umfassendste Open-Source-Implementierung. Wenn Sie mehr als 50 Dollar pro Monat für LLM-API-Aufrufe ausgeben, ist die Rendite sofort spürbar.
ある開発者がClaude Codeを週末放置したところ、400ドルのAPI請求書が届きました。あるスタートアップのRAGパイプラインは月額2,000ドルを消費していました——LLMの推論ではなく、コンテキストトークンに対してです。ツール出力、検索チャンク、ログファイル——LLMはすべてを定価で読んでいました。根本原因はモデルではありません。コンテキスト膨張です。Headroomは、AIエージェントが読むすべてをLLMに届く前に圧縮するオープンソースミドルウェアです。
2025〜2026年に登場した100万トークン以上のコンテキストウィンドウは諸刃の剣です。はい、エージェントはコードベース全体を読むことができます。しかし、マルチエージェント会話の各ターンで全履歴が再送信され、コストは二次関数的に増大します。
| ターン | 送信トークン数 | コスト(Sonnet) |
|---|---|---|
| ターン1 | 約2K | $0.006 |
| ターン10 | 約20K | $0.06 |
| ターン50 | 約100K | $0.30 |
| ターン100 | 約200K以上 | メッセージあたり$0.60以上 |
最大の要因はプロンプトではありません。ツール出力です:変更されていないコード8,000トークンを返すgit diff、50個の同一カラムヘッダーを持つデータベースクエリ結果、1つのFATALを見つけるために10,000行のパステストを出力するテストランナー。
📊 実証結果: Headroomはテストログを10,144 → 1,260 トークンに圧縮——同じFATALエラーを検出、コストはほんの一部です。
Headroomは、AIエージェント専用に設計されたオープンソースのコンテキスト圧縮レイヤーです。アプリケーションとLLM APIの間に位置し、送信前に入力を透過的に圧縮します。
pip install "headroom-ai[all]"Headroomは単一の戦略を使用しません。コンテンツを6つの専門エンジンにルーティングし、それぞれが異なるデータタイプに最適化されています。
CCR(Compressed Context Recovery)はオリジナルをローカルストアに保持します。LLMがより詳細な情報を必要とした場合、headroom_retrieveを呼び出してオンデマンドで特定セクションを復元できます。
pip install "headroom-ai[all]"
headroom proxy --port 8787
# AIツールのベースURLをhttp://localhost:8787/v1に設定
headroom wrap claude # Claude Codeをラップ
headroom wrap cursor # Cursorをラップ
headroom wrap aider # Aiderをラップ
from headroom import withHeadroom
from anthropic import Anthropic
client = withHeadroom(Anthropic())
# すべての呼び出しが自動的に圧縮されます
headroom mcp install
# 登録: headroom_compress, headroom_retrieve, headroom_stats
| フレームワーク | 統合方法 |
|---|---|
| Anthropic / OpenAI SDK | withHeadroom(client) |
| LangChain | HeadroomChatModel(your_llm) |
| Vercel AI SDK | wrapLanguageModel({ middleware: headroomMiddleware() }) |
| LiteLLM | litellm.callbacks = [HeadroomCallback()] |
| Agno | HeadroomAgnoModel(your_model) |
| 機能 | Headroom | RTK | lean-ctx | 手動 |
|---|---|---|---|---|
| 対象範囲 | 全コンテキスト | CLI出力 | CLI+MCP | 会話のみ |
| ローカル実行 | ✅ | ✅ | ✅ | N/A |
| 可逆圧縮 | ✅ CCR | ❌ | ❌ | ❌ |
| MLベース | ✅ Kompress | ❌ | ❌ | ❌ |
| キャッシュ対応 | ✅ CacheAligner | ❌ | ❌ | ❌ |
コンテキスト圧縮は、HTTPにおけるgzipのように、AIエージェントスタックの標準レイヤーになりつつあります。Headroomは最も包括的なオープンソース実装です。月額50ドル以上のLLM APIを使用しているなら、導入のROIは即座に現れるでしょう。