context-editing
build-with-claude/context-editing
History
build-with-claude/context-editing Changed · +21 / -88 lines
* **Thinking block clearing** - For managing thinking blocks when using extended thinking, with options to preserve recent thinking for context continuity * **Client-side SDK compaction** - An SDK-based alternative for summary-based context management (server-side compaction is generally preferred) -| Approach | Where it runs | Strategies | How it works | -| --------------- | ------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Server-side** | API | Tool result clearing (`clear_tool_uses_20250919`) Thinking block clearing (`clear_thinking_20251015`) | Applied before the prompt reaches Claude. Clears specific content from conversation history. Each strategy can be configured independently. | -| **Client-side** | SDK | Compaction | Available in [Python, TypeScript, and Ruby SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) when using [`tool_runner`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner). Generates a summary and replaces full conversation history. See [Client-side compaction](https://platform.claude.com/docs/en/build-with-claude/context-editing#client-side-compaction-sdk). | +| Approach | Where it runs | Strategies | How it works | +| --------------- | ------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Server-side** | API | Tool result clearing (`clear_tool_uses_20250919`) Thinking block clearing (`clear_thinking_20251015`) | Applied before the prompt reaches Claude. Clears specific content from conversation history. Each strategy can be configured independently. | +| **Client-side** | SDK | Compaction | Available in [TypeScript and Ruby SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) when using [`tool_runner`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner). Generates a summary and replaces full conversation history. See [Client-side compaction](https://platform.claude.com/docs/en/build-with-claude/context-editing#client-side-compaction-sdk). | ## Server-side strategies
<Warning> **Anthropic recommends server-side compaction over SDK compaction.** [Server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) handles context management automatically with less integration complexity, better token usage calculation, and no client-side limitations. Use SDK compaction only if you specifically need client-side control over the summarization process. - The `compaction_control` parameter is deprecated in the Python, TypeScript, and Ruby SDKs and will be removed in a future version. The SDKs emit a deprecation warning when it is enabled. To use server-side compaction with a tool runner, pass the `compact_20260112` edit in the request's `context_management` parameter. + The `compaction_control` parameter is deprecated in the TypeScript and Ruby SDKs and will be removed in a future version. The SDKs emit a deprecation warning when it is enabled. The Python SDK removed it in v1.0. To use server-side compaction with a tool runner, pass the `compact_20260112` edit in the request's `context_management` parameter. </Warning> <Note> - Compaction is available in the [Python, TypeScript, and Ruby SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) when using the [`tool_runner` method](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner). + Compaction is available in the [TypeScript and Ruby SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) when using the [`tool_runner` method](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner). </Note> Compaction is an SDK feature that automatically manages conversation context by generating summaries when token usage grows too large. Unlike server-side context editing strategies that clear content, compaction instructs Claude to summarize the conversation history, then replaces the full history with that summary. This allows Claude to continue working on long-running tasks that would otherwise exceed the [context window](https://platform.claude.com/docs/en/build-with-claude/context-windows).
</Tab> <Tab title="Python"> - ```python Python - client = anthropic.Anthropic() - - runner = client.beta.messages.tool_runner( - model="claude-opus-5", - max_tokens=1024, - tools=[read_file], - messages=[{"role": "user", "content": "What's in config.json?"}], - compaction_control={"enabled": True, "context_token_threshold": 100000}, - ) - - for message in runner: - print(f"Tokens used: {message.usage.input_tokens}") - ``` + <Note> + In v1.0 and later, the Python SDK's tool runner does not support client-side `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead: it works with the tool runner by passing the `compact_20260112` edit in the request's `context_management` parameter. + </Note> </Tab> <Tab title="TypeScript">
</Tab> <Tab title="Python"> - ```python Python - client = anthropic.Anthropic() - - runner = client.beta.messages.tool_runner( - model="claude-opus-5", - max_tokens=1024, - tools=[read_file], - messages=[{"role": "user", "content": "What's in config.json?"}], - # Lower values compact more often; raise to 150000 when the task needs more context - compaction_control={"enabled": True, "context_token_threshold": 50000}, - ) - - for message in runner: - print(f"Tokens used: {message.usage.input_tokens}") - ``` + <Note> + In v1.0 and later, the Python SDK's tool runner does not support client-side `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead: it works with the tool runner by passing the `compact_20260112` edit in the request's `context_management` parameter. + </Note> </Tab> <Tab title="TypeScript">
</Tab> <Tab title="Python"> - ```python Python - client = anthropic.Anthropic() - - runner = client.beta.messages.tool_runner( - model="claude-opus-5", - max_tokens=1024, - tools=[read_file], - messages=[{"role": "user", "content": "What's in config.json?"}], - compaction_control={ - "enabled": True, - "context_token_threshold": 100000, - "model": "claude-haiku-4-5", - }, - ) - - for message in runner: - print(f"Tokens used: {message.usage.input_tokens}") - ``` + <Note> + In v1.0 and later, the Python SDK's tool runner does not support client-side `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead: it works with the tool runner by passing the `compact_20260112` edit in the request's `context_management` parameter. + </Note> </Tab> <Tab title="TypeScript">
</Tab> <Tab title="Python"> - ```python Python - client = anthropic.Anthropic() - - runner = client.beta.messages.tool_runner( - model="claude-opus-5", - max_tokens=1024, - tools=[read_file], - messages=[{"role": "user", "content": "What's in config.json?"}], - compaction_control={ - "enabled": True, - "context_token_threshold": 100000, - "summary_prompt": """Summarize the research conducted so far, including: - - Sources consulted and key findings - - Questions answered and remaining unknowns - - Recommended next steps - - Wrap your summary in <summary></summary> tags.""", - }, - ) - - for message in runner: - print(f"Tokens used: {message.usage.input_tokens}") - ``` + <Note> + In v1.0 and later, the Python SDK's tool runner does not support client-side `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead: it works with the tool runner by passing the `compact_20260112` edit in the request's `context_management` parameter. + </Note> </Tab> <Tab title="TypeScript">
</Tab> <Tab title="Python"> - The Python SDK logs compaction events at the INFO level. Enable the `anthropic.lib.tools` logger: - - ```python Python - import logging - - logging.basicConfig(level=logging.INFO) - logging.getLogger("anthropic.lib.tools").setLevel(logging.INFO) - - # Logs will show: - # INFO: Token usage 105000 has exceeded the threshold of 100000. Performing compaction. - # INFO: Compaction complete. New token usage: 2500 - ``` + <Note> + In v1.0 and later, the Python SDK's tool runner does not support `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead. + </Note> </Tab> <Tab title="TypeScript">
build-with-claude/context-editing First recorded · 3023 lines, first recorded
## Overview ## Server-side strategies ### Tool result clearing ### Thinking block clearing ### Context editing happens server-side ### Context editing and prompt caching ## Supported models ## Tool result clearing usage ### Advanced configuration ## Thinking block clearing usage ### Configuration options for thinking block clearing ### Combining strategies ## Configuration options for tool result clearing ## Context editing response ## Token counting ## Using with the memory tool ## Client-side compaction (SDK) ### How compaction works ### Using compaction #### What occurs during compaction ### Configuration options #### Choosing a token threshold #### Using a different model for summaries #### Custom summary prompts ### Default summary prompt ### Limitations #### Server-side tools #### Tool use edge cases ### Monitoring compaction ### When to use compaction ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: Context editing
url: https://platform.claude.com/docs/en/build-with-claude/context-editing
description: Automatically manage conversation context as it grows with context editing.
---
<Note>
For how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).
</Note>
## Overview
<Note>
For most use cases, [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) is the primary strategy for managing context in long-running conversations. The strategies on this page are useful for specific scenarios where you need more fine-grained control over what content is cleared.
</Note>
Context editing allows you to selectively clear specific content from conversation history as it grows. Beyond optimizing costs and staying within limits, this is about actively curating what Claude sees: context is a finite resource with diminishing returns, and irrelevant content degrades model focus. Context editing gives you fine-grained runtime control over that curation. For the broader principles behind context management, see [Effective context engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents). This page covers:
* **Tool result clearing** - Best for agentic workflows with heavy tool use where old tool results are no longer needed
* **Thinking block clearing** - For managing thinking blocks when using extended thinking, with options to preserve recent thinking for context continuity
* **Client-side SDK compaction** - An SDK-based alternative for summary-based context management (server-side compaction is generally preferred)
| Approach | Where it runs | Strategies | How it works |
| --------------- | ------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Server-side** | API | Tool result clearing (`clear_tool_uses_20250919`) Thinking block clearing (`clear_thinking_20251015`) | Applied before the prompt reaches Claude. Clears specific content from conversation history. Each strategy can be configured independently. |
| **Client-side** | SDK | Compaction | Available in [Python, TypeScript, and Ruby SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) when using [`tool_runner`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner). Generates a summary and replaces full conversation history. See [Client-side compaction](https://platform.claude.com/docs/en/build-with-claude/context-editing#client-side-compaction-sdk). |
## Server-side strategies
<Note>
Context editing is in beta with support for tool result clearing and thinking block clearing. To enable it, use the beta header `context-management-2025-06-27` in your API requests.
Share feedback on this feature through the [feedback form](https://forms.gle/YXC2EKGMhjN1c4L88).
</Note>
### Tool result clearing
The `clear_tool_uses_20250919` strategy clears tool results when conversation context grows beyond your configured threshold. This is particularly useful for agentic workflows with heavy tool use. Older tool results (like file contents or search results) are no longer needed once Claude has processed them.
When activated, the API automatically clears the oldest tool results in chronological order. The API replaces each cleared result with placeholder text indicating to Claude that it was removed. By default, only tool results are cleared. You can optionally clear both tool results and tool calls (the tool use parameters) by setting `clear_tool_inputs` to true.
### Thinking block clearing
The `clear_thinking_20251015` strategy manages `thinking` blocks in conversations when extended thinking is enabled. This strategy gives you control over thinking preservation: you can choose to keep more thinking blocks to maintain reasoning continuity, or clear them more aggressively to save context space.
<Tip>
**Default behavior:** The default varies by model class.
| Model class | Keep all prior thinking | Keep only the last turn's thinking |
| ----------- | --------------------------- | ----------------------------------- |
| Opus | Claude Opus 4.5 and later | Claude Opus 4.1 and earlier |
| Sonnet | Claude Sonnet 4.6 and later | Claude Sonnet 4.5 and earlier |
| Haiku | (none) | All models through Claude Haiku 4.5 |
Use this strategy to override the default. If your code runs across multiple model tiers, set `keep` explicitly rather than relying on the per-model default.
</Tip>
An assistant conversation turn may include multiple content blocks (for example, when using tools) and multiple thinking blocks (for example, with [interleaved thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking)).
### Context editing happens server-side
Context editing is applied server-side before the prompt reaches Claude. Your client application maintains the full, unmodified conversation history. You do not need to sync your client state with the edited version. Continue managing your full conversation history locally as you normally would.
### Context editing and prompt caching
Context editing's interaction with [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) varies by strategy:
* **Tool result clearing:** Invalidates cached prompt prefixes when content is cleared. To account for this, clear enough tokens to make the cache invalidation worthwhile. Use the `clear_at_least` parameter to ensure a minimum number of tokens is cleared each time. You'll incur cache write costs each time content is cleared, but subsequent requests can reuse the newly cached prefix.
* **Thinking block clearing:** When thinking blocks are **kept** in context (not cleared), the prompt cache is preserved, enabling cache hits and reducing input token costs. When thinking blocks are **cleared**, the cache is invalidated at the point where clearing occurs. Configure the `keep` parameter based on whether you want to prioritize cache performance or context window availability.
## Supported models
Context editing is available on all supported Claude models.
## Tool result clearing usage
The simplest way to enable tool result clearing is to specify only the strategy type. All other [configuration options](https://platform.claude.com/docs/en/build-with-claude/context-editing#configuration-options-for-tool-result-clearing) use their default values:
<CodeGroup>
```bash cURL
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "anthropic-beta: context-management-2025-06-27" \
--data '{
"model": "claude-opus-5",
"max_tokens": 4096,
"messages": [
{
"role": "user",
"content": "Search for recent developments in AI"
}
],
"tools": [
{
"type": "web_search_20250305",
"name": "web_search"
}
],
"context_management": {
"edits": [
{"type": "clear_tool_uses_20250919"}
]
}
}'
```
```bash CLI
ant beta:messages create --beta context-management-2025-06-27 <<'YAML'
model: claude-opus-5
max_tokens: 4096
messages:
- role: user
content: Search for recent developments in AI
tools:
- type: web_search_20250305
name: web_search
context_management:
edits:
- type: clear_tool_uses_20250919
YAML
```
```python Python
response = client.beta.messages.create(
model="claude-opus-5",
max_tokens=4096,
messages=[{"role": "user", "content": "Search for recent developments in AI"}],
tools=[{"type": "web_search_20250305", "name": "web_search"}],
betas=["context-management-2025-06-27"],
context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
)
```
```typescript TypeScript
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
const response = await anthropic.beta.messages.create({
model: "claude-opus-5",
max_tokens: 4096,
messages: [
{
role: "user",
content: "Search for recent developments in AI"
}
],
tools: [
{
type: "web_search_20250305",
name: "web_search"
}
],
context_management: {
edits: [{ type: "clear_tool_uses_20250919" }]
},
betas: ["context-management-2025-06-27"]
});
```
```csharp C#
using Anthropic;
using Anthropic.Models.Beta;
using Anthropic.Models.Beta.Messages;
using Messages = Anthropic.Models.Messages;
AnthropicClient client = new();
var parameters = new MessageCreateParams
{
Model = Messages::Model.ClaudeOpus5,
MaxTokens = 4096,
Messages = [
new() { Role = Role.User, Content = "Search for recent developments in AI" }
],
Tools = [
new BetaWebSearchTool20250305()
],
ContextManagement = new BetaContextManagementConfig
{
Edits = [new BetaClearToolUses20250919Edit()]
},
Betas = [AnthropicBeta.ContextManagement2025_06_27]
};
var response = await client.Beta.Messages.Create(parameters);
Console.WriteLine(response);
```
```go Go
client := anthropic.NewClient()
response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 4096,
Messages: []anthropic.BetaMessageParam{
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Search for recent developments in AI")),
},
Tools: []anthropic.BetaToolUnionParam{
{OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{}},
},
ContextManagement: anthropic.BetaContextManagementConfigParam{
Edits: []anthropic.BetaContextManagementConfigEditUnionParam{
{OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{}},
},
},
Betas: []anthropic.AnthropicBeta{
anthropic.AnthropicBetaContextManagement2025_06_27,
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(response)
```
```java Java
import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;
import com.anthropic.models.beta.messages.BetaContextManagementConfig;
import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;
import com.anthropic.models.beta.AnthropicBeta;
// ...
void main() {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_5)
.maxTokens(4096L)
.addUserMessage("Search for recent developments in AI")
.addTool(BetaWebSearchTool20250305.builder().build())
.contextManagement(BetaContextManagementConfig.builder()
.addEdit(BetaClearToolUses20250919Edit.builder().build())
.build())
.addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)
.build();
BetaMessage response = client.beta().messages().create(params);
IO.println(response);
}
```
```php PHP
$client = new Client();
$response = $client->beta->messages->create(
maxTokens: 4096,
messages: [
['role' => 'user', 'content' => 'Search for recent developments in AI']
],
model: 'claude-opus-5',
betas: ['context-management-2025-06-27'],
tools: [
['type' => 'web_search_20250305', 'name' => 'web_search']
],
contextManagement: [
'edits' => [
['type' => 'clear_tool_uses_20250919']
]
],
);
echo $response;
```
```ruby Ruby
client = Anthropic::Client.new
response = client.beta.messages.create(
model: "claude-opus-5",
max_tokens: 4096,
messages: [
{ role: "user", content: "Search for recent developments in AI" }
],
tools: [
{ type: "web_search_20250305", name: "web_search" }
],
context_management: {
edits: [
{ type: "clear_tool_uses_20250919" }
]
},
betas: ["context-management-2025-06-27"]
)
puts response
```
</CodeGroup>
### Advanced configuration
You can customize the tool result clearing behavior with additional parameters:
<CodeGroup>
```bash cURL
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
Cut at 300 lines.