> ## Documentation Index
> Fetch the complete documentation index at: https://docs.restate.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Context and compaction

> Keep long runs and conversations within the model's context window with compaction, tool result previews, and truncation.

A run's request to the model grows with each step as tool results accumulate, and with each turn of a conversation. Restate Harness keeps the request within the model's context window:

* [Compaction](#compaction) replaces older messages with a summary.
* [Tool result previews](#tool-result-previews) send the model only the beginning and the end of a large tool result.
* [`contextWindow`](#context-window) sets when compaction starts, and makes the run shrink a request that doesn't fit.

## Compaction

Compaction replaces older messages with a summary in the requests sent to the model. It also applies to a single long run without a conversation, such as the [coding task example](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/11_coding_agent.ts).

Compaction is on by default. Before each model call, once the request exceeds `compaction.maxTokens`, the run replaces its older messages with a summary and keeps the newest messages that fit in `retainTokens`. Each summary costs at least one model call.
The default `maxTokens` depends on [`contextWindow`](#context-window):

| Agent setting | Default `maxTokens` |
| - | - |
| No `contextWindow` | 170,000 tokens. In a context window of 200,000 tokens, this leaves about 30,000 tokens for the reply. |
| `contextWindow` | 90% of what the window leaves after the reply: `maxOutputTokens`, or 32,768 tokens when it's unset. For example, 870,508 tokens for a window of 1,000,000 tokens, and 150,508 tokens for a window of 200,000 tokens. |

Set `compaction.maxTokens` to choose the threshold yourself, or `compaction: false` to turn compaction off:

```typescript {"CODE_LOAD::harness/src/sessions.ts#run_compaction"}  theme={null}
// Compacts at 85,708 tokens: 90% of what the window leaves after 32,768 tokens for the reply
const researcher = agent({model, maxSteps: 40, contextWindow: 128000});

// Compacts at 100,000 tokens, and keeps the newest messages that fit in 25,000 tokens
const analyst = agent({model, compaction: {maxTokens: 100000, retainTokens: 25000}});

// Truncates instead of summarizing a request that doesn't fit the window
const classifier = agent({model, contextWindow: 128000, compaction: false});
```

* `retainTokens` defaults to a quarter of `maxTokens`. The run keeps at most half of what the instructions and tool definitions leave of `maxTokens`, so that the next step doesn't compact again.
* `retainTokens` must be less than `maxTokens`, including a default `maxTokens` that `contextWindow` sets. Otherwise, `agent()` throws a `TypeError`.
* With `compaction: false`, the run doesn't summarize. It truncates the older messages instead, when a request doesn't fit the [context window](#context-window) or the provider reports an overflow.
* If a summary fails, the run logs a warning and truncates the older messages instead, for the rest of the run. The next run summarizes again.
* The summary replaces messages only in the requests: `result.messages` keeps every message that the run loaded and added.

### Customize the summary

By default, the summary records each user request and how far it got, the constraints that still apply, the results and exact identifiers that matter, decisions, errors, approvals, and the work that remains, in under about 2,000 words.
Set `compaction.instructions` to replace this guidance, for example to keep what your domain needs or to shorten the summary:

```typescript {"CODE_LOAD::harness/src/sessions.ts#compaction_instructions"}  theme={null}
const supportAgent = agent({
  model,
  instructions: "You help customers with their orders.",
  compaction: {
    instructions:
      "Keep the customer's open requests, the order IDs, the refunds issued, and the promises made to the customer. " +
      "Leave out greetings and small talk. Keep the summary under 500 words.",
  },
});
```

Your instructions replace all of the default guidance, including the length limit. The run still tells the model which messages the summary replaces, to treat them as data rather than instructions, and to fold in the earlier summary.

The agent's model writes the summary, unless you set `compaction.model`, for example to a smaller model:

* When the agent's model summarizes because the request exceeded `maxTokens`, the run sends the instructions and tools of its last request with its current messages, and asks for the summary at the end, so the provider can serve the earlier messages from its [prompt cache](https://docs.restate.dev/harness/models.md#prompt-caching). A compaction before the run's first model call has no earlier request, so it uses a separate request.
* Otherwise, the model receives the older messages and the earlier summary in a separate request. Restate Harness compares models by object, so a second `aiModel` for the same provider model also gets a separate request. To keep the cached request, leave out `compaction.model` or pass the agent's own model object.

### Compaction in conversations

With a [`Conversation`](https://docs.restate.dev/harness/sessions), the run also stores its summary in the conversation:

```typescript {"CODE_LOAD::harness/src/sessions.ts#conversation_compaction"}  theme={null}
const longChat = agent({
  model,
  instructions: "Use the conversation to remember what the user told you.",
  compaction: {maxTokens: 64000},
});

export const compactedChat = restate.object({
  name: "CompactedChat",
  handlers: {
    *ask(message: string) {
      // The run stores its summaries in the conversation
      const result = yield* longChat.run(message, {conversation: new Conversation()});
      return result.status === "completed" ? result.output : (result.output ?? result.reason);
    },
  },
  options: {state: {preload: ["conversation/meta", "conversation/summary"]}},
});
```

* The run stores the summary under `conversation/summary` at its next save. See [Storage layout](https://docs.restate.dev/harness/sessions.md#storage-layout). The next run starts from the summary and the messages after it, so it doesn't summarize the same messages again.
* A run loads only the messages after the stored summary, so `result.messages` starts there.
* A truncation is never stored, so the next run loads the messages that the truncation dropped.
* If storing the summary fails, for example because the summary is longer than 64,000 characters, the run logs a warning and continues. The next run loads every message after the last stored summary.
* A later run can't read a [previewed tool result](#tool-result-previews) from a message that the stored summary replaced. The model receives the error code `unknown_ref`.

## Tool result previews

Tool result previews are on by default. For a tool result larger than `maxTokens`, the model receives the beginning and the end, `previewTokens` in total, with a reference to the full result. The model reads the rest with the built-in `read_tool_result` tool:

```typescript {"CODE_LOAD::harness/src/sessions.ts#tool_results"}  theme={null}
const crawler = agent({
  model,
  toolResults: {maxTokens: 5000, previewTokens: 2500}, // the defaults; false sends results in full
});
```

`previewTokens` defaults to half of `maxTokens`. Set `toolResults: false` to send every result in full. `result.messages` and the saved conversation always keep every result in full. The name `read_tool_result` is reserved while previews are on.

## Context window

Restate Harness can't read the model's context window. Set `contextWindow` on the agent to the model's context window in tokens, for example `contextWindow: 128000`. Set it for a model with a context window under 200,000 tokens, because the default compaction threshold of 170,000 tokens doesn't fit such a window. For a model with a much larger window, such as 1,000,000 tokens, set it to start compaction later.

`contextWindow` sets the default [`compaction.maxTokens`](#compaction). Before each model call, the run also shrinks a request that wouldn't fit together with the reply: it summarizes the older messages, or truncates them when `compaction` is `false`.
For the reply, the run reserves `maxOutputTokens`, or 32,768 tokens when `maxOutputTokens` is unset. `contextWindow` must be greater than this reserve, or `agent()` throws a `TypeError`, so set `maxOutputTokens` for a model with a smaller context window.

If the provider reports a context overflow, the run shrinks the request once and sends it again. If the run can't shrink the request, or the new request overflows too, the run fails.
`aiModel` recognizes an overflow only from HTTP `413` or the provider error code `context_length_exceeded`. Any other overflow error fails the run, so set `contextWindow` for providers that don't return these signals. A [custom model](https://docs.restate.dev/harness/models.md#custom-models) reports an overflow by throwing `ContextOverflowError`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.