Keep long conversations manageable
Long-running agents can outgrow the amount of conversation a model can read at
once. Compaction saves older turns separately so the agent can continue with
recent messages and retrieve earlier details when needed. It is different from
shortening a large tool result or saving shared application data in
ContextStore.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
from ish import Agent
agent = Agent(
model="gpt-4o-mini",
instructions="Help with the task and preserve important facts from the conversation.",
context_compaction="auto",
compaction_turn_threshold=12,
context_window_tokens=32_768,
)
import { Agent } from "ish-harness";
const agent = new Agent({
model: { provider: "openai_chat", name: "gpt-4o-mini" },
instructions:
"Help with the task and preserve important facts from the conversation.",
context_compaction: true,
compaction_turn_threshold: 12,
context_window_tokens: 32_768,
});
use std::sync::Arc;
use ish_harness::{Agent, OpenAIModel, RunnerConfig};
let config = RunnerConfig {
context_compaction: true,
compaction_turn_threshold: 12,
context_window_tokens: Some(32_768),
..RunnerConfig::default()
};
let agent = Agent::builder(Arc::new(model))
.instructions("Help with the task and preserve important facts from the conversation.")
.config(config)
.build()?;
result, err := client.Run(ctx, ish.AgentRunRequest{
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
SystemPrompt: ish.StringPtr("Help with the task and preserve important facts from the conversation."),
UserPrompt: ish.StringPtr("Continue the current task."),
ContextCompaction: true,
CompactionTurnThreshold: ish.IntPtr(12),
ContextWindowTokens: ish.IntPtr(32_768),
})
using Ish.Harness;
using System.Text.Json;
using var client = new IshClient();
var result = client.Run(new AgentRunRequest
{
Model = new AgentModel { Provider = "openai_chat", Name: "gpt-4o-mini" },
SystemPrompt = "Help with the task and preserve important facts from the conversation.",
UserPrompt = "Continue the current task.",
ContextCompaction = JsonSerializer.SerializeToElement(true),
CompactionTurnThreshold = 12,
ContextWindowTokens = 32_768,
});
import io.github.ishharness.IshClient;
import java.nio.file.Path;
try (var client = new IshClient(Path.of(System.getenv("ISH_NATIVE_LIBRARY")));
var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Help with the task and preserve important facts from the conversation.",
"Continue the current task.")
.provider("openai_chat")
.contextCompaction(true)
.compactionTurnThreshold(12)
.contextWindowTokens(32_768)) {
var result = client.runAgent(request);
System.out.println(result.path("content").asText());
}
Compaction is off by default. Enable it when long conversations approach the model's context limit. The runtime keeps the opening instructions and recent turns, archives older complete exchanges, and can retrieve archived details when the agent needs them. Shared values in ContextStore are separate and are not removed by conversation compaction.
When compaction runs
Choose a turn threshold, a context-window budget, or both. The runtime compacts before sending a prompt that is likely to exceed the configured budget. Compaction preserves complete tool-call exchanges, so a prompt never contains a tool result without its matching request.
What stays available
The opening instructions and recent turns remain in the prompt. Older turns stay in the archive and can be read in pages. If you also enable tool-result offloading, that feature shortens individual tool outputs; it does not replace conversation archival.
Configure automatic compaction across SDKs
Manual compaction (ContextCompactor / compact_messages)
Every SDK also exposes the standalone Rust message compactor (ContextCompactor
in Python, TypeScript, Go, C#, and Java; ish_harness::context::compact_messages
and compact_messages_recoverable in Rust). Defaults are max_messages = 40,
keep_first = 2, and keep_last = 20.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
from ish import ChatMessage, ContextCompactor
messages = [
ChatMessage(role="user", content="first"),
ChatMessage(role="assistant", content="middle"),
ChatMessage(role="user", content="last"),
]
compacted = ContextCompactor.compact(messages, max_messages=2, keep_first=1, keep_last=1)
import { ContextCompactor, IshClient } from "ish-harness";
const client = new IshClient();
const compacted = ContextCompactor.compact(
client,
[
{ role: "user", content: "first" },
{ role: "assistant", content: "middle" },
{ role: "user", content: "last" },
],
{ max_messages: 2, keep_first: 1, keep_last: 1 },
);
client.close();
use ish_harness::context::compact_messages;
use ish_harness::types::ChatMessage;
let messages = vec![
ChatMessage::user("first"),
ChatMessage::assistant("middle"),
ChatMessage::user("last"),
];
let compacted = compact_messages(messages, 2, 1, 1);
compacted, err := ish.ContextCompactor{}.Compact(
client,
[]map[string]any{
{"role": "user", "content": "first"},
{"role": "assistant", "content": "middle"},
{"role": "user", "content": "last"},
},
2,
1,
1,
)
using System.Text.Json;
using Ish.Harness;
using var client = new IshClient();
using var messages = JsonDocument.Parse(
"""[{"role":"user","content":"first"},{"role":"assistant","content":"middle"},{"role":"user","content":"last"}]""");
var compacted = ContextCompactor.Compact(
client, messages.RootElement.EnumerateArray(), maxMessages: 2, keepFirst: 1, keepLast: 1);
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.ishharness.ContextCompactor;
import io.github.ishharness.IshClient;
import java.nio.file.Path;
import java.util.List;
var mapper = new ObjectMapper();
var messages = List.of(
mapper.createObjectNode().put("role", "user").put("content", "first"),
mapper.createObjectNode().put("role", "assistant").put("content", "middle"),
mapper.createObjectNode().put("role", "user").put("content", "last"));
try (var client = new IshClient(Path.of(System.getenv("ISH_NATIVE_LIBRARY")))) {
var compacted = ContextCompactor.compact(client, messages, 2, 1, 1);
System.out.println("Compacted message count: " + compacted.size());
}
When to use compaction
Enable compaction (and optionally context_window_tokens) for long conversations.
ISH saves older turns outside the active prompt and can retrieve them later if
needed. Keep critical rules in system instructions or ContextStore rather than
relying only on old chat messages. Use tool output management
to keep large tool results from filling the conversation.