Skip to main content
You choose which messages each completion request sends to the model. As a conversation grows, resending the full history makes every turn slower and more expensive, until it no longer fits the model’s context window. To keep it in bounds, shrink the message list before each request: Both endpoints return messages you can send to the completions endpoint as is. Any API key with the search ACL can call them.
Both endpoints are in beta and live under /1/unstable/context/. Their request and response shapes may change before they move to a stable path, so keep a fallback, as the loop below does.

Trim a conversation

Trim drops messages without calling an LLM, so the same input always returns the same output. This request keeps the last two messages of a five-message conversation:
The response holds the trimmed messages and a stats object:
Response
Token counts are heuristic estimates, not counts from your LLM provider. To measure a conversation without changing it, send only messages: trim returns them unchanged, with stats. Set one or more limits: keepLastMessages and dropToolParts apply first, so maxTokensEstimate counts only what remains.

Compact a conversation

Compact summarizes every message except the last keepLastMessages into one user message, followed by the kept messages unchanged. Your LLM provider writes the summary, so set providerID to its ID and model to a model it serves. We recommend a small model: it reads the older messages but writes only a short summary.
The response adds a compaction object:
Response
compacted is false when nothing is older than the kept messages, or nothing older has text to summarize. The messages then pass through unchanged. summarizerPromptTokens and summarizerCompletionTokens are the token counts your provider reports, summed across every summary call. They’re null if the provider doesn’t report usage. If a conversation doesn’t fit the summary model’s context window, compact splits it into chunks, summarizes each one, and merges the results. chunksProcessed reports the number of chunks, and passes the number of summary rounds. If compact still can’t summarize the conversation, the endpoint returns 400.

Shrink the conversation on every turn

This example shrinks the messages before every completion request and compacts them once the estimate passes 20,000 tokens:
JavaScript
If either call fails, the loop sends the last ten messages instead, so a change to a beta endpoint doesn’t stop your agent. Messages can use the AI SDK v4 or v5 format, but not both in the same request. The summary stays in the history, so later compactions summarize it again with the newer messages. Compaction doesn’t guarantee a size. For a hard cap, trim the result with maxTokensEstimate before you send it.

See also

Last modified on October 30, 2026