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

compaction-advanced.md

412 lines19.7 KB

1---
2title: "Compaction: Advanced"
3id: compaction-advanced
4description: "Every compaction option, custom strategies, real token counts, background summaries, DevTools events, checkpoints, and session logs."
5keywords:
6 - tanstack ai
7 - compaction
8 - context window
9 - countTokens
10 - summarizeOldest
11 - session log
12---
13​
14This page covers the details of compaction that you need only for special cases. Set up the basics first with [Compaction](./compaction).
15​
16## Options
17​
18### withCompaction
19​
20| Option | Type | Default | Description |
21|--------|------|---------|-------------|
22| `maxTokens` | `number` | - | **Required.** Compact when the token count of `messages` passes this. See `countTokens`. |
23| `strategy` | `CompactionStrategy` | `evictOldest()` | How to shrink the messages. |
24| `estimateTokens` | `(message: ModelMessage) => number` | characters / 4 | The token estimate for one message. Pass a real tokenizer to get exact counts. |
25| `strategyKey` | `string` | identity of the built-in strategy | A stable identity for checkpoints. Set it for custom strategies, custom estimators, or a custom eviction marker. Change it when your `summarize` function can change. |
26| `onCompact` | `(info: CompactionInfo) => void` | - | Runs after each compaction. See [onCompact](#oncompact). |
27| `countTokens` | `'estimate' \| 'usage'` | `'estimate'` | `'usage'` counts with the usage that the provider reported for the last call. See [Count with real usage](#count-with-real-usage). |
28| `auto` | `boolean` | `true` | `false` turns off compaction at `maxTokens`. `compactNext`, the overflow retry, and the check after a run still compact. |
29| `contextWindow` | `number` | - | The context window of the model. See [Set the limit from the context window](#set-the-limit-from-the-context-window). |
30| `durable` | `boolean` | `false` | On a host with a session log, write the result into the log. See [Keep compaction in a session log](#keep-compaction-in-a-session-log). |
31| `continueOnError` | `boolean` | `false` | When the strategy fails, send the full messages and continue. By default the run fails. |
32| `background` | `{ atTokens: number }` | - | Prepare the summary when the count passes `atTokens`, and apply it at the next run. See [Prepare the summary in the background](#prepare-the-summary-in-the-background). |
33| `native` | `{ compact?: (options) => Promise<ModelMessage[]> }` | - | The adapter of the `chat()` call. When it has `compact`, the provider compacts in place of `strategy`. See [Let the provider compact](./compaction#let-the-provider-compact). |
34​
35### Strategy options
36​
37| Strategy | Options |
38|----------|---------|
39| `evictOldest` | `keepRecentTokens` (default `maxTokens / 2`), `marker` |
40| `summarizeOldest` | `summarize` (**required**), `keepRecentTokens` (default `maxTokens / 2`), `summaryRole` (default `'assistant'`), `cut` (default `'message'`) |
41| `clearToolResults` | `keepRecentToolResults` (default `3`), `stub` |
42​
43The token count is a rough `characters / 4` estimate. It is good enough to start a compaction, but it is not exact. Pass `estimateTokens` to get counts that match the provider.
44​
45### onCompact
46​
47`onCompact` gets `{ before, after, messagesBefore, messagesAfter, reason, usage, error, stale }`:
48​
49- `before` and `after`: the estimated tokens.
50- `reason`: why it ran. See [DevTools events](#devtools-events).
51- `usage`: the token usage of the summary calls.
52- `error`: set when the check after a run fails, when a background summary fails, or when `native` compaction failed and `strategy` ran in its place.
53- `stale`: set when a background summary does not fit the current messages.
54​
55## Write your own strategy
56​
57A strategy is a function. It gets the messages and the budget. It returns the rewritten messages, or `null` to change nothing.
58​
59It runs when the count is over `maxTokens`. It also runs when `compactNext` forces it, so the count can be under `maxTokens`.
60​
61```typescript
62import { withCompaction } from "@tanstack/ai-compaction";
63import type { CompactionStrategy } from "@tanstack/ai-compaction";
64​
65// Keep only the last message.
66const keepLastOnly: CompactionStrategy = (messages) => {
67 if (messages.length <= 1) return null;
68 return messages.slice(-1);
69};
70​
71withCompaction({
72 maxTokens: 100_000,
73 strategy: keepLastOnly,
74 strategyKey: "keep-last-v1",
75});
76```
77​
78The second argument of the strategy has:
79​
80- `maxTokens`: the budget.
81- `estimate`: the shared token estimator.
82- `addUsage`: report the usage of a model call that the strategy made, for example a summary.
83- `signal`: aborts when the run is cancelled. Pass it to a model call.
84​
85If you use a custom strategy with persistence, set `strategyKey`. When the strategy can give a different output, change the key. Then an old checkpoint cannot use stale behavior.
86​
87## Native compaction failures
88​
89These rules apply when you pass `native` (see [Let the provider compact](./compaction#let-the-provider-compact)):
90​
91- When `compact` fails, `strategy` runs in its place. `onCompact` and `compaction:ended` get the failure in `error`. Some providers on the OpenAI Responses base have no compaction endpoint.
92- After a 404, 405, or 501 (the provider has no compaction endpoint), that adapter object and model use `strategy` until the process restarts. Create the adapter once, outside the request handler, so that no more compaction calls go out.
93- After any other failure, such as a 400, a 429, or a network error, the next compaction tries `compact` again.
94- The compaction call gets the system prompts of the `chat()` call. It does not get the tools, because the compaction endpoint does not accept them.
95- The compacted messages can hold an encrypted provider item. The adapter sends it back unchanged to the same model. Another model does not get it.
96​
97## Give the retry something to cut
98​
99After a context overflow, the retry compacts even under `maxTokens`. But a strategy can still find nothing to cut:
100​
101- `composeStrategies` stops when the estimate is under `maxTokens`.
102- `evictOldest` keeps `maxTokens / 2` by default.
103​
104Set a small `keepRecentTokens`, so that the retry always drops something:
105​
106```typescript
107import { evictOldest, withCompaction } from "@tanstack/ai-compaction";
108​
109withCompaction({
110 maxTokens: 100_000,
111 strategy: evictOldest({ keepRecentTokens: 20_000 }),
112});
113```
114​
115## Compact on your own schedule
116​
117Call `compactNext(threadId)` to make the next call on a thread compact, even under `maxTokens`. For example, do this before you switch the thread to a model with a smaller context window.
118​
119Create the middleware once, so that `compactNext` reaches the same instance:
120​
121```typescript
122import { withCompaction } from "@tanstack/ai-compaction";
123​
124const compaction = withCompaction({ maxTokens: 100_000 });
125​
126// The next model call on this thread compacts first.
127compaction.compactNext("thread-1");
128```
129​
130## Count with real usage
131​
132The `characters / 4` estimate drifts on long agent runs. Code, JSON, and other languages do not split into tokens like English text. Then compaction runs too late and the call fails. Or it runs too early and drops context that you still need.
133​
134Set `countTokens: 'usage'`. After each model call, compaction saves the usage that the provider reported. The next check starts from that number and estimates only the messages after it.
135​
136```ts
137import { chat, toServerSentEventsResponse } from '@tanstack/ai'
138import { openaiText } from '@tanstack/ai-openai'
139import { withCompaction } from '@tanstack/ai-compaction'
140​
141export async function POST(request: Request) {
142 const { messages, threadId } = await request.json()
143​
144 const stream = chat({
145 adapter: openaiText('gpt-6.1-sol'),
146 messages,
147 threadId,
148 middleware: [withCompaction({ maxTokens: 100_000, countTokens: 'usage' })],
149 })
150​
151 return toServerSentEventsResponse(stream)
153```
154​
155- Before the first model call, there is no usage. Compaction uses the estimate.
156- With a [`metadata` store](#checkpoints), compaction saves the usage. The next request and a restarted server start from the real count.
157- The strategies still use the estimate to choose which messages to keep.
158​
159## Set the limit from the context window
160​
161Most models publish a context window. Keep room for the answer: set `maxTokens` to the window minus a reserve.
162​
163```ts
164import { summarize } from '@tanstack/ai'
165import { openaiSummarize } from '@tanstack/ai-openai'
166import { summarizeOldest, withCompaction } from '@tanstack/ai-compaction'
167​
168const contextWindow = 200_000
169const reserveTokens = 20_000
170​
171const windowed = withCompaction({
172 maxTokens: contextWindow - reserveTokens,
173 contextWindow,
174 countTokens: 'usage',
175 strategy: summarizeOldest({
176 keepRecentTokens: 8_000,
177 summarize: (messages, { threadId }) =>
178 summarize({
179 adapter: openaiSummarize('gpt-6.1-sol'),
180 text: messages
181 .map((m) => `${m.role}: ${typeof m.content === 'string' ? m.content : ''}`)
182 .join('\n'),
183 threadId: `${threadId}:compaction`,
184 }),
185 }),
186})
187```
188​
189| You want | Set |
190|---|---|
191| Compact before the context passes the window minus a reserve | `maxTokens: contextWindow - reserveTokens` |
192| Keep the newest messages word for word | `keepRecentTokens` on the strategy |
193| On a host with a session log: no automatic compaction, but recovery from a silent overflow | `auto: false`, `contextWindow`, `countTokens: 'usage'`, `durable: true` |
194​
195Some providers accept a request that is too large. They cut the input and answer without an error.
196​
197On a host with a [session log](#keep-compaction-in-a-session-log), compaction with `countTokens: 'usage'` and `durable: true` checks once more after the last model call of a run. If the usage passed `maxTokens` or `contextWindow`, it compacts immediately, so the next run starts small.
198​
199- With `auto: false`, only `contextWindow` counts.
200- The answer is not sent again. The only extra model calls are the summary calls.
201- Without a session log, there is no check after a run. The next request compacts before its first model call.
202​
203## Prepare the summary in the background
204​
205A `summarizeOldest` call takes time. When compaction runs at `maxTokens`, the user waits for that call before the model answers. Set `background` to prepare the summary earlier, while the chat continues:
206​
207```ts
208import { chat, summarize, toServerSentEventsResponse } from '@tanstack/ai'
209import { openaiSummarize, openaiText } from '@tanstack/ai-openai'
210import { summarizeOldest, withCompaction } from '@tanstack/ai-compaction'
211​
212// Create it once, so that a summary from one request reaches the next.
213const compaction = withCompaction({
214 maxTokens: 100_000,
215 background: { atTokens: 80_000 },
216 strategy: summarizeOldest({
217 summarize: (messages, { threadId }) =>
218 summarize({
219 adapter: openaiSummarize('gpt-6.1-sol'),
220 text: messages
221 .map((m) => `${m.role}: ${typeof m.content === 'string' ? m.content : ''}`)
222 .join('\n'),
223 threadId: `${threadId}:compaction`,
224 }),
225 }),
226})
227​
228export async function POST(request: Request) {
229 const { messages, threadId } = await request.json()
230​
231 const stream = chat({
232 adapter: openaiText('gpt-6.1-sol'),
233 messages,
234 threadId,
235 middleware: [compaction],
236 })
237​
238 return toServerSentEventsResponse(stream)
240```
241​
242How the background summary runs:
243​
244- `atTokens` must be less than `maxTokens`. If it is not, `withCompaction` throws.
245- When the count at a model call passes `atTokens`, the summary starts on a copy of the messages. The model call does not wait for it.
246- The ready summary waits in the [`metadata` store](#checkpoints), under the namespace `@tanstack/ai-compaction:background`. Without a store, it waits in memory.
247- The summary applies at the first model call of the next run on the same `threadId`, never in the middle of a run.
248- A model call over `maxTokens` while the summary runs waits for it and applies it. It compacts inline only when the messages are still over `maxTokens`. A cancel of the run stops the wait, not the summary.
249​
250Sometimes a summary does not apply:
251​
252- A newer compaction cut past the message that the summary keeps. The summary is dropped and reported with `stale: true`.
253- The summary call failed. Nothing applies, and the failure is reported with `error`. The next model call past `atTokens` starts a new summary.
254​
255`onCompact` always gets these reports. A `compaction:ended` event for a failed summary reaches the stream only while the run that started the summary still runs.
256​
257## Better summaries
258​
259The basic `summarizeOldest` setup works for a chat. A coding agent needs more. It must keep the goal, the decisions, and the files that it touched across many compactions. Three opt-in parts help:
260​
2611. `cut: 'turn'` on `summarizeOldest` gives a better summary when the cut falls inside a turn. The older turns get one summary. The start of the current turn gets its own short summary, under `## Turn context`.
2622. `conversationSummarizer` is a ready summarizer with a structured prompt (goal, constraints, progress, key decisions, next steps, critical context). When an older summary exists, it updates that summary. It reports the usage of each summary call.
2633. `details` on `conversationSummarizer` adds your own facts after the summary, for example the files that the agent read. The next compaction gets them back as `previousDetails`.
264​
265```ts
266import { openaiText } from '@tanstack/ai-openai'
267import {
268 conversationSummarizer,
269 summarizeOldest,
270 withCompaction,
271} from '@tanstack/ai-compaction'
272​
273function pathOf(args: string) {
274 const input: unknown = JSON.parse(args)
275 return typeof input === 'object' &&
276 input !== null &&
277 'path' in input &&
278 typeof input.path === 'string'
279 ? input.path
280 : undefined
282​
283const agentCompaction = withCompaction({
284 maxTokens: 180_000,
285 contextWindow: 200_000,
286 countTokens: 'usage',
287 strategy: summarizeOldest({
288 cut: 'turn',
289 keepRecentTokens: 8_000,
290 summarize: conversationSummarizer({
291 adapter: openaiText('gpt-6.1-sol'),
292 details: ({ messages, previousDetails }) => {
293 const files = new Set(previousDetails?.split('\n').filter(Boolean))
294 for (const message of messages) {
295 for (const call of message.toolCalls ?? []) {
296 const path =
297 call.function.name === 'read_file'
298 ? pathOf(call.function.arguments)
299 : undefined
300 if (path) files.add(path)
301 }
302 }
303 return files.size > 0 ? [...files].join('\n') : undefined
304 },
305 }),
306 }),
307})
308```
309​
310- In the text that goes to the summarizer, each tool result is cut to 2,000 characters. Set `maxToolResultChars` to change this limit.
311- Your own `summarize` function gets a second argument, `summarize(messages, input)`:
312 - `previousSummary` and `previousDetails`: the older summary and its details.
313 - `turnPrefix`: `true` when the call summarizes the start of the current turn.
314 - `turnPrefixMessages`: the start of the current turn. Only the call that writes the details gets it, so the details cover each dropped message.
315 - `signal`: aborts when the run aborts.
316​
317## DevTools events
318​
319After a compaction, the chat stream includes three CUSTOM events in this order:
320​
3211. `compaction:started`: sent before the strategy runs.
3222. `compaction:state`: the result, with counts and previews.
3233. `compaction:ended`: why it ran and what it cost.
324​
325Durability flushes each event when it is emitted. So a slow `summarizeOldest` call still shows as started on the client while it runs.
326​
327`compaction:ended` has these fields:
328​
329- `reason`: `'threshold'` (the count passed `maxTokens`), `'forced'` (`compactNext`, or the retry after a context overflow), or `'background'` (a [background summary](#prepare-the-summary-in-the-background)).
330- `usage`: the token usage of the summary calls.
331- `error`: the message when the strategy failed. By default the run then fails. Set `continueOnError: true` to send the full messages instead.
332- `stale`: `true` when a ready background summary did not fit the current messages and was dropped.
333​
334A compaction after the last model call of a run has `reason: 'after-turn'`. The stream is closed by then, so only `onCompact` reports it. A failed strategy or `onCompact` there does not fail the run, because the answer is complete. Only a failed write to the log fails it.
335​
336TanStack AI DevTools has a Compaction tab on the hook. Each compaction shows:
337​
338- started, state, and ended rows
339- when it ran, with token and message counts
340- the `maxTokens` budget
341- dropped messages
342- the transcript sent to the model
343​
344The conversation timeline also keeps `onCompactStart`, `onCompact`, and `onCompactEnd` steps.
345​
346To see it:
347​
3481. Open the AI plugin in the DevTools panel. The `ts-react-chat` example mounts it.
3492. Select the Compaction hook.
3503. Open the Compaction tab.
351​
352The `/compaction` route in `examples/ts-react-chat` uses a small `maxTokens`, so compaction runs after a few turns. It also uses `withPersistence` (SQLite). Reload after a compaction: the chat still shows every message. The banner is example UI, not part of `useChat`.
353​
354## Checkpoints
355​
356If the persistence adapter has a `metadata` store, compaction saves a small checkpoint:
357​
358- The next request makes sure that the start of the transcript did not change.
359- Then it restores the last compacted result and adds only the new messages.
360- A changed start of the transcript, or a changed strategy key, makes the checkpoint invalid.
361​
362When compaction reuses a checkpoint, a later `summarizeOldest` pass sees the previous summary plus new messages. Then it merges the old summary into the new one. This merge needs a metadata store and a strategy key.
363​
364These strategies get a strategy key automatically:
365​
366- The default strategy and standard `evictOldest`.
367- `summarizeOldest` and `clearToolResults`.
368- Safe compositions of the strategies above.
369​
370Set `strategyKey` for custom strategies, custom estimators, or custom marker functions. When your `summarize` function can change, change `strategyKey` too. Without a metadata store or a safe key, compaction stays stateless.
371​
372With `durable: true` on a host with a session log, compaction writes its result into the log instead. See the next section.
373​
374## Keep compaction in a session log
375​
376Some hosts keep a durable log for each thread. They rebuild the model context from it when a session opens again. A metadata checkpoint can miss on that rebuild. Set `durable: true` so that the compaction goes into the log, and the rebuilt session sees the same context.
377​
3781. Make sure that the host provides `LogRecordsCapability`. See [Append records to the session log](./middleware-advanced#append-records-to-the-session-log).
3792. Add `withCompaction({ durable: true })` to the same `chat()` call.
3803. Fold each compaction record into the messages with `projectCompaction`: for the next model call, and when the host rebuilds the session.
381​
382```ts
383import type { ModelMessage } from '@tanstack/ai'
384import { projectCompaction, withCompaction } from '@tanstack/ai-compaction'
385​
386const compaction = withCompaction({
387 maxTokens: 180_000,
388 contextWindow: 200_000,
389 countTokens: 'usage',
390 durable: true,
391})
392​
393type LogEntry =
394 | { kind: 'message'; message: ModelMessage }
395 | { kind: 'record'; record: { type: string; [key: string]: unknown } }
396​
397// Fold the log in order. A compaction record replaces the messages before it.
398function contextOf(log: Array<LogEntry>): Array<ModelMessage> {
399 let messages: Array<ModelMessage> = []
400 for (const entry of log) {
401 if (entry.kind === 'message') messages = [...messages, entry.message]
402 else messages = projectCompaction({ messages, record: entry.record }) ?? messages
403 }
404 return messages
406```
407​
408- Each compaction writes one record with the type `'tanstack.compaction'` (`COMPACTION_RECORD_TYPE`). The host must accept this type.
409- `projectCompaction` returns `undefined` for a record of another type, and for a record that does not fit the messages. Then keep the messages as they are.
410- Without the fold for the next model call, each later call of the run compacts the full list again.
411- The log only grows, so the original messages stay in the store.
412- Without `LogRecordsCapability`, compaction uses the metadata checkpoint, and there is no check after the run.