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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
docs(site): Python-first quickstart and a FastAPI page built on compress() (#4529)
Tejas Chopra0ae116d46c9f
diff --git a/docs/content/docs/fastapi.mdx b/docs/content/docs/fastapi.mdxnew file mode 100644index 000000000..9e25f12ed--- /dev/null+++ b/docs/content/docs/fastapi.mdx@@ -0,0 +1,124 @@+---+title: FastAPI+description: Cut LLM input tokens in a FastAPI app. Compress tool outputs, logs and chat history with compress() before calling OpenAI or Anthropic. No API key needed to try it.+---++Headroom's `compress()` is a function over your message list, so in FastAPI it+is one call before your model call. This page builds a `POST /chat` endpoint+that returns the compressed messages and token counts, then shows the one-line+change that forwards them to a provider.++## Install++```bash+pip install fastapi "uvicorn[standard]" headroom-ai+```++No provider key, no model download. The base package is enough for+`compress()`; `[ml]` adds the Kompress text model later if you want more+savings on prose-heavy tool output.++## Endpoint++```python+# main.py+from typing import Any++from fastapi import FastAPI+from pydantic import BaseModel++from headroom import compress++app = FastAPI()+++class ChatIn(BaseModel):+ messages: list[dict[str, Any]] # OpenAI or Anthropic message dicts+ model: str = "gpt-4o" # used for token counting and the context limit++[email protected]("/chat")+def chat(body: ChatIn) -> dict[str, Any]:+ result = compress(body.messages, model=body.model)+ return {+ "messages": result.messages,+ "tokens_before": result.tokens_before,+ "tokens_after": result.tokens_after,+ "tokens_saved": result.tokens_saved,+ "transforms": result.transforms_applied,+ }+```++Save it as `main.py` and run it with no network at all:++```bash+HEADROOM_OFFLINE=1 uvicorn main:app --port 8000+```++Then post a 3,000-line tool output with one error in it:++```bash+python - <<'EOF_PY'+import json, urllib.request+log = "\n".join([f"INFO step {i} ok" for i in range(3000)] + ["FATAL disk full"])+msgs = [+ {"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},+]+req = urllib.request.Request("http://127.0.0.1:8000/chat", data=json.dumps({"messages": msgs}).encode(), headers={"content-type": "application/json"})+out = json.load(urllib.request.urlopen(req))+print(out["tokens_before"], "->", out["tokens_after"], "FATAL kept:", "FATAL" in json.dumps(out["messages"]))+EOF_PY+```++Expected output is on the order of `20000 -> 95 FATAL kept: True`: the+repeated `INFO` lines collapse, the `FATAL` line survives.++## Forward to the provider++Replace `messages=body.messages` with `messages=result.messages` in your+existing call. Nothing else changes:++```python+from openai import OpenAI++client = OpenAI()++[email protected]("/answer")+def answer(body: ChatIn) -> dict[str, Any]:+ result = compress(body.messages, model=body.model)+ completion = client.chat.completions.create(model=body.model, messages=result.messages)+ return {+ "answer": completion.choices[0].message.content,+ "tokens_saved": result.tokens_saved,+ }+```++For Anthropic, pass `result.messages` to `client.messages.create` the same way.++## What it keeps++Error lines, stack traces, first and last items, and statistical outliers in+JSON arrays are kept. Repeated and low-information lines are dropped. Originals+are cached locally; the model can ask for them back when it has the retrieval+tool, which the [proxy](/docs/proxy) and the [MCP server](/docs/mcp) provide+([CCR](/docs/ccr)). The plain `compress()` call above does not expose it.+Compression applies to tool and assistant messages; user messages are left alone+unless you pass `compress_user_messages=True`. Short prompts and prose compress+very little; see [Limitations](/docs/limitations).++## Not this page++`headroom.integrations.asgi.CompressionMiddleware` is for FastAPI apps that+*serve* an LLM-shaped endpoint (`/v1/messages`, `/v1/chat/completions`), such+as a proxy you built. For an app that *calls* a provider, use `compress()` as+above.++## Settings you will reach for++- `HEADROOM_OFFLINE=1`: no update check, no model or pricing-table downloads, no beacon. Use it in CI and sandboxes. See [Security model](/docs/security-model).+- `compress(..., model_limit=N)`: tell Headroom the model's window is N tokens, so it compresses harder as the prompt approaches it. It never truncates history.+- `compress(..., protect_recent=K)`: leave source code in the last K messages uncompressed.+- [Configuration](/docs/configuration) has the rest.diff --git a/docs/content/docs/index.mdx b/docs/content/docs/index.mdxindex 5533b48a9..bf3545216 100644--- a/docs/content/docs/index.mdx+++ b/docs/content/docs/index.mdx@@ -1,6 +1,6 @@---title: Introduction-description: 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.+description: Headroom (headroom-ai) compresses tool outputs, logs, JSON, RAG results and chat history before each LLM call, to reduce input tokens and token cost and fit a context window. Python library (no API key), proxy and MCP server. Same answers, fewer 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.diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex ba7553294..a0c2b9eda 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -28,6 +28,7 @@"corporate-networks","local-llm-prefill","---Integrations---",+ "fastapi","vercel-ai-sdk","openai-sdk","anthropic-sdk",diff --git a/docs/content/docs/quickstart.mdx b/docs/content/docs/quickstart.mdxindex afa76b2b0..8c3d3e7b5 100644--- a/docs/content/docs/quickstart.mdx+++ b/docs/content/docs/quickstart.mdx@@ -7,7 +7,7 @@ This guide gets you from zero to compressed LLM calls in under 5 minutes.## 1. Install-<Tabs groupId="lang" items={['TypeScript', 'Python']}>+<Tabs groupId="lang" items={['Python', 'TypeScript']}><Tab value="TypeScript">```bashnpm install headroom-ai@@ -15,12 +15,15 @@ npm install headroom-ai</Tab><Tab value="Python">```bash-# CLI/proxy/wrap on your machine-uv tool install --python 3.13 "headroom-ai[all]"+# Python project or virtualenv: enough for compress(), no API key, no model download+pip install headroom-ai-# Python project or virtualenv-pip install "headroom-ai[all]"+# CLI, proxy and `headroom wrap` on your machine+uv tool install --python 3.13 "headroom-ai[all]"```++`[all]` adds the proxy, the MCP server, the Kompress model and more; `compress()`+needs only the base package.</Tab></Tabs>@@ -38,7 +41,7 @@ The proxy runs the compression pipeline (Python) and exposes an HTTP API that th## 2. Compress messages-<Tabs groupId="lang" items={['TypeScript', 'Python']}>+<Tabs groupId="lang" items={['Python', 'TypeScript']}><Tab value="TypeScript">```ts twoslashimport { compress } from 'headroom-ai';@@ -110,11 +113,22 @@ result = compress(messages, model="gpt-4o")</Tab></Tabs>+<Callout type="info" title="No provider key needed to try it">+The Python call runs in-process. `HEADROOM_OFFLINE=1` makes it zero-network as+well (no update check, no model or pricing-table downloads):++```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))"+```++A [FastAPI endpoint](/docs/fastapi) built on the same call is one page away.+</Callout>+## 3. Send to your LLMUse the compressed messages exactly like the originals:-<Tabs groupId="lang" items={['TypeScript', 'Python']}>+<Tabs groupId="lang" items={['Python', 'TypeScript']}><Tab value="TypeScript">```ts twoslashimport OpenAI from 'openai';@@ -149,7 +163,7 @@ print(response.choices[0].message.content)## 4. Check your savings-<Tabs groupId="lang" items={['TypeScript', 'Python']}>+<Tabs groupId="lang" items={['Python', 'TypeScript']}><Tab value="TypeScript">```ts twoslashconst result = {