Headroom

Introduction

Headroom is the context optimization layer for LLM applications. Compress tool outputs, DB results, file reads, and RAG results before they reach the model. Same answers, fraction of the tokens.

Headroom compresses everything your AI agent reads -- tool outputs, database results, file reads, RAG retrievals, API responses -- before it reaches the LLM. The model sees less noise, responds faster, and costs less.

Quick preview

import {  } from 'headroom-ai';

const  = [
  { : 'user' as , : 'Analyze these results' },
];

const  = await (, { : 'gpt-4o' });
// compressionRatio is tokensAfter / tokensBefore, so savings is 1 - ratio.
.(`Saved ${.tokensSaved} tokens (${((1 - .compressionRatio) * 100).(0)}%)`);
from headroom import compress
from openai import OpenAI

messages = [{"role": "user", "content": "Analyze these results"}]

result = compress(messages, model="gpt-4o")

client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4o",
    messages=result.messages,
)
print(f"Saved {result.tokens_saved} tokens ({result.compression_ratio:.0%})")

What gets compressed

Content typeWhat happensTypical savings
JSON arrays (tool outputs)Statistical analysis keeps errors, anomalies, boundariesvaries with array size and redundancy
Source codeAST-aware compression preserves signatures, collapses bodiesopt-in; disabled by default
Build/test logsKeeps failures and errors, drops passing noisevaries with log verbosity
Search resultsRanks by relevance, keeps top matchesvaries with result set size
Plain textModernBERT token classification removes redundancyvaries with redundancy
Git diffsPreserves change hunks, drops unchanged contextvaries with diff size
ImagesML router selects optimal resize/quality tradeoffvaries with image content

Savings depend heavily on how repetitive the content is -- see Benchmarks and the reproducible scenario table below for measured numbers on real workloads.

Where Headroom fits

Your Agent / App
    |
    |  tool outputs, logs, DB reads, RAG results, file reads, API responses
    v
 Headroom  <-- proxy, Python library, TS SDK, or framework integration
    |
    v
 LLM Provider  (OpenAI, Anthropic, Google, Bedrock, 100+ via LiteLLM)

Headroom works as a transparent proxy (zero code changes), a Python function (compress()), a TypeScript function (compress()), or a framework integration (LangChain, Agno, Strands, LiteLLM, Vercel AI SDK, MCP).

Real-world results

Headroom is built for the scenario that matters most in agent workflows: a single critical error or fact buried inside a large, mostly-routine tool output. SmartCrusher preserves error items, anomalies (values outside normal statistical range), and first/last boundaries by construction -- not by keyword matching, but by statistical analysis of field variance -- so the signal survives even when the surrounding noise is compressed away aggressively.

Measured on local, seeded test data built from real MCP server output formats. These are not production telemetry, and they are reproducible:

ScenarioBeforeAfterSavings
Code search (100 results)17,19913,59721%
SRE incident debugging55,95724,34057%
Codebase exploration58,80133,89542%
GitHub issue triage46,06732,42930%
uv run python benchmarks/index_proof_table.py --seed 20260902

Token counts are from the gpt-5.6 tokenizer. The corpus is generated, so the exact before/after counts move slightly with the seed; the savings hold across seeds (Code search 21%, SRE 56--57%, triage 29--30%, exploration 41--50% over five seeds). Savings depend on how repetitive your tool output is, so treat these as a shape, not a promise.

See Benchmarks for the wider suite.

Key Features

Lossless Compression (CCR)

Compresses aggressively, stores originals, gives the LLM a tool to retrieve full details. Nothing is thrown away.

Learn more →

Smart Content Detection

Auto-detects JSON, code, logs, text, diffs, HTML. Routes each to the best compressor. Zero configuration needed.

Learn more →

Cache Optimization

Stabilizes prefixes so provider KV caches hit. Tracks frozen messages to preserve the 90% read discount.

Learn more →

Image Compression

40-90% token reduction via trained ML router. Automatically selects resize/quality tradeoff per image.

Learn more →

Persistent Memory

Hierarchical memory (user/session/agent/turn) with SQLite + HNSW backends. Survives across conversations.

Learn more →

Failure Learning

Reads past sessions, finds failed tool calls, correlates with what succeeded, writes learnings to CLAUDE.md.

Learn more →

Multi-Agent Context

Compress what moves between agents. Any framework.

ctx = SharedContext()
ctx.put("research", big_output)
summary = ctx.get("research")
Learn more →

Metrics & Observability

Prometheus endpoint, per-request logging, cost tracking, budget limits, pipeline timing breakdowns.

Learn more →

Framework Integrations

LangChain

Wrap any chat model. Supports memory, retrievers, tools, streaming, async.

from headroom.integrations.langchain import HeadroomChatModel
llm = HeadroomChatModel(ChatOpenAI())
LangChain Guide →

Agno

Full agent framework integration with observability hooks.

from headroom.integrations.agno import HeadroomAgnoModel
model = HeadroomAgnoModel(Claude())
agent = Agent(model=model)
Agno Guide →

Strands

Model wrapping + tool output hook provider for Strands Agents.

from headroom.integrations.strands import HeadroomStrandsModel
model = HeadroomStrandsModel(...)
agent = Agent(model=model)
Strands Guide →

MCP Tools

Three tools for Claude Code, Cursor, or any MCP client: headroom_compress, headroom_retrieve, headroom_stats.

headroom mcp install && claude
MCP Tools Guide →

TypeScript SDK

compress(), Vercel AI SDK middleware, OpenAI and Anthropic client wrappers.

npm install headroom-ai
TypeScript SDK Guide →

Vercel AI SDK

One-liner withHeadroom() or headroomMiddleware() for any Vercel AI SDK model.

import { withHeadroom } from 'headroom-ai/vercel-ai'
const model = withHeadroom(openai('gpt-4o'))
Vercel AI SDK Guide →
All integration patterns →

Nothing is lost

Compressed content goes into the CCR store (Compress-Cache-Retrieve). The LLM gets a headroom_retrieve tool and can fetch full originals when it needs more detail. Compression is aggressive but reversible.

Next steps

On this page