Open History to see the last commit
1---
2title: Compaction
3id: compaction
4order: 3
5description: "Keep long chats under the context limit. withCompaction from @tanstack/ai-compaction shrinks what the model sees before each call: drop old messages, summarize them, or clear old tool output."
6keywords:
7 - tanstack ai
8 - compaction
9 - context window
10 - middleware
11 - token limit
12 - summarize history
13---
14
15Compaction shortens a transcript before it passes the model context limit. A long chat or agent loop otherwise fails on the next call.
16
17Add `withCompaction` to your `chat()` call. It runs before each model call.
18
19## Quick setup
20
21### 1. Install the package
22
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24
25react: @tanstack/ai-compaction
26vue: @tanstack/ai-compaction
27solid: @tanstack/ai-compaction
28svelte: @tanstack/ai-compaction
29preact: @tanstack/ai-compaction
30angular: @tanstack/ai-compaction
31octane: @tanstack/ai-compaction
32vanilla: @tanstack/ai-compaction
33
34<!-- ::end:tabs -->
35
36### 2. Add the middleware to your chat endpoint
37
38```typescript
39import {
40 chat,
41 chatParamsFromRequest,
42 toServerSentEventsResponse,
43} from "@tanstack/ai";
44import { openaiText } from "@tanstack/ai-openai";
45import { withCompaction } from "@tanstack/ai-compaction";
46
47export async function POST(request: Request) {
48 const { messages, threadId, runId } = await chatParamsFromRequest(request);
49
50 const stream = chat({
51 adapter: openaiText("gpt-6.1-sol"),
52 messages,
53 threadId,
54 runId,
55 middleware: [withCompaction({ maxTokens: 100_000 })],
56 });
57
58 return toServerSentEventsResponse(stream);
59}
60```
61
62The client does not change. Your `useChat` code stays the same.
63
64### 3. Watch it run
65
66Use a small `maxTokens` and an `onCompact` log while you try it:
67
68```typescript
69import { withCompaction } from "@tanstack/ai-compaction";
70
71const compaction = withCompaction({
72 maxTokens: 2_000,
73 onCompact: (info) => {
74 console.log(`Compacted from ${info.before} to ${info.after} tokens`);
75 },
76});
77```
78
79Put `compaction` in the `middleware` array and chat for a few turns. The server logs a line each time the history shrinks, and the chat keeps answering.
80
81## How it works
82
83- `withCompaction` is a [chat middleware](./middleware). Before each model call, it estimates the token count of the messages (characters / 4).
84- When the count passes `maxTokens`, a **strategy** rewrites the messages that go to the provider.
85- The full transcript does not change. Persistence and the UI still see every message.
86- The system prompt is never dropped. `chat()` keeps it separate from `messages`.
87- Tool calls stay paired with their results, so the request stays valid.
88
89## Pick a strategy
90
91Pass `strategy` to change how the history shrinks. Three are built in:
92
93| Strategy | What it does | Cost |
94|----------|--------------|------|
95| `evictOldest` (default) | Drop the oldest messages and leave a marker | No extra model call |
96| `summarizeOldest` | Replace the oldest messages with a summary from a model | One summary call (up to two with `cut: 'turn'`) |
97| `clearToolResults` | Replace the content of old tool results with a stub, keep the messages | No extra model call |
98
99### evictOldest
100
101This strategy is the cheapest. It keeps the recent messages, drops the older ones, and puts a short marker in their place. It is the default, so name it only to set `keepRecentTokens`:
102
103```typescript
104import { withCompaction, evictOldest } from "@tanstack/ai-compaction";
105
106withCompaction({
107 maxTokens: 100_000,
108 strategy: evictOldest({ keepRecentTokens: 40_000 }),
109});
110```
111
112### summarizeOldest
113
114This strategy keeps the meaning of old turns and costs one summary call. Give it a `summarize` function. The function gets the messages to drop and an input with the `threadId` of the conversation. It returns the summary. Give the summary call a thread id of its own, so it does not share state with the conversation:
115
116```typescript
117import {
118 chat,
119 chatParamsFromRequest,
120 summarize,
121 toServerSentEventsResponse,
122} from "@tanstack/ai";
123import type { ModelMessage } from "@tanstack/ai";
124import { openaiSummarize, openaiText } from "@tanstack/ai-openai";
125import {
126 summarizeOldest,
127 withCompaction,
128 type SummarizeInput,
129} from "@tanstack/ai-compaction";
130
131async function summarizeHistory(
132 messages: Array<ModelMessage>,
133 { threadId }: SummarizeInput,
134) {
135 const text = messages
136 .map((m) => `${m.role}: ${typeof m.content === "string" ? m.content : ""}`)
137 .join("\n");
138
139 // Return the whole result, so compaction can report its usage.
140 return summarize({
141 adapter: openaiSummarize("gpt-6.1-sol"),
142 text,
143 threadId: `${threadId}:compaction`,
144 });
145}
146
147export async function POST(request: Request) {
148 const { messages, threadId, runId } = await chatParamsFromRequest(request);
149
150 const stream = chat({
151 adapter: openaiText("gpt-6.1-sol"),
152 messages,
153 threadId,
154 runId,
155 middleware: [
156 withCompaction({
157 maxTokens: 100_000,
158 strategy: summarizeOldest({ summarize: summarizeHistory }),
159 }),
160 ],
161 });
162
163 return toServerSentEventsResponse(stream);
164}
165```
166
167`summarize` can return the summary text, or an object with `summary` and `usage`. Return the `summarize()` result as it is, so that compaction can report the cost of the summary.
168
169For a coding agent, use the ready summarizer in [Better summaries](./compaction-advanced#better-summaries).
170
171### clearToolResults
172
173This strategy is the best fit for agent loops. Tool output (file reads, command output) is usually most of the tokens. The strategy replaces the content of old tool results with a stub. Every message and every tool-call pair stays in place.
174
175```typescript
176import { withCompaction, clearToolResults } from "@tanstack/ai-compaction";
177
178withCompaction({
179 maxTokens: 100_000,
180 // Keep the 5 most recent tool results in full. Stub the older ones.
181 strategy: clearToolResults({ keepRecentToolResults: 5 }),
182});
183```
184
185## Combine strategies
186
187`composeStrategies` runs several strategies in order. It stops as soon as the result is under `maxTokens`. Put the cheap, targeted strategy first and a broad fallback last.
188
189This example clears old tool output first. It drops old messages only when that is not enough:
190
191```typescript
192import {
193 withCompaction,
194 composeStrategies,
195 clearToolResults,
196 evictOldest,
197} from "@tanstack/ai-compaction";
198
199withCompaction({
200 maxTokens: 100_000,
201 strategy: composeStrategies(clearToolResults(), evictOldest()),
202});
203```
204
205## Let the provider compact
206
207Some providers can compact the conversation on their own servers. The model then keeps more of the old turns than a marker gives. It costs one compaction call.
208
209Pass the adapter of the `chat()` call as `native`. When the count passes `maxTokens`, the `compact` method of the adapter runs in place of `strategy`:
210
211```typescript
212import {
213 chat,
214 chatParamsFromRequest,
215 toServerSentEventsResponse,
216} from "@tanstack/ai";
217import { openaiText } from "@tanstack/ai-openai";
218import { withCompaction } from "@tanstack/ai-compaction";
219
220// Create the adapter once, outside the request handler.
221const adapter = openaiText("gpt-6.1-sol");
222
223export async function POST(request: Request) {
224 const { messages, threadId, runId } = await chatParamsFromRequest(request);
225
226 const stream = chat({
227 adapter,
228 messages,
229 threadId,
230 runId,
231 middleware: [withCompaction({ maxTokens: 100_000, native: adapter })],
232 });
233
234 return toServerSentEventsResponse(stream);
235}
236```
237
238- An adapter with no `compact` method uses `strategy`.
239- When `compact` fails, `strategy` runs in its place.
240
241The OpenAI Responses adapters have `compact`. See [Native compaction](../adapters/openai-advanced#native-compaction). For what happens on each kind of failure, see [Native compaction failures](./compaction-advanced#native-compaction-failures).
242
243## When the chat is still too long
244
245The token count is an estimate. So sometimes a call is still too long for the model, and the provider rejects it.
246
247You do not have to catch that error. When a call fails with `CONTEXT_OVERFLOW_CODE`, `withCompaction` compacts and calls the model again, in the same run. Your code only sees the answer. This also works with `auto: false`.
248
249It retries once for each model call. If the compacted call is still too long, the run ends with a `RUN_ERROR`:
250
251- `code` is `CONTEXT_OVERFLOW_CODE` (`'context_overflow'`).
252- `message` is the text from the provider.
253
254These adapters set this code:
255
256- OpenAI, Anthropic, Gemini, and Bedrock.
257- OpenRouter, Grok, Cloudflare, and BytePlus.
258- Other OpenAI-compatible adapters, when the provider sends `context_length_exceeded`.
259
260To make sure that the retry always has something to drop, see [Give the retry something to cut](./compaction-advanced#give-the-retry-something-to-cut).
261
262## Compaction and persistence
263
264Compaction and server-side [`withPersistence`](../persistence/chat-persistence) use two views of the messages:
265
266- `messages` is the full transcript. Persistence saves this view.
267- `providerMessages` is the context for the model. Compaction rewrites this view.
268
269The order of the middleware does not change this split. Dropped, summarized, and stubbed content stays in the message store.
270
271If the persistence adapter has a `metadata` store, compaction also saves a small checkpoint. The next request then starts from the last compacted result. See [Checkpoints](./compaction-advanced#checkpoints) for the details.
272
273## Advanced
274
275[Compaction: Advanced](./compaction-advanced) has the deep details:
276
277- Every option of `withCompaction` and of each strategy.
278- Your own strategy, and compaction on your own schedule.
279- Counts from the real usage of the provider, and summaries that run in the background.
280- DevTools events, checkpoints, and session logs.