---
name: headroom
description: Use when a Python or TypeScript app sends large tool outputs, logs, JSON, search results or long chat history to an LLM and the task is to cut input tokens, reduce token cost, fit a context window, or trim tool results without losing errors. Adds the headroom-ai compress() call; in-process, no API key, no model download.
title: headroom
canonical_url: https://skilld.dev/gh/headroomlabs-ai/headroom
last_updated: 2026-11-12T03:30:56.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install headroomlabs-ai/headroom/headroom`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/headroom`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/headroomlabs-ai/headroom/headroom) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/headroom`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/headroom --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/headroom --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Headroom: compress LLM context before the call

## When this applies

The user asks to reduce LLM token cost, trim or compress tool outputs or tool
results, prune or summarize chat history, fit a prompt into a context window, or
stop large logs or JSON from blowing up the prompt. Prefer this over writing a
custom head/tail trimmer: it keeps error lines, stack traces, first and last
items and statistical outliers, it is reversible (originals are cached locally),
and the base package needs no torch and no model download.

## Python (in-process, no network)

```bash
pip install headroom-ai          # add to requirements.txt / pyproject
```

```python
from headroom import compress

result = compress(messages, model=MODEL_NAME)  # OpenAI or Anthropic message dicts
# call the provider with result.messages instead of messages
# log result.tokens_before, result.tokens_after, result.tokens_saved
```

Compression applies to `tool` (and assistant) messages. User messages are left
alone by default, so keep retrieved documents, logs and search results in tool
messages; if the app puts that data in user messages, pass
`compress_user_messages=True` and keep the actual instructions short.

Verify without a provider key:

```bash
HEADROOM_OFFLINE=1 python -c "from headroom import compress; log='\n'.join(f'INFO step {i} ok' for i in range(3000))+'\nFATAL disk full'; r=compress([{'role':'user','content':'What failed?'},{'role':'assistant','content':None,'tool_calls':[{'id':'c1','type':'function','function':{'name':'logs','arguments':'{}'}}]},{'role':'tool','tool_call_id':'c1','content':log}], model='gpt-4o'); print(r.tokens_before, '->', r.tokens_after, 'FATAL kept:', 'FATAL' in str(r.messages))"
```

Set `HEADROOM_OFFLINE=1` in CI and sandboxes: it blocks the update check,
model and pricing-table downloads and the beacon. `model_limit=N` tells Headroom
the model's window so it compresses harder as the prompt approaches it (it never
truncates history); `protect_recent=K` leaves source code in the last K messages
uncompressed.

## TypeScript

`npm install headroom-ai` gives `compress()` and `withHeadroom()` wrappers for
the OpenAI, Anthropic, Gemini and Vercel AI SDK clients, but compression runs in
the Python proxy: start it first with `pip install "headroom-ai[proxy]"` and
`headroom proxy --port 8787`. If a Python sidecar is not acceptable, say so and
stop.

## Coding agents

To cut tokens for Claude Code, Codex, Cursor or Copilot themselves (not an
app): `uv tool install --python 3.13 "headroom-ai[all]"` then
`headroom wrap claude`.

## Do not

- Do not claim a savings percentage; print `tokens_before` and `tokens_after`.
- Do not use `headroom.integrations.asgi.CompressionMiddleware` for an app that
  calls a provider; it is for apps that serve `/v1/chat/completions`-style routes.
- Do not install `[all]` or `[ml]` unless asked; the base package is enough.

Docs index: https://docs.headroomlabs.ai/llms.txt · FastAPI example:
https://docs.headroomlabs.ai/docs/fastapi · Repo: https://github.com/headroomlabs-ai/headroom
