# Headroom Context Compression

Headroom reduces the prompt history sent to a model, including eligible text from earlier tool results. AISIX first applies any input screening and redaction, then sends the resulting context to a Headroom service you operate. AISIX rewrites only eligible history and preserves the current user message, system and developer instructions, and protected cache prefixes.

## Prepare Headroom[​](#prepare-headroom "Direct link to Prepare Headroom")

Use a Headroom service reachable from each AISIX gateway that will apply the policy. AISIX has been verified with Headroom 0.45.0. Set `HEADROOM_COMPRESS_ALLOW_REMOTE=1` on Headroom for access from a remote gateway. If Headroom uses `HEADROOM_PROXY_TOKEN`, configure the same value as the policy's API key. AISIX sends it as a Bearer token. For deployment and protocol details, see [Headroom's proxy documentation](https://github.com/headroomlabs-ai/headroom/blob/v0.45.0/docs/content/docs/proxy.mdx#gateway-mode).

The policy requires gateway 1.13.0 or later. The dashboard workflow in AISIX Enterprise and AISIX Cloud also requires control plane 1.13.0 or later and permission to manage guardrails and attachments in the environment.

## Create and Attach a Policy[​](#create-and-attach-a-policy "Direct link to Create and Attach a Policy")

1. In the dashboard, select a test environment, open **Guardrails**, and select **New guardrail**. Enter a **Name**, such as `docs-compress-history`, and select **Headroom** as the **Type**.

2. Under **Scope**, choose **Whole environment** for this example. Under **Connection**, enter the **Base URL** of your Headroom service, such as `https://headroom.example.com/proxy`. AISIX appends `/v1/compress` to the base URL, preserving the optional path prefix. Provide the **API key** if Headroom requires it. Keep the defaults below for this example with a single Headroom replica.

   ![Headroom guardrail form with Whole environment selected and the service base URL outlined](https://static.api7.ai/uploads/2026/12/02/sk6GIhWl_guardrail-form.webp)

3. Select **Create guardrail** to save the policy and its enabled apply attachment. Confirm that the policy is **enabled** and shows **Whole environment**.

   ![Saved Headroom guardrail with enabled status and Whole environment scope](https://static.api7.ai/uploads/2026/12/02/OqXXCRhE_guardrail-saved.webp)

To limit compression to particular traffic, choose **Specified resources** and select compatible **Models**, **Caller API keys**, or **Model tags**. An enabled apply attachment is required. Model and model tag attachments match the alias addressed by the caller, including direct, routing, and semantic models. The Admin API also supports apply attachments for teams. An enabled exclusion for a model, model tag, or caller API key takes precedence over an apply attachment. For the shared controls, see [Apply or Exclude Requests by Resource](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md#apply-or-exclude-requests-by-resource).

| Dashboard Setting                 | Admin API Field        | Default and Effect                                                                                                                                                                     |
| --------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Base URL**                      | `config.api_base`      | Required HTTP(S) base URL. Omit the query and fragment.                                                                                                                                |
| **API key**                       | `config.api_key`       | Optional Headroom Bearer token.                                                                                                                                                        |
| **Timeout (ms)**                  | `config.timeout_ms`    | `60000` milliseconds per Headroom call.                                                                                                                                                |
| **Retrieve compressed context**   | `config.ccr_retrieval` | `true`. Allow eligible non-streaming requests to retrieve original context.                                                                                                            |
| **If Headroom compression fails** | `fail_open`            | `false` (**Block the request (safer)**). A compression failure returns HTTP 502. Select **Forward without compression** to send the screened and redacted request without compression. |

For the Admin API, create the guardrail with `kind: headroom` and at least one enabled apply attachment. Headroom fixes `hook_point` to `input`, `enforcement_mode` to `block`, and `input_messages` to `all`. In AISIX OSS, set the same values and put the Headroom connection fields directly on the guardrail entry in the [resources file](https://docs.api7.ai/ai-gateway/reference/resources-file.md#guardrails). Declare the apply attachment in `guardrail_attachments`.

## Choose Whether to Retrieve Context[​](#choose-whether-to-retrieve-context "Direct link to Choose Whether to Retrieve Context")

Compressed Context Retrieval (CCR) lets a model ask for details from compressed history. During a CCR turn, AISIX relays model responses to Headroom to retrieve the original context and continues generation on the same upstream model. The client receives the final result in its original API protocol. Retrieval can add provider calls and latency. AISIX records token usage for each actual model call, applies the same route's pricing rules to each round, and counts the turn as one client request.

| Request or Upstream Path                                                                                                                                   | Behavior                                                                             |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Eligible non-streaming Chat Completions, Anthropic Messages, and OpenAI Responses                                                                          | Compression with retrieval when enabled and supported by the selected upstream path. |
| Supported streaming requests, signed Amazon Bedrock or native Gemini upstream requests, and requests with forced tool choice                               | Compression without retrieval markers.                                               |
| Native Responses requests with `conversation` or `previous_response_id`, or with application tools and `parallel_tool_calls` absent or enabled             | Compression without retrieval markers when the request includes eligible history.    |
| Background Responses, requests without eligible history, and other surfaces such as embeddings, MCP, passthrough, and the native Gemini API on the gateway | AISIX skips compression.                                                             |

Route `/v1/compress` and `/v1/compress/response` for each turn to the same Headroom replica. A shared Headroom session store leaves in-progress turns on the replica that started them. If your deployment cannot guarantee this routing, turn off **Retrieve compressed context** to keep basic compression. **Forward without compression** applies to the initial compression call. If Headroom fails during retrieval, AISIX returns HTTP 502.

## Verify Compression[​](#verify-compression "Direct link to Verify Compression")

Send a request through a covered model alias with a long tool result from an earlier turn, such as a build log that precedes a completed assistant reply. Inspect the Headroom token counters, such as `aisix_headroom_tokens_saved_total`, for compression activity. Repeat with `x-headroom-bypass: true` to compare the same request without compression. The header applies to that request only, and the gateway still applies its safety guardrails.

If a recently reporting gateway is known to lack Headroom support, the control plane rejects an enabled save with HTTP 422 and `DP_INCOMPATIBLE`. After the policy is saved, a gateway that joins the environment on a supported version below 1.13.0 or rolls back to such a version continues serving requests with its existing safety guardrails and skips Headroom. The control plane can report the ignored configuration in the gateway's compatibility information.
