Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

compaction.md

248 lines9.8 KB

1---
2title: Compaction
3id: compaction
4order: 3
5description: "Keep long chats under the context limit with @tanstack/ai-compaction. withCompaction runs a pluggable strategy before each model call: evict, summarize, or clear old tool output."
6keywords:
7 - tanstack ai
8 - compaction
9 - context window
10 - middleware
11 - token limit
12 - summarize history
13---
14​
15A long chat or a multi-step agent loop keeps adding messages. At some point the transcript passes the model's context limit and the call fails. You want the conversation to keep working without hitting that wall.
16​
17`withCompaction` shrinks provider context before each model call. When the context passes `maxTokens`, a **strategy** rewrites what the model sees. The canonical transcript does not change. Add this [`ChatMiddleware`](./middleware) to the `middleware` array of any `chat()` call.
18​
19## Install
20​
21```bash
22pnpm add @tanstack/ai-compaction
23```
24​
25## Quick start
26​
27The default strategy drops the oldest messages once the transcript passes `maxTokens` and keeps the recent ones.
28​
29```typescript
30import { chat, toServerSentEventsResponse } from "@tanstack/ai";
31import { openaiText } from "@tanstack/ai-openai";
32import { withCompaction } from "@tanstack/ai-compaction";
33​
34export async function POST(request: Request) {
35 const { messages } = await request.json();
36​
37 const stream = chat({
38 adapter: openaiText("gpt-5.5"),
39 messages,
40 middleware: [withCompaction({ maxTokens: 100_000 })],
41 });
42​
43 return toServerSentEventsResponse(stream);
45```
46​
47## Pick a strategy
48​
49Pass `strategy` to change how the history shrinks. Three are built in.
50​
51| Strategy | What it does | Cost |
52|----------|--------------|------|
53| `evictOldest` (default) | Drop the oldest messages, leave a marker | No extra model call |
54| `summarizeOldest` | Replace the oldest messages with an LLM summary | One summarize call |
55| `clearToolResults` | Stub the content of old tool results, keep the messages | No extra model call |
56​
57### evictOldest
58​
59Cheapest. Keeps the recent tail, drops the older head, and leaves a short marker in its place. This is the default, so you only name it to tune `keepRecentTokens`.
60​
61```typescript
62import { withCompaction, evictOldest } from "@tanstack/ai-compaction";
63​
64withCompaction({
65 maxTokens: 100_000,
66 strategy: evictOldest({ keepRecentTokens: 40_000 }),
67});
68```
69​
70### summarizeOldest
71​
72Keeps the gist of old turns instead of dropping them, at the cost of one summarization call. Pass a `summarize` callback. It gets the messages about to be dropped and returns the summary text. Wire it to `summarize()` or any model call.
73​
74```typescript
75import { chat, summarize, toServerSentEventsResponse } from "@tanstack/ai";
76import { openaiText, openaiSummarize } from "@tanstack/ai-openai";
77import { withCompaction, summarizeOldest } from "@tanstack/ai-compaction";
78import type { ModelMessage } from "@tanstack/ai";
79​
80async function summarizeHistory(messages: Array<ModelMessage>): Promise<string> {
81 const text = messages
82 .map((m) => `${m.role}: ${typeof m.content === "string" ? m.content : ""}`)
83 .join("\n");
84​
85 const { summary } = await summarize({
86 adapter: openaiSummarize("gpt-5.5"),
87 text,
88 });
89 return summary;
91​
92export async function POST(request: Request) {
93 const { messages } = await request.json();
94​
95 const stream = chat({
96 adapter: openaiText("gpt-5.5"),
97 messages,
98 middleware: [
99 withCompaction({
100 maxTokens: 100_000,
101 strategy: summarizeOldest({ summarize: summarizeHistory }),
102 }),
103 ],
104 });
105​
106 return toServerSentEventsResponse(stream);
108```
109​
110### clearToolResults
111​
112Best for agent loops. Tool output (file reads, command output) is usually most of the tokens. This strategy replaces the content of old tool results with a stub and keeps every message and its tool-call pairing in place. The conversation shape does not change.
113​
114```typescript
115import { withCompaction, clearToolResults } from "@tanstack/ai-compaction";
116​
117withCompaction({
118 maxTokens: 100_000,
119 // Keep the 5 most recent tool results in full, stub the older ones.
120 strategy: clearToolResults({ keepRecentToolResults: 5 }),
121});
122```
123​
124### Write your own
125​
126A strategy is a function. It gets the messages and the budget, and returns the rewritten messages, or `null` to change nothing. It runs only when the estimate is over `maxTokens`.
127​
128```typescript
129import { withCompaction } from "@tanstack/ai-compaction";
130import type { CompactionStrategy } from "@tanstack/ai-compaction";
131​
132// Keep only the last message.
133const keepLastOnly: CompactionStrategy = (messages) => {
134 if (messages.length <= 1) return null;
135 return messages.slice(-1);
136};
137​
138withCompaction({
139 maxTokens: 100_000,
140 strategy: keepLastOnly,
141 strategyKey: "keep-last-v1",
142});
143```
144​
145Set `strategyKey` when you combine a custom strategy with persistence. Change
146the key when the strategy can produce different output. This prevents an old
147checkpoint from using stale behavior.
148​
149## Combine strategies
150​
151`composeStrategies` runs several strategies in order and **escalates**: it stops as soon as the result is back under `maxTokens`. Put the cheap, targeted strategy first and a broad fallback last. Here it clears old tool output first, and only drops old messages if that was not enough.
152​
153```typescript
154import {
155 withCompaction,
156 composeStrategies,
157 clearToolResults,
158 evictOldest,
159} from "@tanstack/ai-compaction";
160​
161withCompaction({
162 maxTokens: 100_000,
163 strategy: composeStrategies(clearToolResults(), evictOldest()),
164});
165```
166​
167## Options
168​
169### withCompaction
170​
171| Option | Type | Default | Description |
172|--------|------|---------|-------------|
173| `maxTokens` | `number` | - | **Required.** Compact when the estimated tokens across `messages` pass this. |
174| `strategy` | `CompactionStrategy` | `evictOldest()` | How to shrink the messages. |
175| `estimateTokens` | `(message: ModelMessage) => number` | characters / 4 | Per-message token estimate. Pass a real tokenizer if you need exact counts. |
176| `strategyKey` | `string` | built-in strategy identity | Stable checkpoint identity. Set it for custom strategies, custom estimators, or a custom eviction marker. Change it when your `summarize` function can change. |
177| `onCompact` | `(info: CompactionInfo) => void` | - | Runs after each compaction. `info` is `{ before, after, messagesBefore, messagesAfter }` (token and message counts). |
178​
179### Strategy options
180​
181| Strategy | Options |
182|----------|---------|
183| `evictOldest` | `keepRecentTokens` (default `maxTokens / 2`), `marker` |
184| `summarizeOldest` | `summarize` (**required**), `keepRecentTokens`, `summaryRole` (default `assistant`) |
185| `clearToolResults` | `keepRecentToolResults` (default `3`), `stub` |
186​
187The token count is a rough `characters / 4` estimate. It is good enough to trigger on, not exact. Pass `estimateTokens` for provider-accurate counts.
188​
189## What it keeps safe
190​
191- **The system prompt is never dropped.** `chat()` keeps it separate from `messages`, so compaction only touches the conversation.
192- **Tool calls stay paired with their results.** The built-in strategies never leave an orphaned tool result, so the request stays valid.
193- **It runs before every model call.** Compaction skips `init`. It runs on `beforeModel` and `structuredOutput`. Each later call can compact again.
194- **The canonical transcript stays complete.** Compaction writes provider-only context. Persistence and other middleware still read `ctx.messages`.
195​
196## DevTools
197​
198After a compaction, the chat stream includes three CUSTOM events in order:
199`compaction:started`, `compaction:state`, then `compaction:ended`.
200`compaction:started` is sent before the strategy runs. Durability flushes each
201event as soon as it is emitted, so a slow `summarizeOldest` call still shows
202as started on the client while it runs. The state and ended events follow when
203the strategy returns.
204TanStack AI DevTools has a Compaction tab on the hook. Each compact shows:
205​
206- started, state, and ended rows
207- when it ran, with token and message counts
208- the `maxTokens` budget
209- dropped messages
210- the transcript sent to the model
211​
212The conversation timeline also keeps `onCompactStart`, `onCompact`, and
213`onCompactEnd` steps.
214​
215Open the AI plugin in the DevTools panel (the `ts-react-chat` example mounts it). Select the Compaction hook, then open the Compaction tab.
216​
217The `/compaction` route in `examples/ts-react-chat` uses a small `maxTokens` so this fires after a few turns. It also uses `withPersistence` (SQLite). Reload after a compact: the chat still shows every message. The banner is example UI, not part of `useChat`.
218​
219## Compaction and persistence
220​
221Compaction and server-side [`withPersistence`](../persistence/chat-persistence)
222use two message views:
223​
224- `messages` is the complete canonical transcript. Persistence saves this view.
225- `providerMessages` is temporary model context. Compaction rewrites this view.
226​
227Middleware order does not change this split. Dropped, summarized, and stubbed
228content remains in the message store.
229​
230If the persistence adapter has a `metadata` store, compaction also saves a small
231checkpoint. The next request validates the canonical prefix, restores the last
232compacted result, and adds only new messages. A changed prefix or strategy key
233invalidates the checkpoint.
234​
235When a checkpoint is reused, a later `summarizeOldest` pass sees the previous
236summary plus new messages. Then it folds the old summary into the new one.
237Folding needs a metadata store and a strategy key.
238​
239The default strategy, standard `evictOldest`, `summarizeOldest`,
240`clearToolResults`, and safe compositions get a strategy key automatically.
241Set `strategyKey` for custom strategies, custom estimators, or custom marker
242functions. Change `strategyKey` when your `summarize` function can change.
243Without a metadata store or safe key, compaction stays stateless.
244​
245## Next steps
246​
247- [Middleware](./middleware): the full hook reference and how middleware composes
248- [Built-in Middleware](./built-in-middleware): ready-made middleware that ships in `@tanstack/ai`