# Headroom Example Use Cases: 7 Real-World Patterns from the Source Code

> Explore 7 real-world headroom example use cases directly from the source code. Discover inline SDK integration, HTTP proxy interception, and automated workflows.

- Repository: [Tejas Chopra/headroom](https://github.com/chopratejas/headroom)
- Tags: how-to-guide
- Published: 2026-06-21

---

**The chopratejas/headroom repository contains seven production-ready example use cases covering inline Python SDK integration, HTTP proxy interception, MCP server deployment, and automated CLI workflows.**

Headroom is a context-compression layer designed to reduce token costs in AI agent stacks. The source code provides concrete implementation patterns that demonstrate how to compress prompts, tool outputs, and RAG chunks using three primary modes: **library integration**, **proxy wrapping**, and **MCP server deployment**. These examples illustrate exactly how the compression pipeline in [`headroom/transforms/content_router.py`](https://github.com/chopratejas/headroom/blob/main/headroom/transforms/content_router.py) processes data through specialized compressors before reaching your LLM provider.

## Library SDK Examples (In-Process Compression)

When you import Headroom directly into your Python application, you invoke the compression pipeline locally without external API calls. The `headroom.compress()` function in [`headroom/compress.py`](https://github.com/chopratejas/headroom/blob/main/headroom/compress.py) (lines 448-452) serves as the main entry point, routing content through the appropriate compressor based on type detection.

### Compressing Tabular Data and Spreadsheets

The [`examples/tabular_compression_demo.py`](https://github.com/chopratejas/headroom/blob/main/examples/tabular_compression_demo.py) script demonstrates how to compress structured data and Excel files. This example uses `headroom.compress_spreadsheet()`, which internally leverages `openpyxl` to parse Excel formats before applying compression.

```python
import headroom

# Compress plain text messages

res = headroom.compress(
    [{"role": "user", "content": content}],
    compress_user_messages=True,
)
print(f"tokens {res.tokens_before} → {res.tokens_after} ({res.tokens_saved}% saved)")

# Compress Excel spreadsheets

res = headroom.compress_spreadsheet(
    [{"role": "user", "content": excel_file_path}],
    compress_user_messages=True,
)

```

*What it shows:* Per-message token accounting and spreadsheet-specific compression that handles Excel ingestion transparently [source: `examples/tabular_compression_demo.py#L70-L88`].

### Optimizing RAG Context Windows

For retrieval-augmented generation pipelines, [`examples/context_compression_demo.py`](https://github.com/chopratejas/headroom/blob/main/examples/context_compression_demo.py) shows how to compress JSON-serialized document chunks before they reach the LLM. This example runs entirely locally using the `kompress-base` text model and AST compressors, requiring no API keys.

```python
import json
import headroom

chunks = build_retriever_chunks()  # realistic RAG chunks

compressed = headroom.compress(
    [{"role": "user", "content": json.dumps(chunks)}],
    compress_user_messages=True,
)
print(f"Saved {compressed.tokens_saved} tokens")

```

*What it shows:* Full-stack RAG integration where document chunks pass through JSON and AST compressors in the pipeline, with the core logic implemented in [`headroom/transforms/content_router.py`](https://github.com/chopratejas/headroom/blob/main/headroom/transforms/content_router.py) (lines 477-536) [source: `examples/context_compression_demo.py#L17-L33`].

### LangChain Retriever Integration

The [`examples/langchain_demo/show_compression.py`](https://github.com/chopratejas/headroom/blob/main/examples/langchain_demo/show_compression.py) file implements a custom `HeadroomRetriever` that injects compression into existing LangChain applications. This example uses the **SmartCrusher** compressor for JSON data, demonstrating library-level integration without changing your underlying LLM calls.

```python
from headroom.providers import OpenAIProvider
from headroom.transforms import SmartCrusher
from headroom.integrations.langchain.retriever import HeadroomRetriever

retriever = HeadroomRetriever(
    provider=OpenAIProvider(),
    compressor=SmartCrusher(),
)
docs = retriever.compress_documents(raw_docs)

```

*What it shows:* Before-and-after token counts when using Headroom as a drop-in replacement for standard LangChain retrievers, with the compression logic applied transparently before document return [source: `examples/langchain_demo/show_compression.py#L22-L68`].

## Proxy Mode Examples (Zero-Code Deployment)

Headroom operates as an HTTP interceptor that sits between your application and the LLM provider. The proxy handles incoming requests in [`headroom/proxy/server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/proxy/server.py) (lines 3688-3695), runs the compression pipeline, and forwards traffic while maintaining session state via CCR (Context Compression and Retrieval).

### Wrapping Existing Agents with Session Headers

The [`examples/strands_via_proxy_demo.py`](https://github.com/chopratejas/headroom/blob/main/examples/strands_via_proxy_demo.py) script demonstrates spawning the proxy as a subprocess to wrap agents like Claude or Codex. This pattern requires no code changes to the existing agent—simply route traffic through the local proxy.

```python
import subprocess

# Spawn proxy forwarding to Bedrock

proc = subprocess.Popen(
    ["headroom", "proxy", "--backend", "bedrock"],
    stdout=log,
    stderr=log,
)

# Include session header for CCR and cross-agent memory

headers = {"x-headroom-session-id": SESSION_ID}

```

*What it shows:* How to enable cross-agent memory and compression by injecting the `x-headroom-session-id` header, with the proxy handling all compression transparently [source: `examples/strands_via_proxy_demo.py#L91-L101`].

### Reducing Output Tokens with Verbosity Steering

The proxy supports **output token reduction** via environment variables. Setting `HEADROOM_OUTPUT_SHAPER=1` appends a terse system-prompt snippet and routes low-effort turns to cheaper models, cutting costs on the response side rather than just the context side.

```bash
export HEADROOM_OUTPUT_SHAPER=1
headroom proxy --port 8787

```

*What it shows:* Runtime configuration that modifies LLM behavior without application restarts, as the proxy reads this variable live on every request [source: `README.md#L42-L51`].

## MCP Server and CLI Automation

Headroom exposes MCP (Multi-Chat-Provider) compliant endpoints and CLI tools for automated optimization workflows.

### Compressing MCP Tool Results

The [`examples/mcp_demo/run_agent_eval.py`](https://github.com/chopratejas/headroom/blob/main/examples/mcp_demo/run_agent_eval.py) script integrates with the MCP server implementation in [`headroom/integrations/mcp/server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/integrations/mcp/server.py) (lines 354-400). This allows any MCP-compatible client (Strands, LangChain MCP adapters) to compress tool outputs before they enter the conversation context.

```python
from headroom.integrations.mcp import compress_tool_result_with_metrics
from headroom.providers import OpenAIProvider

compressed = compress_tool_result_with_metrics(
    tool_output, 
    provider=OpenAIProvider()
)
print(f"Tokens saved: {compressed.tokens_saved}")

```

*What it shows:* Direct usage of the `compress_tool_result` helper exposed by the MCP server, enabling compression for tool outputs without modifying the agent code [source: `headroom/integrations/mcp/server.py#L354-L400`].

### Learning from Failed Sessions

The CLI `learn` command mines failed sessions to automatically configure optimal verbosity levels. This workflow writes corrections to [`CLAUDE.md`](https://github.com/chopratejas/headroom/blob/main/CLAUDE.md) and applies them to future proxy sessions.

```bash

# Dry-run to see recommendations

headroom learn --verbosity

# Apply the learned configuration

headroom learn --verbosity --apply

```

*What it shows:* Automated pipeline optimization that configures the proxy based on historical session data, reducing manual tuning requirements [source: `README.md#L58-L66`].

## Summary

The chopratejas/headroom repository provides seven distinct example use cases that demonstrate:

- **Library integration** via `headroom.compress()` for tabular data, RAG chunks, and LangChain retrievers
- **Proxy deployment** for zero-code HTTP interception with session management and output shaping
- **MCP compliance** through `compress_tool_result` helpers for tool-output compression
- **CLI automation** with the `learn` command for session-based optimization

Each example references specific implementation files—from [`headroom/transforms/content_router.py`](https://github.com/chopratejas/headroom/blob/main/headroom/transforms/content_router.py) that selects compressors to [`headroom/compress.py`](https://github.com/chopratejas/headroom/blob/main/headroom/compress.py) that exposes the public API—providing a complete roadmap for implementation.

## Frequently Asked Questions

### Do the Headroom examples require API keys to run?

No. The core compression examples—including tabular data compression and RAG chunk optimization—run entirely locally using the `kompress-base` text model and AST compressors implemented in [`headroom/transforms/kompress_compressor.py`](https://github.com/chopratejas/headroom/blob/main/headroom/transforms/kompress_compressor.py) and [`headroom/transforms/code_compressor.py`](https://github.com/chopratejas/headroom/blob/main/headroom/transforms/code_compressor.py). You only need API keys when configuring the proxy mode to forward requests to commercial LLM backends like Bedrock or OpenAI.

### How does proxy mode intercept traffic without changing my application code?

The proxy acts as a transparent HTTP wrapper that sits between your application and the LLM provider. As implemented in [`headroom/proxy/server.py`](https://github.com/chopratejas/headroom/blob/main/headroom/proxy/server.py), you launch the proxy with `headroom proxy --port 8787` and point your existing application to `localhost:8787` instead of the provider's native endpoint. The proxy reads the `x-headroom-session-id` header to enable CCR (Context Compression and Retrieval) while forwarding compressed requests to the actual backend, requiring no code modifications in your agent.

### Can I integrate Headroom with my existing LangChain application?

Yes. The [`examples/langchain_demo/show_compression.py`](https://github.com/chopratejas/headroom/blob/main/examples/langchain_demo/show_compression.py) file demonstrates a drop-in `HeadroomRetriever` class that replaces your standard retriever. This class uses the **SmartCrusher** compressor from `headroom/transforms` to process documents before they reach your LLM chain. You initialize it with any Headroom provider (such as `OpenAIProvider()`) and call `compress_documents()` to get token-reduced outputs compatible with standard LangChain pipelines.

### What is the difference between the `compress` function and the SmartCrusher class?

The `headroom.compress()` function in [`headroom/compress.py`](https://github.com/chopratejas/headroom/blob/main/headroom/compress.py) is the high-level API that automatically routes content through the appropriate compressor based on type detection in [`headroom/transforms/content_router.py`](https://github.com/chopratejas/headroom/blob/main/headroom/transforms/content_router.py). **SmartCrusher** is a specific compressor implementation optimized for JSON and structured data, used explicitly in the LangChain integration example. While `compress` handles general cases (text, code, spreadsheets), SmartCrusher provides specialized aggressive compression for retrieval contexts where JSON serialization dominates.