Skip to content
Source
Sign inSign up
TanStack/ai

packages/ai-compaction

README.md

TanStack AI

@tanstack/ai-compaction

Context-window compaction as a chat() middleware. When the working message set grows past maxTokens, withCompaction runs a pluggable strategy that rewrites provider context. It runs before every model call, so compaction is incremental and rolling. The canonical transcript and system prompt stay unchanged.

npm install @tanstack/ai-compaction

Quick start

The default strategy (evictOldest) drops the oldest messages and keeps the recent ones.

import { chat } from '@tanstack/ai'
import { withCompaction } from '@tanstack/ai-compaction'

chat({
  adapter,
  messages,
  middleware: [withCompaction({ maxTokens: 100_000 })],
})

Strategies

Pass strategy to change how the history shrinks. Three are built in.

StrategyWhat it doesCost
evictOldest (default)Drop the oldest messages, leave a markerNo extra model call
summarizeOldestReplace the oldest messages with an LLM summaryOne summarize call
clearToolResultsStub the content of old tool results, keep the messagesNo extra model call
import {
  withCompaction,
  evictOldest,
  summarizeOldest,
  clearToolResults,
} from '@tanstack/ai-compaction'

// Tune how much recent history to keep.
withCompaction({
  maxTokens: 100_000,
  strategy: evictOldest({ keepRecentTokens: 40_000 }),
})

// Summarize instead of dropping. `summarize` gets the messages being removed.
withCompaction({
  maxTokens: 100_000,
  strategy: summarizeOldest({ summarize: (msgs) => summarizeToText(msgs) }),
})

// Best for agent loops: stub old tool output, keep the messages in place.
withCompaction({
  maxTokens: 100_000,
  strategy: clearToolResults({ keepRecentToolResults: 5 }),
})

Combine them

composeStrategies runs strategies in order and escalates: it stops once the result is back under maxTokens. Put the cheap one first.

import {
  withCompaction,
  composeStrategies,
  clearToolResults,
  evictOldest,
} from '@tanstack/ai-compaction'

// Clear old tool output first; only drop old messages if that isn't enough.
withCompaction({
  maxTokens: 100_000,
  strategy: composeStrategies(clearToolResults(), evictOldest()),
})

Write your own

A strategy 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.

import type { CompactionStrategy } from '@tanstack/ai-compaction'

const keepLastOnly: CompactionStrategy = (messages) =>
  messages.length <= 1 ? null : messages.slice(-1)

withCompaction({
  maxTokens: 100_000,
  strategy: keepLastOnly,
  strategyKey: 'keep-last-v1',
})

Options

withCompaction

OptionDefaultWhat it does
maxTokens(required)Compact when estimated tokens exceed this.
strategyevictOldest()How to shrink the messages.
estimateTokenschars / 4Per-message token estimate. Swap in a real tokenizer for accuracy.
strategyKeybuilt-in keyStable checkpoint identity. Set it for custom strategies or estimators.
onCompact—Observe each compaction (before/after/messagesBefore/messagesAfter).

Strategy options

StrategyOptions
evictOldestkeepRecentTokens (default maxTokens / 2), marker
summarizeOldestsummarize (required), keepRecentTokens, summaryRole (default assistant)
clearToolResultskeepRecentToolResults (default 3), stub

The token estimate is a rough chars / 4 heuristic, good enough to trigger on, not exact. Pass estimateTokens if you need provider-accurate counts.

When withPersistence provides a metadata store, compaction saves a validated checkpoint automatically. The next request reuses the compacted prefix and adds new canonical messages. Without metadata, compaction remains stateless.

TanStack AI DevTools has a Compaction tab with started, state, and ended events, before/after counts, and dropped vs sent message previews. Those stats ride the chat stream as compaction:started, compaction:state, and compaction:ended CUSTOM events.