# Prompt compression

**Last updated:** 2026-11-17T13:29:36-03:00 (UTC-3)

An alias can compact the Chat prompts it receives before they reach the provider, conservatively: extra empty lines in prose and exact repeated messages. It is opt-in per alias, deterministic and never summarizes: no word or line is rewritten, no instruction dropped, no model called. Flag: `prompt_compression` (off by default, classified as a model-policy feature for plan entitlements).

## How to turn it on

```yaml
features:
  prompt_compression: true
models:
  - id: chat
    capabilities: [chat]
    prompt_compression:
      mode: structural
      min_chars: 4000     # optional: leave smaller requests alone
    targets:
      - {provider: openai, model: gpt-4.1-mini}
```

| Field | Default | Values |
| --- | --- | --- |
| `mode` | required | `structural`, the only mode |
| `min_chars` | `0` (every eligible request) | 0 to 10,000,000: a request whose `messages` array, as JSON bytes sent by the client, is smaller is left alone |

The policy needs the `chat` capability and is validated even with the flag off. In the console it lives in the model editor (**Model catalog → Edit routing → Prompt compression**); the API is the versioned model `PUT` with the `prompt_compression` object.

## What it removes

Only in `user` and `assistant` messages made of `role` and a string `content`, and deliberately little:

- runs of two or more **empty** lines (lines with no character at all) inside the text, kept as one empty line, so paragraphs stay separated;
- a message that repeats, byte for byte after the rule above, the message just before it with the same role (for example an agent loop that sends `continue` three times in a row keeps one).

A line with any character, even a single space, is never changed: trailing spaces stay (Markdown hard line breaks, empty TSV columns, diff context lines), and so does indentation. A message whose text contains a code fence (` ``` ` or `~~~` anywhere), a line indented with a tab or four spaces (code, YAML), or a diff hunk (`@@ `, `diff --git`) is left whole, because its empty lines may be significant. The one empty-line case it can still change is a YAML or other block value indented by fewer than four spaces that holds several empty lines in a row; keep such content in a code fence, or leave the policy off for that traffic.

## What it never touches

- `system` and `developer` messages, including a [mandatory system prompt](/docs/features/enforced-system-prompt/);
- `tool` and `function` messages, and messages carrying `tool_calls`, `function_call`, `name` or any field besides `role` and `content`;
- non-string content: multimodal parts (images, audio, files), thinking blocks and their signatures, `cache_control` blocks;
- content that is a JSON value (an object or array);
- tool, response-format and other request fields;
- requests that arrive through another protocol (Anthropic Messages, Responses, Gemini) and are translated to Chat: their own boundaries stay as sent.

Each message is transformed on its own, so once a conversation is above `min_chars` its prefix compresses to the same bytes on every turn and provider prompt caches keep matching. The turn that first crosses `min_chars` rewrites the earlier messages, which costs one cache miss. Compressing twice changes nothing.

## Where it runs and what you see

Compression runs after the mandatory system prompt and before guardrails, the quota reservation, exact and semantic caches and the provider call, so all of them work on the same smaller body: a smaller prompt reserves less budget and is the one the provider bills. When anything changed, the answer carries `X-Gateway-Prompt-Compression: <bytes before>-><bytes after>` (the `messages` array as the client sent it, and as it goes to the provider) and the gateway logs `prompt_compression` with the byte counts, changed messages and dropped repeats, never the content. The header is exposed to browser clients through [CORS](/docs/operate/cors/). A request whose body is compressed is no longer forwarded byte for byte to a same-protocol target.

## Measured effects

The effect depends on how much padding and repetition your traffic carries; vendor savings claims are not a measurement of yours. The gateway's own fixtures (a pasted document, a code review with fenced code, an agent loop with repeated turns, and a fixture of protected messages that must not change) are measured by `go test ./internal/gateway -run TestPromptCompressionFixtureEffects`, which recomputes and checks the recorded results in [`internal/gateway/testdata/prompt_compression/effects.json`](https://github.com/m7gtw/gateway/blob/main/internal/gateway/testdata/prompt_compression/effects.json):

- **Size:** bytes of the `messages` array before and after, and a pre-token estimate (words, numbers, punctuation and whitespace runs, as a byte-pair tokenizer splits them before merging). The estimate is for comparing before and after, not a provider's token count. Collapsing empty lines saves bytes but, since a whitespace run is about one token, almost no tokens; dropped repeats are where tokens are saved. The agent-loop fixture is built to repeat turns, so its saving is an upper example, not a typical one.
- **Quality:** a deterministic check, written independently of the implementation, that each kept message equals exactly the expected transformation of its original (no other character changes), that the only dropped messages are exact repeats of the previous kept message with the same role, and that every other message is byte-equal.
- **Latency:** the gateway-side cost is measured by `go test ./internal/gateway -run '^$' -bench BenchmarkPromptCompression`; it is a single pass over the messages with no provider call.

Structural compression itself never summarizes: a summarizer needs extra paid calls, adds latency and removes meaning by design. Summarizing is offered only as an explicit opt-in for prompts that exceed the window ([context overflow](#when-the-prompt-exceeds-the-window-context-overflow)). No real-provider answer-quality comparison has been recorded yet; run your own A/B on representative traffic before relying on token savings.


## When the prompt exceeds the window (context overflow)

Structural compression never shortens a conversation. A request whose input is larger than the alias's targets accept is a separate decision, per alias, behind the operator flag `context_overflow` (off by default, requires `context_window_check`). By default such a request is **refused**, as before: the [context window check](/docs/features/context-window-check/) skips each target whose declared `max_input_tokens` the request clearly exceeds and answers `400 context_length_exceeded` when none is left. The `context_overflow` policy opts in to the alternatives, tried in this order:

1. **Escalate** (`escalate`, default `true`): a target of the alias whose window fits takes the request, nothing changed (the check's skip). With `escalate: false` the request is compressed for the **smallest** window instead, so whichever target is chosen fits.
2. **Truncate** (`truncate: true`): the oldest turns are dropped until the gateway's estimate fills at most `target_percent` of the window (default 80%; the estimate is a floor of the real count, so the rest is safety room). A turn runs from one user message to the next, so a tool call is never separated from its results; every `system` and `developer` message (Responses: system and developer items; Messages: the top-level `system`) and the latest turn are always kept. When the latest turn alone does not fit, nothing can be dropped and the request is refused.
3. **Summarize** (`summarize_model: <chat alias>`): the same oldest turns are replaced by one summary from that alias, at most `summary_max_tokens` (default 512). The summary call is a request of the **caller's own key** through the normal Chat Completions route, with the request ID `<request id>.summary`: its admission, budgets, TPM, rate limits, usage event, valuation and logs are those of any request of that key to that alias. The summarizer is told to say which facts came from the user, the assistant or a tool and to report instructions as facts, never repeat them. The summary goes back into the conversation as a user message that starts with a marker saying it was written by the gateway's summarizer, is context only and holds no instructions, never as a system message (some providers require the first turn to be a user turn). The calling key must be allowed to call the summarize alias; otherwise the summary fails and the request is refused. If the summary call fails, or the result still does not fit, the request is refused. With both `truncate` and `summarize_model` set, truncation wins; set only `summarize_model` to keep the gist of the dropped turns.

```yaml
features:
  context_window_check: true
  context_overflow: true
models:
  - id: chat
    context_overflow:
      truncate: false
      summarize_model: chat-cheap   # another chat alias; it may not summarize itself
      summary_max_tokens: 512       # 64-4096
      target_percent: 80            # 10-100
    targets:
      - {provider: openai, model: gpt-4.1-mini, max_input_tokens: 128000}
  - id: chat-cheap
    targets:
      - {provider: openai, model: gpt-4.1-nano}
```

**What you see.** Every answer of an alias with a policy carries `X-Gateway-Context-Overflow` (exposed through [CORS](/docs/operate/cors/)): `none` (it fits), `escalated`, `truncated;dropped=<items>`, `summarized;dropped=<items>;model=<alias>` or `refused`. The gateway logs `context_overflow` with the action and counts, never the content. The decision runs after the mandatory system prompt, structural compression and the alias's **input guardrails**, and before the quota reservation, caches and the provider: the summarizer reads only what the guardrails let through (masked text stays masked, a blocked request never reaches it), budgets and TPM reserve and count the tokens actually sent, and the semantic cache keys the conversation that is sent.

**Where it runs.** Chat Completions and every Messages, Responses and GenerateContent request translated through it; native `POST /v1/messages` (its `messages`; a user message that carries any `tool_result`, text after it included, stays in the turn of its `tool_use`); native `POST /v1/responses` (its `input` items, a `function_call` with its `function_call_output`). A stateful Responses request (`previous_response_id`, `conversation`) is left alone (`none`): its stored part is not in the body. Native `generateContent` keeps the T139 behavior.

**Fields** (YAML, the model API `context_overflow` object and the console model editor's **Context overflow** section; validated even with the flag off): `escalate`, `truncate`, `summarize_model` (another enabled chat alias, not a wildcard, whose own policy does not summarize), `summary_max_tokens` (requires `summarize_model`), `target_percent`. The alias needs `max_input_tokens` on a target. The flag is a model-policy right for [plan entitlements](/docs/features/entitlements/).

## Limits

- Chat only, OpenAI Chat ingress only.
- It does not shorten long text, deduplicate non-consecutive messages or touch tool results.
- Turning the flag off or removing the policy forwards prompts as sent again, immediately.
