Repository Public
1---2title: Context editing3url: https://platform.claude.com/docs/en/build-with-claude/context-editing4description: Automatically manage conversation context as it grows with context editing.5---67<Note>8 To learn 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).9</Note>1011## Overview1213<Note>14 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.15</Note>1617Context 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:1819* **Tool result clearing** - Best for agentic workflows with heavy tool use where old tool results are no longer needed20* **Thinking block clearing** - For managing thinking blocks when using extended thinking, with options to preserve recent thinking for context continuity21* **Client-side SDK compaction** - An SDK-based alternative for summary-based context management (server-side compaction is generally preferred)2223| Approach | Where it runs | Strategies | How it works |24| --------------- | ------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |25| **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. |26| **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). |2728## Server-side strategies2930<Note>31 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.3233 Share feedback on this feature through the [feedback form](https://forms.gle/YXC2EKGMhjN1c4L88).34</Note>3536### Tool result clearing3738The `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.3940When 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.4142### Thinking block clearing4344The `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.4546<Tip>47 **Default behavior:** The default varies by model class.4849 | Model class | Keep all prior thinking | Keep only the last turn's thinking |50 | ---------------- | --------------------------- | ----------------------------------- |51 | Opus | Claude Opus 4.5 and later | Claude Opus 4.1 and earlier |52 | Sonnet | Claude Sonnet 4.6 and later | Claude Sonnet 4.5 and earlier |53 | Haiku | (none) | All models through Claude Haiku 4.5 |54 | Fable and Mythos | All models | (none) |5556 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.57</Tip>5859An 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)).6061### Context editing happens server-side6263Context 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.6465On Claude Fable 5.1, server-side context management never invalidates thinking blocks. Client-side edits to earlier turns can invalidate the thinking blocks in every later assistant turn. For new accounts created on or after August 31, 2026, a request that replays an invalidated block is rejected unless you opt into dropping it. See [Keeping the prefix unchanged](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#prefix-check).6667### Context editing and prompt caching6869Context editing's interaction with [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) varies by strategy:7071* **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.7273* **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.7475## Supported models7677Context editing is available on all supported Claude models.7879## Tool result clearing usage8081The 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:8283<CodeGroup>84 ```bash cURL85 curl https://api.anthropic.com/v1/messages \86 --header "x-api-key: $ANTHROPIC_API_KEY" \87 --header "anthropic-version: 2023-06-01" \88 --header "content-type: application/json" \89 --header "anthropic-beta: context-management-2025-06-27" \90 --data '{91 "model": "claude-opus-5",92 "max_tokens": 4096,93 "messages": [94 {95 "role": "user",96 "content": "Search for recent developments in AI"97 }98 ],99 "tools": [100 {101 "type": "web_search_20250305",102 "name": "web_search"103 }104 ],105 "context_management": {106 "edits": [107 {"type": "clear_tool_uses_20250919"}108 ]109 }110 }'111 ```112113 ```bash CLI114 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'115 model: claude-opus-5116 max_tokens: 4096117 messages:118 - role: user119 content: Search for recent developments in AI120 tools:121 - type: web_search_20250305122 name: web_search123 context_management:124 edits:125 - type: clear_tool_uses_20250919126 YAML127 ```128129 ```python Python130 response = client.beta.messages.create(131 model="claude-opus-5",132 max_tokens=4096,133 messages=[{"role": "user", "content": "Search for recent developments in AI"}],134 tools=[{"type": "web_search_20250305", "name": "web_search"}],135 betas=["context-management-2025-06-27"],136 context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},137 )138 ```139140 ```typescript TypeScript141 const anthropic = new Anthropic({142 apiKey: process.env.ANTHROPIC_API_KEY143 });144145 const response = await anthropic.beta.messages.create({146 model: "claude-opus-5",147 max_tokens: 4096,148 messages: [149 {150 role: "user",151 content: "Search for recent developments in AI"152 }153 ],154 tools: [155 {156 type: "web_search_20250305",157 name: "web_search"158 }159 ],160 context_management: {161 edits: [{ type: "clear_tool_uses_20250919" }]162 },163 betas: ["context-management-2025-06-27"]164 });165 ```166167 ```csharp C#168 using Anthropic;169 using Anthropic.Models.Beta;170 using Anthropic.Models.Beta.Messages;171 using Messages = Anthropic.Models.Messages;172173 AnthropicClient client = new();174175 var parameters = new MessageCreateParams176 {177 Model = Messages::Model.ClaudeOpus5,178 MaxTokens = 4096,179 Messages = [180 new() { Role = Role.User, Content = "Search for recent developments in AI" }181 ],182 Tools = [183 new BetaWebSearchTool20250305()184 ],185 ContextManagement = new BetaContextManagementConfig186 {187 Edits = [new BetaClearToolUses20250919Edit()]188 },189 Betas = [AnthropicBeta.ContextManagement2025_06_27]190 };191192 var response = await client.Beta.Messages.Create(parameters);193 Console.WriteLine(response);194 ```195196 ```go Go197 client := anthropic.NewClient()198199 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{200 Model: anthropic.ModelClaudeOpus5,201 MaxTokens: 4096,202 Messages: []anthropic.BetaMessageParam{203 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Search for recent developments in AI")),204 },205 Tools: []anthropic.BetaToolUnionParam{206 {OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{}},207 },208 ContextManagement: anthropic.BetaContextManagementConfigParam{209 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{210 {OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{}},211 },212 },213 Betas: []anthropic.AnthropicBeta{214 anthropic.AnthropicBetaContextManagement2025_06_27,215 },216 })217 if err != nil {218 log.Fatal(err)219 }220 fmt.Println(response)221 ```222223 ```java Java224 import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;225 import com.anthropic.models.beta.messages.BetaContextManagementConfig;226 import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;227 import com.anthropic.models.beta.AnthropicBeta;228 // ...229 void main() {230 AnthropicClient client = AnthropicOkHttpClient.fromEnv();231232 MessageCreateParams params = MessageCreateParams.builder()233 .model(Model.CLAUDE_OPUS_5)234 .maxTokens(4096L)235 .addUserMessage("Search for recent developments in AI")236 .addTool(BetaWebSearchTool20250305.builder().build())237 .contextManagement(BetaContextManagementConfig.builder()238 .addEdit(BetaClearToolUses20250919Edit.builder().build())239 .build())240 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)241 .build();242243 BetaMessage response = client.beta().messages().create(params);244 IO.println(response);245 }246 ```247248 ```php PHP249 $client = new Client();250251 $response = $client->beta->messages->create(252 maxTokens: 4096,253 messages: [254 ['role' => 'user', 'content' => 'Search for recent developments in AI']255 ],256 model: 'claude-opus-5',257 betas: ['context-management-2025-06-27'],258 tools: [259 ['type' => 'web_search_20250305', 'name' => 'web_search']260 ],261 contextManagement: [262 'edits' => [263 ['type' => 'clear_tool_uses_20250919']264 ]265 ],266 );267268 echo $response;269 ```270271 ```ruby Ruby272 client = Anthropic::Client.new273274 response = client.beta.messages.create(275 model: "claude-opus-5",276 max_tokens: 4096,277 messages: [278 { role: "user", content: "Search for recent developments in AI" }279 ],280 tools: [281 { type: "web_search_20250305", name: "web_search" }282 ],283 context_management: {284 edits: [285 { type: "clear_tool_uses_20250919" }286 ]287 },288 betas: ["context-management-2025-06-27"]289 )290 puts response291 ```292</CodeGroup>293294### Advanced configuration295296You can customize the tool result clearing behavior with additional parameters:297298<CodeGroup>299 ```bash cURL300 curl https://api.anthropic.com/v1/messages \301 --header "x-api-key: $ANTHROPIC_API_KEY" \302 --header "anthropic-version: 2023-06-01" \303 --header "content-type: application/json" \304 --header "anthropic-beta: context-management-2025-06-27" \305 --data '{306 "model": "claude-opus-5",307 "max_tokens": 4096,308 "messages": [309 {310 "role": "user",311 "content": "Create a simple command line calculator app using Python"312 }313 ],314 "tools": [315 {316 "type": "text_editor_20250728",317 "name": "str_replace_based_edit_tool",318 "max_characters": 10000319 },320 {321 "type": "web_search_20250305",322 "name": "web_search",323 "max_uses": 3324 }325 ],326 "context_management": {327 "edits": [328 {329 "type": "clear_tool_uses_20250919",330 "trigger": {331 "type": "input_tokens",332 "value": 30000333 },334 "keep": {335 "type": "tool_uses",336 "value": 3337 },338 "clear_at_least": {339 "type": "input_tokens",340 "value": 5000341 },342 "exclude_tools": ["web_search"]343 }344 ]345 }346 }'347 ```348349 ```bash CLI350 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'351 model: claude-opus-5352 max_tokens: 4096353 messages:354 - role: user355 content: Create a simple command line calculator app using Python356 tools:357 - type: text_editor_20250728358 name: str_replace_based_edit_tool359 max_characters: 10000360 - type: web_search_20250305361 name: web_search362 max_uses: 3363 context_management:364 edits:365 - type: clear_tool_uses_20250919366 trigger:367 type: input_tokens368 value: 30000369 keep:370 type: tool_uses371 value: 3372 clear_at_least:373 type: input_tokens374 value: 5000375 exclude_tools:376 - web_search377 YAML378 ```379380 ```python Python381 response = client.beta.messages.create(382 model="claude-opus-5",383 max_tokens=4096,384 messages=[385 {386 "role": "user",387 "content": "Create a simple command line calculator app using Python",388 }389 ],390 tools=[391 {392 "type": "text_editor_20250728",393 "name": "str_replace_based_edit_tool",394 "max_characters": 10000,395 },396 {"type": "web_search_20250305", "name": "web_search", "max_uses": 3},397 ],398 betas=["context-management-2025-06-27"],399 context_management={400 "edits": [401 {402 "type": "clear_tool_uses_20250919",403 # Trigger clearing when threshold is exceeded404 "trigger": {"type": "input_tokens", "value": 30000},405 # Number of tool uses to keep after clearing406 "keep": {"type": "tool_uses", "value": 3},407 # Optional: Clear at least this many tokens408 "clear_at_least": {"type": "input_tokens", "value": 5000},409 # Exclude these tools from being cleared410 "exclude_tools": ["web_search"],411 }412 ]413 },414 )415 ```416417 ```typescript TypeScript418 const anthropic = new Anthropic({419 apiKey: process.env.ANTHROPIC_API_KEY420 });421422 const response = await anthropic.beta.messages.create({423 model: "claude-opus-5",424 max_tokens: 4096,425 messages: [426 {427 role: "user",428 content: "Create a simple command line calculator app using Python"429 }430 ],431 tools: [432 {433 type: "text_editor_20250728",434 name: "str_replace_based_edit_tool",435 max_characters: 10000436 },437 {438 type: "web_search_20250305",439 name: "web_search",440 max_uses: 3441 }442 ],443 betas: ["context-management-2025-06-27"],444 context_management: {445 edits: [446 {447 type: "clear_tool_uses_20250919",448 // Trigger clearing when threshold is exceeded449 trigger: {450 type: "input_tokens",451 value: 30000452 },453 // Number of tool uses to keep after clearing454 keep: {455 type: "tool_uses",456 value: 3457 },458 // Optional: Clear at least this many tokens459 clear_at_least: {460 type: "input_tokens",461 value: 5000462 },463 // Exclude these tools from being cleared464 exclude_tools: ["web_search"]465 }466 ]467 }468 });469 ```470471 ```csharp C#472 using Anthropic;473 using Anthropic.Models.Beta;474 using Anthropic.Models.Beta.Messages;475 using Messages = Anthropic.Models.Messages;476477 AnthropicClient client = new();478479 var parameters = new MessageCreateParams480 {481 Model = Messages::Model.ClaudeOpus5,482 MaxTokens = 4096,483 Messages = [484 new() { Role = Role.User, Content = "Create a simple command line calculator app using Python" }485 ],486 Tools = [487 new BetaToolTextEditor20250728 { MaxCharacters = 10000 },488 new BetaWebSearchTool20250305 { MaxUses = 3 }489 ],490 Betas = [AnthropicBeta.ContextManagement2025_06_27],491 ContextManagement = new BetaContextManagementConfig492 {493 Edits = [494 new BetaClearToolUses20250919Edit495 {496 Trigger = new BetaInputTokensTrigger(30000),497 Keep = new BetaToolUsesKeep(3),498 ClearAtLeast = new BetaInputTokensClearAtLeast(5000),499 ExcludeTools = ["web_search"]500 }501 ]502 }503 };504505 var response = await client.Beta.Messages.Create(parameters);506 Console.WriteLine(response);507 ```508509 ```go Go510 client := anthropic.NewClient()511512 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{513 Model: anthropic.ModelClaudeOpus5,514 MaxTokens: 4096,515 Messages: []anthropic.BetaMessageParam{516 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Create a simple command line calculator app using Python")),517 },518 Tools: []anthropic.BetaToolUnionParam{519 {OfTextEditor20250728: &anthropic.BetaToolTextEditor20250728Param{520 MaxCharacters: anthropic.Int(10000),521 }},522 {OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{523 MaxUses: anthropic.Int(3),524 }},525 },526 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},527 ContextManagement: anthropic.BetaContextManagementConfigParam{528 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{529 {OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{530 Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{531 OfInputTokens: &anthropic.BetaInputTokensTriggerParam{532 Value: 30000,533 },534 },535 Keep: anthropic.BetaToolUsesKeepParam{536 Value: 3,537 },538 ClearAtLeast: anthropic.BetaInputTokensClearAtLeastParam{539 Value: 5000,540 },541 ExcludeTools: []string{"web_search"},542 }},543 },544 },545 })546 if err != nil {547 log.Fatal(err)548 }549 fmt.Println(response)550 ```551552 ```java Java553 import com.anthropic.models.beta.messages.BetaToolTextEditor20250728;554 import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;555 import com.anthropic.models.beta.messages.BetaContextManagementConfig;556 import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;557 import com.anthropic.models.beta.messages.BetaInputTokensTrigger;558 import com.anthropic.models.beta.messages.BetaInputTokensClearAtLeast;559 import com.anthropic.models.beta.messages.BetaToolUsesKeep;560 import com.anthropic.models.beta.AnthropicBeta;561 // ...562 void main() {563 AnthropicClient client = AnthropicOkHttpClient.fromEnv();564565 MessageCreateParams params = MessageCreateParams.builder()566 .model(Model.CLAUDE_OPUS_5)567 .maxTokens(4096L)568 .addUserMessage("Create a simple command line calculator app using Python")569 .addTool(BetaToolTextEditor20250728.builder()570 .maxCharacters(10000L)571 .build())572 .addTool(BetaWebSearchTool20250305.builder()573 .maxUses(3L)574 .build())575 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)576 .contextManagement(BetaContextManagementConfig.builder()577 .addEdit(BetaClearToolUses20250919Edit.builder()578 .trigger(BetaInputTokensTrigger.builder()579 .value(30000L)580 .build())581 .keep(BetaToolUsesKeep.builder()582 .value(3L)583 .build())584 .clearAtLeast(BetaInputTokensClearAtLeast.builder()585 .value(5000L)586 .build())587 .addExcludeTool("web_search")588 .build())589 .build())590 .build();591592 BetaMessage response = client.beta().messages().create(params);593 IO.println(response);594 }595 ```596597 ```php PHP598 $client = new Client();599600 $response = $client->beta->messages->create(601 maxTokens: 4096,602 messages: [603 [604 'role' => 'user',605 'content' => 'Create a simple command line calculator app using Python'606 ]607 ],608 model: 'claude-opus-5',609 betas: ['context-management-2025-06-27'],610 tools: [611 [612 'type' => 'text_editor_20250728',613 'name' => 'str_replace_based_edit_tool',614 'max_characters' => 10000615 ],616 [617 'type' => 'web_search_20250305',618 'name' => 'web_search',619 'max_uses' => 3620 ]621 ],622 contextManagement: [623 'edits' => [624 [625 'type' => 'clear_tool_uses_20250919',626 'trigger' => [627 'type' => 'input_tokens',628 'value' => 30000629 ],630 'keep' => [631 'type' => 'tool_uses',632 'value' => 3633 ],634 'clear_at_least' => [635 'type' => 'input_tokens',636 'value' => 5000637 ],638 'exclude_tools' => ['web_search']639 ]640 ]641 ],642 );643644 echo $response;645 ```646647 ```ruby Ruby648 client = Anthropic::Client.new649650 response = client.beta.messages.create(651 model: "claude-opus-5",652 max_tokens: 4096,653 messages: [654 {655 role: "user",656 content: "Create a simple command line calculator app using Python"657 }658 ],659 tools: [660 {661 type: "text_editor_20250728",662 name: "str_replace_based_edit_tool",663 max_characters: 10000664 },665 {666 type: "web_search_20250305",667 name: "web_search",668 max_uses: 3669 }670 ],671 betas: ["context-management-2025-06-27"],672 context_management: {673 edits: [674 {675 type: "clear_tool_uses_20250919",676 trigger: {677 type: "input_tokens",678 value: 30000679 },680 keep: {681 type: "tool_uses",682 value: 3683 },684 clear_at_least: {685 type: "input_tokens",686 value: 5000687 },688 exclude_tools: ["web_search"]689 }690 ]691 }692 )693 puts response694 ```695</CodeGroup>696697## Thinking block clearing usage698699Enable thinking block clearing to manage context and prompt caching effectively when extended thinking is enabled:700701<CodeGroup>702 ```bash cURL703 curl https://api.anthropic.com/v1/messages \704 --header "x-api-key: $ANTHROPIC_API_KEY" \705 --header "anthropic-version: 2023-06-01" \706 --header "content-type: application/json" \707 --header "anthropic-beta: context-management-2025-06-27" \708 --data '{709 "model": "claude-opus-5",710 "max_tokens": 16000,711 "messages": [{"role": "user", "content": "Hello"}],712 "context_management": {713 "edits": [714 {715 "type": "clear_thinking_20251015",716 "keep": {717 "type": "thinking_turns",718 "value": 2719 }720 }721 ]722 }723 }'724 ```725726 ```bash CLI727 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'728 model: claude-opus-5729 max_tokens: 16000730 messages:731 - role: user732 content: Hello733 context_management:734 edits:735 - type: clear_thinking_20251015736 keep:737 type: thinking_turns738 value: 2739 YAML740 ```741742 ```python Python743 response = client.beta.messages.create(744 model="claude-opus-5",745 max_tokens=16000,746 messages=[{"role": "user", "content": "Hello"}],747 betas=["context-management-2025-06-27"],748 context_management={749 "edits": [750 {751 "type": "clear_thinking_20251015",752 "keep": {"type": "thinking_turns", "value": 2},753 }754 ]755 },756 )757 ```758759 ```typescript TypeScript760 const anthropic = new Anthropic({761 apiKey: process.env.ANTHROPIC_API_KEY762 });763764 const response = await anthropic.beta.messages.create({765 model: "claude-opus-5",766 max_tokens: 16000,767 messages: [{ role: "user", content: "Hello" }],768 betas: ["context-management-2025-06-27"],769 context_management: {770 edits: [771 {772 type: "clear_thinking_20251015",773 keep: {774 type: "thinking_turns",775 value: 2776 }777 }778 ]779 }780 });781 ```782783 ```csharp C#784 using Anthropic;785 using Anthropic.Models.Beta;786 using Anthropic.Models.Beta.Messages;787 using Messages = Anthropic.Models.Messages;788789 AnthropicClient client = new();790791 var parameters = new MessageCreateParams792 {793 Model = Messages::Model.ClaudeOpus5,794 MaxTokens = 16000,795 Messages = [796 new() { Role = Role.User, Content = "Hello" }797 ],798 Betas = [AnthropicBeta.ContextManagement2025_06_27],799 ContextManagement = new BetaContextManagementConfig800 {801 Edits = [802 new BetaClearThinking20251015Edit803 {804 Keep = new BetaThinkingTurns(2)805 }806 ]807 }808 };809810 var response = await client.Beta.Messages.Create(parameters);811 Console.WriteLine(response);812 ```813814 ```go Go815 client := anthropic.NewClient()816817 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{818 Model: anthropic.ModelClaudeOpus5,819 MaxTokens: 16000,820 Messages: []anthropic.BetaMessageParam{821 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),822 },823 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},824 ContextManagement: anthropic.BetaContextManagementConfigParam{825 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{826 {OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{827 Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{828 OfThinkingTurns: &anthropic.BetaThinkingTurnsParam{829 Value: 2,830 },831 },832 }},833 },834 },835 })836 if err != nil {837 log.Fatal(err)838 }839 fmt.Println(response)840 ```841842 ```java Java843 import com.anthropic.models.beta.messages.BetaContextManagementConfig;844 import com.anthropic.models.beta.messages.BetaClearThinking20251015Edit;845 import com.anthropic.models.beta.messages.BetaThinkingTurns;846 import com.anthropic.models.beta.AnthropicBeta;847 // ...848 void main() {849 AnthropicClient client = AnthropicOkHttpClient.fromEnv();850851 MessageCreateParams params = MessageCreateParams.builder()852 .model(Model.CLAUDE_OPUS_5)853 .maxTokens(16000L)854 .addUserMessage("Hello")855 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)856 .contextManagement(BetaContextManagementConfig.builder()857 .addEdit(BetaClearThinking20251015Edit.builder()858 .keep(BetaThinkingTurns.builder()859 .value(2L)860 .build())861 .build())862 .build())863 .build();864865 BetaMessage response = client.beta().messages().create(params);866 IO.println(response);867 }868 ```869870 ```php PHP871 $client = new Client();872873 $response = $client->beta->messages->create(874 maxTokens: 16000,875 messages: [876 ['role' => 'user', 'content' => 'Hello']877 ],878 model: 'claude-opus-5',879 betas: ['context-management-2025-06-27'],880 contextManagement: [881 'edits' => [882 [883 'type' => 'clear_thinking_20251015',884 'keep' => [885 'type' => 'thinking_turns',886 'value' => 2887 ]888 ]889 ]890 ],891 );892893 echo $response;894 ```895896 ```ruby Ruby897 client = Anthropic::Client.new898899 response = client.beta.messages.create(900 model: "claude-opus-5",901 max_tokens: 16000,902 messages: [{ role: "user", content: "Hello" }],903 betas: ["context-management-2025-06-27"],904 context_management: {905 edits: [906 {907 type: "clear_thinking_20251015",908 keep: {909 type: "thinking_turns",910 value: 2911 }912 }913 ]914 }915 )916 puts response917 ```918</CodeGroup>919920### Configuration options for thinking block clearing921922The `clear_thinking_20251015` strategy supports the following configuration:923924| Configuration option | Default | Description |925| -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |926| `keep` | Model-specific | Defines how many recent assistant turns with thinking blocks to preserve. Use `{type: "thinking_turns", value: N}` where N must be > 0 to keep the last N turns, or `"all"` to keep all thinking blocks. Opus 4.5+ and Sonnet 4.6+: all turns. Fable and Mythos models: all turns. Earlier Opus/Sonnet and all Haiku: last turn only. |927928**Example configurations:**929930Keep thinking blocks from the last 3 assistant turns:931932<CodeGroup>933 ```bash cURL934 curl https://api.anthropic.com/v1/messages \935 --header "x-api-key: $ANTHROPIC_API_KEY" \936 --header "anthropic-version: 2023-06-01" \937 --header "content-type: application/json" \938 --header "anthropic-beta: context-management-2025-06-27" \939 --data '{940 "model": "claude-opus-5",941 "max_tokens": 16000,942 "messages": [{"role": "user", "content": "Hello"}],943 "context_management": {944 "edits": [945 {946 "type": "clear_thinking_20251015",947 "keep": {948 "type": "thinking_turns",949 "value": 3950 }951 }952 ]953 }954 }'955 ```956957 ```bash CLI958 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'959 model: claude-opus-5960 max_tokens: 16000961 messages:962 - role: user963 content: Hello964 context_management:965 edits:966 - type: clear_thinking_20251015967 keep:968 type: thinking_turns969 value: 3970 YAML971 ```972973 ```python Python974 response = client.beta.messages.create(975 model="claude-opus-5",976 max_tokens=16000,977 messages=[{"role": "user", "content": "Hello"}],978 betas=["context-management-2025-06-27"],979 context_management={980 "edits": [981 {982 "type": "clear_thinking_20251015",983 "keep": {"type": "thinking_turns", "value": 3},984 }985 ]986 },987 )988 ```989990 ```typescript TypeScript991 const anthropic = new Anthropic({992 apiKey: process.env.ANTHROPIC_API_KEY993 });994995 const response = await anthropic.beta.messages.create({996 model: "claude-opus-5",997 max_tokens: 16000,998 messages: [{ role: "user", content: "Hello" }],999 betas: ["context-management-2025-06-27"],1000 context_management: {1001 edits: [1002 {1003 type: "clear_thinking_20251015",1004 keep: {1005 type: "thinking_turns",1006 value: 31007 }1008 }1009 ]1010 }1011 });1012 ```10131014 ```csharp C#1015 using Anthropic;1016 using Anthropic.Models.Beta;1017 using Anthropic.Models.Beta.Messages;1018 using Messages = Anthropic.Models.Messages;10191020 AnthropicClient client = new();10211022 var parameters = new MessageCreateParams1023 {1024 Model = Messages::Model.ClaudeOpus5,1025 MaxTokens = 16000,1026 Messages = [1027 new() { Role = Role.User, Content = "Hello" }1028 ],1029 Betas = [AnthropicBeta.ContextManagement2025_06_27],1030 ContextManagement = new BetaContextManagementConfig1031 {1032 Edits = [1033 new BetaClearThinking20251015Edit1034 {1035 Keep = new BetaThinkingTurns(3)1036 }1037 ]1038 }1039 };10401041 var response = await client.Beta.Messages.Create(parameters);1042 Console.WriteLine(response);1043 ```10441045 ```go Go1046 client := anthropic.NewClient()10471048 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1049 Model: anthropic.ModelClaudeOpus5,1050 MaxTokens: 16000,1051 Messages: []anthropic.BetaMessageParam{1052 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),1053 },1054 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},1055 ContextManagement: anthropic.BetaContextManagementConfigParam{1056 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1057 {OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{1058 Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{1059 OfThinkingTurns: &anthropic.BetaThinkingTurnsParam{1060 Value: 3,1061 },1062 },1063 }},1064 },1065 },1066 })1067 if err != nil {1068 log.Fatal(err)1069 }1070 fmt.Println(response)1071 ```10721073 ```java Java1074 AnthropicClient client = AnthropicOkHttpClient.fromEnv();10751076 MessageCreateParams params = MessageCreateParams.builder()1077 .model(Model.CLAUDE_OPUS_5)1078 .maxTokens(16000L)1079 .addUserMessage("Hello")1080 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)1081 .contextManagement(BetaContextManagementConfig.builder()1082 .addEdit(BetaClearThinking20251015Edit.builder()1083 .keep(BetaThinkingTurns.builder()1084 .value(3L)1085 .build())1086 .build())1087 .build())1088 .build();10891090 BetaMessage response = client.beta().messages().create(params);1091 IO.println(response);1092 ```10931094 ```php PHP1095 $client = new Client();10961097 $response = $client->beta->messages->create(1098 maxTokens: 16000,1099 messages: [1100 ['role' => 'user', 'content' => 'Hello']1101 ],1102 model: 'claude-opus-5',1103 betas: ['context-management-2025-06-27'],1104 contextManagement: [1105 'edits' => [1106 [1107 'type' => 'clear_thinking_20251015',1108 'keep' => [1109 'type' => 'thinking_turns',1110 'value' => 31111 ]1112 ]1113 ]1114 ],1115 );11161117 echo $response;1118 ```11191120 ```ruby Ruby1121 client = Anthropic::Client.new11221123 response = client.beta.messages.create(1124 model: "claude-opus-5",1125 max_tokens: 16000,1126 messages: [{ role: "user", content: "Hello" }],1127 betas: ["context-management-2025-06-27"],1128 context_management: {1129 edits: [1130 {1131 type: "clear_thinking_20251015",1132 keep: {1133 type: "thinking_turns",1134 value: 31135 }1136 }1137 ]1138 }1139 )1140 puts response1141 ```1142</CodeGroup>11431144Keep all thinking blocks (maximizes cache hits):11451146<CodeGroup>1147 ```bash cURL1148 curl https://api.anthropic.com/v1/messages \1149 --header "x-api-key: $ANTHROPIC_API_KEY" \1150 --header "anthropic-version: 2023-06-01" \1151 --header "content-type: application/json" \1152 --header "anthropic-beta: context-management-2025-06-27" \1153 --data '{1154 "model": "claude-opus-5",1155 "max_tokens": 16000,1156 "messages": [{"role": "user", "content": "Hello"}],1157 "context_management": {1158 "edits": [1159 {1160 "type": "clear_thinking_20251015",1161 "keep": "all"1162 }1163 ]1164 }1165 }'1166 ```11671168 ```bash CLI1169 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'1170 model: claude-opus-51171 max_tokens: 160001172 messages:1173 - role: user1174 content: Hello1175 context_management:1176 edits:1177 - type: clear_thinking_202510151178 keep: all1179 YAML1180 ```11811182 ```python Python1183 response = client.beta.messages.create(1184 model="claude-opus-5",1185 max_tokens=16000,1186 messages=[{"role": "user", "content": "Hello"}],1187 betas=["context-management-2025-06-27"],1188 context_management={1189 "edits": [1190 {1191 "type": "clear_thinking_20251015",1192 "keep": "all",1193 }1194 ]1195 },1196 )1197 ```11981199 ```typescript TypeScript1200 const anthropic = new Anthropic({1201 apiKey: process.env.ANTHROPIC_API_KEY1202 });12031204 const response = await anthropic.beta.messages.create({1205 model: "claude-opus-5",1206 max_tokens: 16000,1207 messages: [{ role: "user", content: "Hello" }],1208 betas: ["context-management-2025-06-27"],1209 context_management: {1210 edits: [1211 {1212 type: "clear_thinking_20251015",1213 keep: "all"1214 }1215 ]1216 }1217 });1218 ```12191220 ```csharp C#1221 using Anthropic;1222 using Anthropic.Models.Beta;1223 using Anthropic.Models.Beta.Messages;1224 using Messages = Anthropic.Models.Messages;12251226 AnthropicClient client = new();12271228 var parameters = new MessageCreateParams1229 {1230 Model = Messages::Model.ClaudeOpus5,1231 MaxTokens = 16000,1232 Messages = [1233 new() { Role = Role.User, Content = "Hello" }1234 ],1235 Betas = [AnthropicBeta.ContextManagement2025_06_27],1236 ContextManagement = new BetaContextManagementConfig1237 {1238 Edits = [1239 new BetaClearThinking20251015Edit1240 {1241 Keep = new All()1242 }1243 ]1244 }1245 };12461247 var response = await client.Beta.Messages.Create(parameters);1248 Console.WriteLine(response);1249 ```12501251 ```go Go1252 client := anthropic.NewClient()12531254 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1255 Model: anthropic.ModelClaudeOpus5,1256 MaxTokens: 16000,1257 Messages: []anthropic.BetaMessageParam{1258 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),1259 },1260 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},1261 ContextManagement: anthropic.BetaContextManagementConfigParam{1262 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1263 {OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{1264 Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{1265 OfAll: constant.ValueOf[constant.All](),1266 },1267 }},1268 },1269 },1270 })1271 if err != nil {1272 log.Fatal(err)1273 }1274 fmt.Println(response)1275 ```12761277 ```java Java1278 AnthropicClient client = AnthropicOkHttpClient.fromEnv();12791280 MessageCreateParams params = MessageCreateParams.builder()1281 .model(Model.CLAUDE_OPUS_5)1282 .maxTokens(16000L)1283 .addUserMessage("Hello")1284 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)1285 .contextManagement(BetaContextManagementConfig.builder()1286 .addEdit(BetaClearThinking20251015Edit.builder()1287 .keepAll()1288 .build())1289 .build())1290 .build();12911292 BetaMessage response = client.beta().messages().create(params);1293 IO.println(response);1294 ```12951296 ```php PHP1297 $client = new Client();12981299 $response = $client->beta->messages->create(1300 maxTokens: 16000,1301 messages: [1302 ['role' => 'user', 'content' => 'Hello']1303 ],1304 model: 'claude-opus-5',1305 betas: ['context-management-2025-06-27'],1306 contextManagement: [1307 'edits' => [1308 [1309 'type' => 'clear_thinking_20251015',1310 'keep' => 'all'1311 ]1312 ]1313 ],1314 );13151316 echo $response;1317 ```13181319 ```ruby Ruby1320 client = Anthropic::Client.new13211322 response = client.beta.messages.create(1323 model: "claude-opus-5",1324 max_tokens: 16000,1325 messages: [{ role: "user", content: "Hello" }],1326 betas: ["context-management-2025-06-27"],1327 context_management: {1328 edits: [1329 {1330 type: "clear_thinking_20251015",1331 keep: "all"1332 }1333 ]1334 }1335 )1336 puts response1337 ```1338</CodeGroup>13391340### Combining strategies13411342You can use both thinking block clearing and tool result clearing together:13431344<Note>1345 When using multiple strategies, the `clear_thinking_20251015` strategy must be listed first in the `edits` array.1346</Note>13471348<CodeGroup>1349 ```bash cURL1350 curl https://api.anthropic.com/v1/messages \1351 --header "x-api-key: $ANTHROPIC_API_KEY" \1352 --header "anthropic-version: 2023-06-01" \1353 --header "content-type: application/json" \1354 --header "anthropic-beta: context-management-2025-06-27" \1355 --data '{1356 "model": "claude-opus-5",1357 "max_tokens": 16000,1358 "messages": [1359 {1360 "role": "user",1361 "content": "Search for the latest developments in quantum error correction and summarize the key breakthroughs."1362 }1363 ],1364 "tools": [1365 {1366 "type": "web_search_20250305",1367 "name": "web_search",1368 "max_uses": 51369 }1370 ],1371 "context_management": {1372 "edits": [1373 {1374 "type": "clear_thinking_20251015",1375 "keep": {1376 "type": "thinking_turns",1377 "value": 21378 }1379 },1380 {1381 "type": "clear_tool_uses_20250919",1382 "trigger": {1383 "type": "input_tokens",1384 "value": 500001385 },1386 "keep": {1387 "type": "tool_uses",1388 "value": 51389 }1390 }1391 ]1392 }1393 }'1394 ```13951396 ```bash CLI1397 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'1398 model: claude-opus-51399 max_tokens: 160001400 messages:1401 - role: user1402 content: Search for the latest developments in quantum error correction and summarize the key breakthroughs.1403 tools:1404 - type: web_search_202503051405 name: web_search1406 max_uses: 51407 context_management:1408 edits:1409 - type: clear_thinking_202510151410 keep:1411 type: thinking_turns1412 value: 21413 - type: clear_tool_uses_202509191414 trigger:1415 type: input_tokens1416 value: 500001417 keep:1418 type: tool_uses1419 value: 51420 YAML1421 ```14221423 ```python Python1424 response = client.beta.messages.create(1425 model="claude-opus-5",1426 max_tokens=16000,1427 messages=[1428 {1429 "role": "user",1430 "content": "Search for the latest developments in quantum error correction and summarize the key breakthroughs.",1431 }1432 ],1433 tools=[1434 {1435 "type": "web_search_20250305",1436 "name": "web_search",1437 "max_uses": 5,1438 }1439 ],1440 betas=["context-management-2025-06-27"],1441 context_management={1442 "edits": [1443 {1444 "type": "clear_thinking_20251015",1445 "keep": {"type": "thinking_turns", "value": 2},1446 },1447 {1448 "type": "clear_tool_uses_20250919",1449 "trigger": {"type": "input_tokens", "value": 50000},1450 "keep": {"type": "tool_uses", "value": 5},1451 },1452 ]1453 },1454 )14551456 print(response)1457 ```14581459 ```typescript TypeScript1460 const anthropic = new Anthropic({1461 apiKey: process.env.ANTHROPIC_API_KEY1462 });14631464 const response = await anthropic.beta.messages.create({1465 model: "claude-opus-5",1466 max_tokens: 16000,1467 messages: [1468 {1469 role: "user",1470 content:1471 "Search for the latest developments in quantum error correction and summarize the key breakthroughs."1472 }1473 ],1474 tools: [1475 {1476 type: "web_search_20250305",1477 name: "web_search",1478 max_uses: 51479 }1480 ],1481 betas: ["context-management-2025-06-27"],1482 context_management: {1483 edits: [1484 {1485 type: "clear_thinking_20251015",1486 keep: {1487 type: "thinking_turns",1488 value: 21489 }1490 },1491 {1492 type: "clear_tool_uses_20250919",1493 trigger: {1494 type: "input_tokens",1495 value: 500001496 },1497 keep: {1498 type: "tool_uses",1499 value: 51500 }1501 }1502 ]1503 }1504 });15051506 console.log(response);1507 ```15081509 ```csharp C#1510 using Anthropic;1511 using Anthropic.Models.Beta;1512 using Anthropic.Models.Beta.Messages;1513 using Messages = Anthropic.Models.Messages;15141515 AnthropicClient client = new();15161517 var parameters = new MessageCreateParams1518 {1519 Model = Messages::Model.ClaudeOpus5,1520 MaxTokens = 16000,1521 Messages = [1522 new() { Role = Role.User, Content = "Search for the latest developments in quantum error correction and summarize the key breakthroughs." }1523 ],1524 Tools = [1525 new BetaWebSearchTool20250305 { MaxUses = 5 }1526 ],1527 Betas = [AnthropicBeta.ContextManagement2025_06_27],1528 ContextManagement = new BetaContextManagementConfig1529 {1530 Edits = [1531 new BetaClearThinking20251015Edit1532 {1533 Keep = new BetaThinkingTurns(2)1534 },1535 new BetaClearToolUses20250919Edit1536 {1537 Trigger = new BetaInputTokensTrigger(50000),1538 Keep = new BetaToolUsesKeep(5)1539 }1540 ]1541 }1542 };15431544 var response = await client.Beta.Messages.Create(parameters);1545 Console.WriteLine(response);1546 ```15471548 ```go Go1549 client := anthropic.NewClient()15501551 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{1552 Model: anthropic.ModelClaudeOpus5,1553 MaxTokens: 16000,1554 Messages: []anthropic.BetaMessageParam{1555 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Search for the latest developments in quantum error correction and summarize the key breakthroughs.")),1556 },1557 Tools: []anthropic.BetaToolUnionParam{1558 {OfWebSearchTool20250305: &anthropic.BetaWebSearchTool20250305Param{1559 MaxUses: anthropic.Int(5),1560 }},1561 },1562 Betas: []anthropic.AnthropicBeta{1563 anthropic.AnthropicBetaContextManagement2025_06_27,1564 },1565 ContextManagement: anthropic.BetaContextManagementConfigParam{1566 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1567 {OfClearThinking20251015: &anthropic.BetaClearThinking20251015EditParam{1568 Keep: anthropic.BetaClearThinking20251015EditKeepUnionParam{1569 OfThinkingTurns: &anthropic.BetaThinkingTurnsParam{1570 Value: 2,1571 },1572 },1573 }},1574 {OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{1575 Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{1576 OfInputTokens: &anthropic.BetaInputTokensTriggerParam{1577 Value: 50000,1578 },1579 },1580 Keep: anthropic.BetaToolUsesKeepParam{1581 Value: 5,1582 },1583 }},1584 },1585 },1586 })1587 if err != nil {1588 log.Fatal(err)1589 }1590 fmt.Println(response)1591 ```15921593 ```java Java1594 import com.anthropic.models.beta.messages.BetaWebSearchTool20250305;1595 import com.anthropic.models.beta.messages.BetaContextManagementConfig;1596 import com.anthropic.models.beta.messages.BetaClearThinking20251015Edit;1597 import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;1598 import com.anthropic.models.beta.messages.BetaThinkingTurns;1599 import com.anthropic.models.beta.messages.BetaInputTokensTrigger;1600 import com.anthropic.models.beta.messages.BetaToolUsesKeep;1601 import com.anthropic.models.beta.AnthropicBeta;1602 // ...1603 void main() {1604 AnthropicClient client = AnthropicOkHttpClient.fromEnv();16051606 MessageCreateParams params = MessageCreateParams.builder()1607 .model(Model.CLAUDE_OPUS_5)1608 .maxTokens(16000L)1609 .addUserMessage("Search for the latest developments in quantum error correction and summarize the key breakthroughs.")1610 .addTool(BetaWebSearchTool20250305.builder()1611 .maxUses(5L)1612 .build())1613 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)1614 .contextManagement(BetaContextManagementConfig.builder()1615 .addEdit(BetaClearThinking20251015Edit.builder()1616 .keep(BetaThinkingTurns.builder()1617 .value(2L)1618 .build())1619 .build())1620 .addEdit(BetaClearToolUses20250919Edit.builder()1621 .trigger(BetaInputTokensTrigger.builder()1622 .value(50000L)1623 .build())1624 .keep(BetaToolUsesKeep.builder()1625 .value(5L)1626 .build())1627 .build())1628 .build())1629 .build();16301631 BetaMessage response = client.beta().messages().create(params);1632 IO.println(response);1633 }1634 ```16351636 ```php PHP1637 $client = new Client();16381639 $response = $client->beta->messages->create(1640 maxTokens: 16000,1641 messages: [1642 [1643 'role' => 'user',1644 'content' => 'Search for the latest developments in quantum error correction and summarize the key breakthroughs.'1645 ]1646 ],1647 model: 'claude-opus-5',1648 betas: ['context-management-2025-06-27'],1649 tools: [1650 [1651 'type' => 'web_search_20250305',1652 'name' => 'web_search',1653 'max_uses' => 51654 ]1655 ],1656 contextManagement: [1657 'edits' => [1658 [1659 'type' => 'clear_thinking_20251015',1660 'keep' => [1661 'type' => 'thinking_turns',1662 'value' => 21663 ]1664 ],1665 [1666 'type' => 'clear_tool_uses_20250919',1667 'trigger' => [1668 'type' => 'input_tokens',1669 'value' => 500001670 ],1671 'keep' => [1672 'type' => 'tool_uses',1673 'value' => 51674 ]1675 ]1676 ]1677 ],1678 );16791680 echo $response;1681 ```16821683 ```ruby Ruby1684 client = Anthropic::Client.new16851686 response = client.beta.messages.create(1687 model: "claude-opus-5",1688 max_tokens: 16000,1689 messages: [1690 {1691 role: "user",1692 content: "Search for the latest developments in quantum error correction and summarize the key breakthroughs."1693 }1694 ],1695 tools: [1696 {1697 type: "web_search_20250305",1698 name: "web_search",1699 max_uses: 51700 }1701 ],1702 betas: ["context-management-2025-06-27"],1703 context_management: {1704 edits: [1705 {1706 type: "clear_thinking_20251015",1707 keep: {1708 type: "thinking_turns",1709 value: 21710 }1711 },1712 {1713 type: "clear_tool_uses_20250919",1714 trigger: {1715 type: "input_tokens",1716 value: 500001717 },1718 keep: {1719 type: "tool_uses",1720 value: 51721 }1722 }1723 ]1724 }1725 )1726 puts response1727 ```1728</CodeGroup>17291730## Configuration options for tool result clearing17311732| Configuration option | Default | Description |1733| -------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1734| `trigger` | 100,000 input tokens | Defines when the context editing strategy activates. Once the prompt exceeds this threshold, clearing begins. You can specify this value in either `input_tokens` or `tool_uses`. |1735| `keep` | 3 tool uses | Defines how many recent tool use/result pairs to keep after clearing occurs. The API removes the oldest tool interactions first, preserving the most recent ones. |1736| `clear_at_least` | None | Ensures a minimum number of tokens is cleared each time the strategy activates. If the API can't clear at least the specified amount, the strategy will not be applied. This helps determine if context clearing is worth breaking your prompt cache. |1737| `exclude_tools` | None | List of tool names whose tool uses and results should never be cleared. Useful for preserving important context. |1738| `clear_tool_inputs` | `false` | Controls whether the tool call parameters are cleared along with the tool results. By default, only the tool results are cleared while keeping Claude's original tool calls visible. |17391740## Context editing response17411742You can see which context edits were applied to your request using the `context_management` response field, along with helpful statistics about the content and input tokens cleared.17431744```json Output1745{1746 "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",1747 "type": "message",1748 "role": "assistant",1749 "content": [1750 // ...1751 ],1752 "usage": {1753 // ...1754 },1755 "context_management": {1756 "applied_edits": [1757 // When using `clear_thinking_20251015`1758 {1759 "type": "clear_thinking_20251015",1760 "cleared_thinking_turns": 3,1761 "cleared_input_tokens": 150001762 },1763 // When using `clear_tool_uses_20250919`1764 {1765 "type": "clear_tool_uses_20250919",1766 "cleared_tool_uses": 8,1767 "cleared_input_tokens": 500001768 }1769 ]1770 }1771}1772```17731774For streaming responses, the context edits are included in the final `message_delta` event:17751776```json Streaming Response1777{1778 "type": "message_delta",1779 "delta": {1780 "stop_reason": "end_turn",1781 "stop_sequence": null1782 },1783 "usage": {1784 "output_tokens": 10241785 },1786 "context_management": {1787 "applied_edits": [1788 // ...1789 ]1790 }1791}1792```17931794## Token counting17951796The [token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) endpoint supports context management, allowing you to preview how many tokens your prompt will use after context editing is applied.17971798<CodeGroup>1799 ```bash cURL1800 curl https://api.anthropic.com/v1/messages/count_tokens \1801 --header "x-api-key: $ANTHROPIC_API_KEY" \1802 --header "anthropic-version: 2023-06-01" \1803 --header "content-type: application/json" \1804 --header "anthropic-beta: context-management-2025-06-27" \1805 --data '{1806 "model": "claude-opus-5",1807 "messages": [1808 {1809 "role": "user",1810 "content": "Continue our conversation..."1811 }1812 ],1813 "context_management": {1814 "edits": [1815 {1816 "type": "clear_tool_uses_20250919",1817 "trigger": {1818 "type": "input_tokens",1819 "value": 300001820 },1821 "keep": {1822 "type": "tool_uses",1823 "value": 51824 }1825 }1826 ]1827 }1828 }'1829 ```18301831 ```bash CLI1832 cat > request.yaml <<'YAML'1833 model: claude-opus-51834 messages:1835 - role: user1836 content: Continue our conversation...1837 context_management:1838 edits:1839 - type: clear_tool_uses_202509191840 trigger:1841 type: input_tokens1842 value: 300001843 keep:1844 type: tool_uses1845 value: 51846 YAML18471848 ORIGINAL=$(ant beta:messages count-tokens \1849 --beta context-management-2025-06-27 \1850 --transform context_management.original_input_tokens \1851 --raw-output < request.yaml)18521853 INPUT_TOKENS=$(ant beta:messages count-tokens \1854 --beta context-management-2025-06-27 \1855 --transform input_tokens --raw-output < request.yaml)18561857 printf 'Original tokens: %s\n' "$ORIGINAL"1858 printf 'After clearing: %s\n' "$INPUT_TOKENS"1859 printf 'Savings: %s tokens\n' "$((ORIGINAL - INPUT_TOKENS))"1860 ```18611862 ```python Python1863 response = client.beta.messages.count_tokens(1864 model="claude-opus-5",1865 messages=[{"role": "user", "content": "Continue our conversation..."}],1866 betas=["context-management-2025-06-27"],1867 context_management={1868 "edits": [1869 {1870 "type": "clear_tool_uses_20250919",1871 "trigger": {"type": "input_tokens", "value": 30000},1872 "keep": {"type": "tool_uses", "value": 5},1873 }1874 ]1875 },1876 )18771878 print(f"Original tokens: {response.context_management.original_input_tokens}")1879 print(f"After clearing: {response.input_tokens}")1880 print(1881 f"Savings: {response.context_management.original_input_tokens - response.input_tokens} tokens"1882 )1883 ```18841885 ```typescript TypeScript1886 const anthropic = new Anthropic({1887 apiKey: process.env.ANTHROPIC_API_KEY1888 });18891890 const response = await anthropic.beta.messages.countTokens({1891 model: "claude-opus-5",1892 messages: [1893 {1894 role: "user",1895 content: "Continue our conversation..."1896 }1897 ],1898 betas: ["context-management-2025-06-27"],1899 context_management: {1900 edits: [1901 {1902 type: "clear_tool_uses_20250919",1903 trigger: {1904 type: "input_tokens",1905 value: 300001906 },1907 keep: {1908 type: "tool_uses",1909 value: 51910 }1911 }1912 ]1913 }1914 });19151916 console.log(`Original tokens: ${response.context_management?.original_input_tokens}`);1917 console.log(`After clearing: ${response.input_tokens}`);1918 console.log(1919 `Savings: ${1920 (response.context_management?.original_input_tokens || 0) - response.input_tokens1921 } tokens`1922 );1923 ```19241925 ```csharp C#1926 using Anthropic;1927 using Anthropic.Models.Beta;1928 using Anthropic.Models.Beta.Messages;1929 using Messages = Anthropic.Models.Messages;19301931 AnthropicClient client = new();19321933 var parameters = new MessageCountTokensParams1934 {1935 Model = Messages::Model.ClaudeOpus5,1936 Messages = [new() { Role = Role.User, Content = "Continue our conversation..." }],1937 Betas = [AnthropicBeta.ContextManagement2025_06_27],1938 ContextManagement = new BetaContextManagementConfig1939 {1940 Edits = [1941 new BetaClearToolUses20250919Edit1942 {1943 Trigger = new BetaInputTokensTrigger(30000),1944 Keep = new BetaToolUsesKeep(5)1945 }1946 ]1947 }1948 };19491950 var response = await client.Beta.Messages.CountTokens(parameters);19511952 Console.WriteLine($"Original tokens: {response.ContextManagement?.OriginalInputTokens}");1953 Console.WriteLine($"After clearing: {response.InputTokens}");1954 Console.WriteLine($"Savings: {(response.ContextManagement?.OriginalInputTokens ?? 0) - response.InputTokens} tokens");1955 ```19561957 ```go Go1958 client := anthropic.NewClient()19591960 response, err := client.Beta.Messages.CountTokens(context.TODO(), anthropic.BetaMessageCountTokensParams{1961 Model: anthropic.ModelClaudeOpus5,1962 Messages: []anthropic.BetaMessageParam{1963 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Continue our conversation...")),1964 },1965 Betas: []anthropic.AnthropicBeta{1966 anthropic.AnthropicBetaContextManagement2025_06_27,1967 },1968 ContextManagement: anthropic.BetaContextManagementConfigParam{1969 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{1970 {OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{1971 Trigger: anthropic.BetaClearToolUses20250919EditTriggerUnionParam{1972 OfInputTokens: &anthropic.BetaInputTokensTriggerParam{1973 Value: 30000,1974 },1975 },1976 Keep: anthropic.BetaToolUsesKeepParam{1977 Value: 5,1978 },1979 }},1980 },1981 },1982 })1983 if err != nil {1984 log.Fatal(err)1985 }19861987 fmt.Printf("Original tokens: %d\n", response.ContextManagement.OriginalInputTokens)1988 fmt.Printf("After clearing: %d\n", response.InputTokens)1989 fmt.Printf("Savings: %d tokens\n", response.ContextManagement.OriginalInputTokens-response.InputTokens)1990 ```19911992 ```java Java1993 import com.anthropic.models.beta.messages.BetaMessageTokensCount;1994 import com.anthropic.models.beta.messages.MessageCountTokensParams;1995 import com.anthropic.models.beta.messages.BetaContextManagementConfig;1996 import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;1997 import com.anthropic.models.beta.messages.BetaInputTokensTrigger;1998 import com.anthropic.models.beta.messages.BetaToolUsesKeep;1999 import com.anthropic.models.beta.AnthropicBeta;2000 // ...2001 void main() {2002 AnthropicClient client = AnthropicOkHttpClient.fromEnv();20032004 MessageCountTokensParams params = MessageCountTokensParams.builder()2005 .model(Model.CLAUDE_OPUS_5)2006 .addUserMessage("Continue our conversation...")2007 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)2008 .contextManagement(BetaContextManagementConfig.builder()2009 .addEdit(BetaClearToolUses20250919Edit.builder()2010 .trigger(BetaInputTokensTrigger.builder()2011 .value(30000L)2012 .build())2013 .keep(BetaToolUsesKeep.builder()2014 .value(5L)2015 .build())2016 .build())2017 .build())2018 .build();20192020 BetaMessageTokensCount response = client.beta().messages().countTokens(params);20212022 IO.println("Original tokens: " + response.contextManagement().get().originalInputTokens());2023 IO.println("After clearing: " + response.inputTokens());2024 IO.println("Savings: " + (response.contextManagement().get().originalInputTokens() - response.inputTokens()) + " tokens");2025 }2026 ```20272028 ```php PHP2029 $client = new Client();20302031 $response = $client->beta->messages->countTokens(2032 messages: [2033 ['role' => 'user', 'content' => 'Continue our conversation...']2034 ],2035 model: 'claude-opus-5',2036 betas: ['context-management-2025-06-27'],2037 contextManagement: [2038 'edits' => [2039 [2040 'type' => 'clear_tool_uses_20250919',2041 'trigger' => [2042 'type' => 'input_tokens',2043 'value' => 300002044 ],2045 'keep' => [2046 'type' => 'tool_uses',2047 'value' => 52048 ]2049 ]2050 ]2051 ],2052 );20532054 echo "Original tokens: " . $response->contextManagement->originalInputTokens . "\n";2055 echo "After clearing: " . $response->inputTokens . "\n";2056 echo "Savings: " . ($response->contextManagement->originalInputTokens - $response->inputTokens) . " tokens\n";2057 ```20582059 ```ruby Ruby2060 client = Anthropic::Client.new20612062 response = client.beta.messages.count_tokens(2063 model: "claude-opus-5",2064 messages: [2065 { role: "user", content: "Continue our conversation..." }2066 ],2067 betas: ["context-management-2025-06-27"],2068 context_management: {2069 edits: [2070 {2071 type: "clear_tool_uses_20250919",2072 trigger: {2073 type: "input_tokens",2074 value: 300002075 },2076 keep: {2077 type: "tool_uses",2078 value: 52079 }2080 }2081 ]2082 }2083 )20842085 puts "Original tokens: #{response.context_management.original_input_tokens}"2086 puts "After clearing: #{response.input_tokens}"2087 puts "Savings: #{response.context_management.original_input_tokens - response.input_tokens} tokens"2088 ```2089</CodeGroup>20902091```json Output2092{2093 "input_tokens": 25000,2094 "context_management": {2095 "original_input_tokens": 700002096 }2097}2098```20992100The response shows both the final token count after context management is applied (`input_tokens`) and the original token count before any clearing occurred (`original_input_tokens`).21012102## Using with the memory tool21032104Context editing can be combined with the [memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool). When your conversation context approaches the configured clearing threshold, Claude receives an automatic warning to preserve important information. This enables Claude to save tool results or context to its memory files before they're cleared from the conversation history.21052106This combination allows you to:21072108* **Preserve important context:** Claude can write essential information from tool results to memory files before those results are cleared2109* **Maintain long-running workflows:** Enable agentic workflows that would otherwise exceed context limits by offloading information to persistent storage2110* **Access information on demand:** Claude can look up previously cleared information from memory files when needed, rather than keeping everything in the active context window21112112For example, in a file editing workflow where Claude performs many operations, Claude can summarize completed changes to memory files as the context grows. When tool results are cleared, Claude retains access to that information through its memory system and can continue working effectively.21132114To use both features together, enable them in your API request:21152116<CodeGroup>2117 ```bash cURL2118 curl https://api.anthropic.com/v1/messages \2119 --header "x-api-key: $ANTHROPIC_API_KEY" \2120 --header "anthropic-version: 2023-06-01" \2121 --header "content-type: application/json" \2122 --header "anthropic-beta: context-management-2025-06-27" \2123 --data '{2124 "model": "claude-opus-5",2125 "max_tokens": 4096,2126 "messages": [2127 {2128 "role": "user",2129 "content": "Hello"2130 }2131 ],2132 "tools": [2133 {2134 "type": "memory_20250818",2135 "name": "memory"2136 }2137 ],2138 "context_management": {2139 "edits": [2140 {"type": "clear_tool_uses_20250919"}2141 ]2142 }2143 }'2144 ```21452146 ```bash CLI2147 ant beta:messages create --beta context-management-2025-06-27 <<'YAML'2148 model: claude-opus-52149 max_tokens: 40962150 messages:2151 - role: user2152 content: Hello2153 tools:2154 - type: memory_202508182155 name: memory2156 context_management:2157 edits:2158 - type: clear_tool_uses_202509192159 YAML2160 ```21612162 ```python Python2163 response = client.beta.messages.create(2164 model="claude-opus-5",2165 max_tokens=4096,2166 messages=[{"role": "user", "content": "Hello"}],2167 tools=[{"type": "memory_20250818", "name": "memory"}],2168 betas=["context-management-2025-06-27"],2169 context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},2170 )2171 ```21722173 ```typescript TypeScript2174 const anthropic = new Anthropic({2175 apiKey: process.env.ANTHROPIC_API_KEY2176 });21772178 const response = await anthropic.beta.messages.create({2179 model: "claude-opus-5",2180 max_tokens: 4096,2181 messages: [{ role: "user", content: "Hello" }],2182 tools: [2183 {2184 type: "memory_20250818",2185 name: "memory"2186 }2187 ],2188 betas: ["context-management-2025-06-27"],2189 context_management: {2190 edits: [{ type: "clear_tool_uses_20250919" }]2191 }2192 });2193 ```21942195 ```csharp C#2196 using Anthropic;2197 using Anthropic.Models.Beta;2198 using Anthropic.Models.Beta.Messages;2199 using Messages = Anthropic.Models.Messages;22002201 AnthropicClient client = new();22022203 var parameters = new MessageCreateParams2204 {2205 Model = Messages::Model.ClaudeOpus5,2206 MaxTokens = 4096,2207 Messages = [2208 new() { Role = Role.User, Content = "Hello" }2209 ],2210 Tools = [2211 new BetaMemoryTool20250818()2212 ],2213 Betas = [AnthropicBeta.ContextManagement2025_06_27],2214 ContextManagement = new BetaContextManagementConfig2215 {2216 Edits = [new BetaClearToolUses20250919Edit()]2217 }2218 };22192220 var response = await client.Beta.Messages.Create(parameters);2221 Console.WriteLine(response);2222 ```22232224 ```go Go2225 client := anthropic.NewClient()22262227 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{2228 Model: anthropic.ModelClaudeOpus5,2229 MaxTokens: 4096,2230 Messages: []anthropic.BetaMessageParam{2231 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello")),2232 },2233 Tools: []anthropic.BetaToolUnionParam{2234 {OfMemoryTool20250818: &anthropic.BetaMemoryTool20250818Param{}},2235 },2236 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaContextManagement2025_06_27},2237 ContextManagement: anthropic.BetaContextManagementConfigParam{2238 Edits: []anthropic.BetaContextManagementConfigEditUnionParam{2239 {OfClearToolUses20250919: &anthropic.BetaClearToolUses20250919EditParam{}},2240 },2241 },2242 })2243 if err != nil {2244 log.Fatal(err)2245 }2246 fmt.Println(response)2247 ```22482249 ```java Java2250 import com.anthropic.models.beta.messages.BetaMemoryTool20250818;2251 import com.anthropic.models.beta.messages.BetaContextManagementConfig;2252 import com.anthropic.models.beta.messages.BetaClearToolUses20250919Edit;2253 import com.anthropic.models.beta.AnthropicBeta;2254 // ...2255 void main() {2256 AnthropicClient client = AnthropicOkHttpClient.fromEnv();22572258 MessageCreateParams params = MessageCreateParams.builder()2259 .model(Model.CLAUDE_OPUS_5)2260 .maxTokens(4096L)2261 .addUserMessage("Hello")2262 .addTool(BetaMemoryTool20250818.builder().build())2263 .addBeta(AnthropicBeta.CONTEXT_MANAGEMENT_2025_06_27)2264 .contextManagement(BetaContextManagementConfig.builder()2265 .addEdit(BetaClearToolUses20250919Edit.builder().build())2266 .build())2267 .build();22682269 BetaMessage response = client.beta().messages().create(params);2270 IO.println(response);2271 }2272 ```22732274 ```php PHP2275 $client = new Client();22762277 $response = $client->beta->messages->create(2278 maxTokens: 4096,2279 messages: [2280 ['role' => 'user', 'content' => 'Hello']2281 ],2282 model: 'claude-opus-5',2283 betas: ['context-management-2025-06-27'],2284 tools: [2285 [2286 'type' => 'memory_20250818',2287 'name' => 'memory'2288 ]2289 ],2290 contextManagement: [2291 'edits' => [2292 ['type' => 'clear_tool_uses_20250919']2293 ]2294 ],2295 );22962297 echo $response;2298 ```22992300 ```ruby Ruby2301 client = Anthropic::Client.new23022303 response = client.beta.messages.create(2304 model: "claude-opus-5",2305 max_tokens: 4096,2306 messages: [{ role: "user", content: "Hello" }],2307 tools: [2308 {2309 type: "memory_20250818",2310 name: "memory"2311 }2312 ],2313 betas: ["context-management-2025-06-27"],2314 context_management: {2315 edits: [2316 { type: "clear_tool_uses_20250919" }2317 ]2318 }2319 )2320 puts response2321 ```2322</CodeGroup>23232324For the full memory tool reference including commands and examples, see [Memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool).23252326## Client-side compaction (SDK)23272328<Warning>2329 **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.23302331 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.2332</Warning>23332334<Note>2335 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).2336</Note>23372338Compaction 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).23392340### How compaction works23412342When compaction is enabled, the SDK monitors token usage after each model response:234323441. **Threshold check:** The SDK calculates total tokens as `input_tokens + cache_creation_input_tokens + cache_read_input_tokens + output_tokens` (see [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for the cache token fields).23452. **Summary generation:** When the threshold is exceeded, a summary prompt is injected as a user turn, and Claude generates a structured summary wrapped in `<summary></summary>` tags.23463. **Context replacement:** The SDK extracts the summary and replaces the entire message history with it.23474. **Continuation:** The conversation resumes from the summary, with Claude picking up where it left off.23482349### Using compaction23502351Add `compaction_control` to your `tool_runner` call to enable automatic summarization when token usage exceeds the threshold.23522353<Tabs>2354 <Tab title="cURL">2355 <Note>2356 Compaction runs client-side in the SDK `tool_runner` helpers, so it has no direct HTTP equivalent. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers.2357 </Note>2358 </Tab>23592360 <Tab title="CLI">2361 <Note>2362 The CLI does not include a `tool_runner` helper. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers without SDK-side integration.2363 </Note>2364 </Tab>23652366 <Tab title="Python">2367 <Note>2368 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.2369 </Note>2370 </Tab>23712372 <Tab title="TypeScript">2373 ```typescript TypeScript2374 const client = new Anthropic();23752376 const runner = client.beta.messages.toolRunner({2377 model: "claude-opus-5",2378 max_tokens: 1024,2379 tools: [readFile],2380 messages: [{ role: "user", content: "What's in config.json?" }],2381 compactionControl: { enabled: true, contextTokenThreshold: 100000 }2382 });23832384 for await (const message of runner) {2385 console.log(`Tokens used: ${message.usage.input_tokens}`);2386 }2387 ```2388 </Tab>23892390 <Tab title="C#">2391 <Note>2392 The C# SDK includes a tool runner, but it 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.2393 </Note>2394 </Tab>23952396 <Tab title="Go">2397 <Note>2398 The Go SDK includes a tool runner, but it 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.2399 </Note>2400 </Tab>24012402 <Tab title="Java">2403 <Note>2404 The Java SDK includes a tool runner, but it 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.2405 </Note>2406 </Tab>24072408 <Tab title="PHP">2409 <Note>2410 The PHP SDK includes a tool runner, but it 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.2411 </Note>2412 </Tab>24132414 <Tab title="Ruby">2415 ```ruby Ruby2416 client = Anthropic::Client.new24172418 runner = client.beta.messages.tool_runner(2419 model: "claude-opus-5",2420 max_tokens: 1024,2421 tools: [ReadFile.new],2422 messages: [{ role: "user", content: "What's in config.json?" }],2423 compaction_control: { enabled: true, context_token_threshold: 100000 }2424 )24252426 runner.each_message do |message|2427 puts "Tokens used: #{message.usage.input_tokens}"2428 end2429 ```2430 </Tab>2431</Tabs>24322433#### What occurs during compaction24342435As the conversation grows, the message history accumulates:24362437**Before compaction (approaching 100k tokens):**24382439```json2440[2441 { "role": "user", "content": "Analyze all files and write a report..." },2442 { "role": "assistant", "content": "I'll help. Let me start by reading..." },2443 {2444 "role": "user",2445 "content": [{ "type": "tool_result", "tool_use_id": "...", "content": "..." }]2446 },2447 { "role": "assistant", "content": "Based on file1.txt, I see..." },2448 {2449 "role": "user",2450 "content": [{ "type": "tool_result", "tool_use_id": "...", "content": "..." }]2451 },2452 { "role": "assistant", "content": "After analyzing file2.txt..." }2453 // ... 50 more exchanges like this ...2454]2455```24562457When tokens exceed the threshold, the SDK injects a summary request and Claude generates a summary. The entire history is then replaced:24582459**After compaction (back to \~2–3k tokens):**24602461```json2462[2463 {2464 "role": "assistant",2465 "content": "# Task Overview\nThe user requested analysis of directory files to produce a summary report...\n\n# Current State\nAnalyzed 52 files across 3 subdirectories. Key findings documented in report.md...\n\n# Important Discoveries\n- Configuration files use YAML format\n- Found 3 deprecated dependencies\n- Test coverage at 67%\n\n# Next Steps\n1. Analyze remaining files in /src/legacy\n2. Complete final report sections...\n\n# Context to Preserve\nUser prefers markdown format with executive summary first..."2466 }2467]2468```24692470Claude continues working from this summary as if it were the original conversation history.24712472### Configuration options24732474| Parameter | Type | Required | Default | Description |2475| ------------------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- |2476| `enabled` | boolean | Yes | - | Whether to enable automatic compaction |2477| `context_token_threshold` | number | No | 100,000 | Token count at which compaction triggers |2478| `model` | string | No | Same as main model | Model to use for generating summaries |2479| `summary_prompt` | string | No | See [Default summary prompt](https://platform.claude.com/docs/en/build-with-claude/context-editing#default-summary-prompt) | Custom prompt for summary generation |24802481#### Choosing a token threshold24822483The threshold determines when compaction occurs. A lower threshold means more frequent compactions with smaller context windows. A higher threshold allows more context but risks hitting limits.24842485<Tabs>2486 <Tab title="cURL">2487 <Note>2488 Compaction runs client-side in the SDK `tool_runner` helpers, so it has no direct HTTP equivalent. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers.2489 </Note>2490 </Tab>24912492 <Tab title="CLI">2493 <Note>2494 The CLI does not include a `tool_runner` helper. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers without SDK-side integration.2495 </Note>2496 </Tab>24972498 <Tab title="Python">2499 <Note>2500 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.2501 </Note>2502 </Tab>25032504 <Tab title="TypeScript">2505 ```typescript TypeScript2506 const client = new Anthropic();25072508 const runner = client.beta.messages.toolRunner({2509 model: "claude-opus-5",2510 max_tokens: 1024,2511 tools: [readFile],2512 messages: [{ role: "user", content: "What's in config.json?" }],2513 // Lower values compact more often; raise to 150000 when the task needs more context2514 compactionControl: { enabled: true, contextTokenThreshold: 50000 }2515 });25162517 for await (const message of runner) {2518 console.log(`Tokens used: ${message.usage.input_tokens}`);2519 }2520 ```2521 </Tab>25222523 <Tab title="C#">2524 <Note>2525 The C# SDK includes a tool runner, but it 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.2526 </Note>2527 </Tab>25282529 <Tab title="Go">2530 <Note>2531 The Go SDK includes a tool runner, but it 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.2532 </Note>2533 </Tab>25342535 <Tab title="Java">2536 <Note>2537 The Java SDK includes a tool runner, but it 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.2538 </Note>2539 </Tab>25402541 <Tab title="PHP">2542 <Note>2543 The PHP SDK includes a tool runner, but it 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.2544 </Note>2545 </Tab>25462547 <Tab title="Ruby">2548 ```ruby Ruby2549 client = Anthropic::Client.new25502551 runner = client.beta.messages.tool_runner(2552 model: "claude-opus-5",2553 max_tokens: 1024,2554 tools: [ReadFile.new],2555 messages: [{ role: "user", content: "What's in config.json?" }],2556 # Lower values compact more often; raise to 150000 when the task needs more context2557 compaction_control: { enabled: true, context_token_threshold: 50000 }2558 )25592560 runner.each_message do |message|2561 puts "Tokens used: #{message.usage.input_tokens}"2562 end2563 ```2564 </Tab>2565</Tabs>25662567#### Using a different model for summaries25682569You can use a faster or cheaper model for generating summaries:25702571<Tabs>2572 <Tab title="cURL">2573 <Note>2574 Compaction runs client-side in the SDK `tool_runner` helpers, so it has no direct HTTP equivalent. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers.2575 </Note>2576 </Tab>25772578 <Tab title="CLI">2579 <Note>2580 The CLI does not include a `tool_runner` helper. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers without SDK-side integration.2581 </Note>2582 </Tab>25832584 <Tab title="Python">2585 <Note>2586 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.2587 </Note>2588 </Tab>25892590 <Tab title="TypeScript">2591 ```typescript TypeScript2592 const client = new Anthropic();25932594 const runner = client.beta.messages.toolRunner({2595 model: "claude-opus-5",2596 max_tokens: 1024,2597 tools: [readFile],2598 messages: [{ role: "user", content: "What's in config.json?" }],2599 compactionControl: {2600 enabled: true,2601 contextTokenThreshold: 100000,2602 model: "claude-haiku-4-5"2603 }2604 });26052606 for await (const message of runner) {2607 console.log(`Tokens used: ${message.usage.input_tokens}`);2608 }2609 ```2610 </Tab>26112612 <Tab title="C#">2613 <Note>2614 The C# SDK includes a tool runner, but it 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.2615 </Note>2616 </Tab>26172618 <Tab title="Go">2619 <Note>2620 The Go SDK includes a tool runner, but it 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.2621 </Note>2622 </Tab>26232624 <Tab title="Java">2625 <Note>2626 The Java SDK includes a tool runner, but it 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.2627 </Note>2628 </Tab>26292630 <Tab title="PHP">2631 <Note>2632 The PHP SDK includes a tool runner, but it 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.2633 </Note>2634 </Tab>26352636 <Tab title="Ruby">2637 ```ruby Ruby2638 client = Anthropic::Client.new26392640 runner = client.beta.messages.tool_runner(2641 model: "claude-opus-5",2642 max_tokens: 1024,2643 tools: [ReadFile.new],2644 messages: [{ role: "user", content: "What's in config.json?" }],2645 compaction_control: {2646 enabled: true,2647 context_token_threshold: 100000,2648 model: "claude-haiku-4-5"2649 }2650 )26512652 runner.each_message do |message|2653 puts "Tokens used: #{message.usage.input_tokens}"2654 end2655 ```2656 </Tab>2657</Tabs>26582659#### Custom summary prompts26602661You can provide a custom prompt for domain-specific needs. Your prompt should instruct Claude to wrap its summary in `<summary></summary>` tags.26622663<Tabs>2664 <Tab title="cURL">2665 <Note>2666 Compaction runs client-side in the SDK `tool_runner` helpers, so it has no direct HTTP equivalent. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers.2667 </Note>2668 </Tab>26692670 <Tab title="CLI">2671 <Note>2672 The CLI does not include a `tool_runner` helper. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers without SDK-side integration.2673 </Note>2674 </Tab>26752676 <Tab title="Python">2677 <Note>2678 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.2679 </Note>2680 </Tab>26812682 <Tab title="TypeScript">2683 ```typescript TypeScript2684 const client = new Anthropic();26852686 const runner = client.beta.messages.toolRunner({2687 model: "claude-opus-5",2688 max_tokens: 1024,2689 tools: [readFile],2690 messages: [{ role: "user", content: "What's in config.json?" }],2691 compactionControl: {2692 enabled: true,2693 contextTokenThreshold: 100000,2694 summaryPrompt: `Summarize the research conducted so far, including:2695 - Sources consulted and key findings2696 - Questions answered and remaining unknowns2697 - Recommended next steps26982699 Wrap your summary in <summary></summary> tags.`2700 }2701 });27022703 for await (const message of runner) {2704 console.log(`Tokens used: ${message.usage.input_tokens}`);2705 }2706 ```2707 </Tab>27082709 <Tab title="C#">2710 <Note>2711 The C# SDK includes a tool runner, but it 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.2712 </Note>2713 </Tab>27142715 <Tab title="Go">2716 <Note>2717 The Go SDK includes a tool runner, but it 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.2718 </Note>2719 </Tab>27202721 <Tab title="Java">2722 <Note>2723 The Java SDK includes a tool runner, but it 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.2724 </Note>2725 </Tab>27262727 <Tab title="PHP">2728 <Note>2729 The PHP SDK includes a tool runner, but it 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.2730 </Note>2731 </Tab>27322733 <Tab title="Ruby">2734 ```ruby Ruby2735 client = Anthropic::Client.new27362737 runner = client.beta.messages.tool_runner(2738 model: "claude-opus-5",2739 max_tokens: 1024,2740 tools: [ReadFile.new],2741 messages: [{ role: "user", content: "What's in config.json?" }],2742 compaction_control: {2743 enabled: true,2744 context_token_threshold: 100000,2745 summary_prompt: <<~PROMPT2746 Summarize the research conducted so far, including:2747 - Sources consulted and key findings2748 - Questions answered and remaining unknowns2749 - Recommended next steps27502751 Wrap your summary in <summary></summary> tags.2752 PROMPT2753 }2754 )27552756 runner.each_message do |message|2757 puts "Tokens used: #{message.usage.input_tokens}"2758 end2759 ```2760 </Tab>2761</Tabs>27622763### Default summary prompt27642765The built-in summary prompt instructs Claude to create a structured continuation summary including:276627671. **Task Overview:** The user's core request, success criteria, and constraints.27682. **Current State:** What has been completed, files modified, and artifacts produced.27693. **Important Discoveries:** Technical constraints, decisions made, errors resolved, and failed approaches.27704. **Next Steps:** Specific actions needed, blockers, and priority order.27715. **Context to Preserve:** User preferences, domain-specific details, and commitments made.27722773This structure enables Claude to resume work efficiently without losing important context or repeating mistakes.27742775<Accordion title="View full default prompt">2776 ```text wrap2777 You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:27782779 1. Task Overview2780 The user's core request and success criteria2781 Any clarifications or constraints they specified27822783 2. Current State2784 What has been completed so far2785 Files created, modified, or analyzed (with paths if relevant)2786 Key outputs or artifacts produced27872788 3. Important Discoveries2789 Technical constraints or requirements uncovered2790 Decisions made and their rationale2791 Errors encountered and how they were resolved2792 What approaches were tried that didn't work (and why)27932794 4. Next Steps2795 Specific actions needed to complete the task2796 Any blockers or open questions to resolve2797 Priority order if multiple steps remain27982799 5. Context to Preserve2800 User preferences or style requirements2801 Domain-specific details that aren't obvious2802 Any promises made to the user28032804 Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.28052806 Wrap your summary in <summary></summary> tags.2807 ```2808</Accordion>28092810### Limitations28112812#### Server-side tools28132814<Warning>2815 Compaction requires special consideration when using server-side tools such as [web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) or [web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool).2816</Warning>28172818When using server-side tools, the SDK may incorrectly calculate token usage, causing compaction to trigger at the wrong time.28192820For example, after a web search operation, the API response might show:28212822```json Output2823{2824 "usage": {2825 "input_tokens": 63000,2826 "cache_creation_input_tokens": 0,2827 "cache_read_input_tokens": 270000,2828 "output_tokens": 14002829 }2830}2831```28322833The SDK calculates total usage as 63,000 + 0 + 270,000 + 1,400 = 334,400 tokens. However, the `cache_read_input_tokens` value includes accumulated reads from multiple internal API calls made by the server-side tool, not your actual conversation context. Your real context length might only be the 63,000 `input_tokens`, but the SDK sees 334k and triggers compaction prematurely.28342835**Workarounds:**28362837* Use the [token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) endpoint to get accurate context length2838* Avoid compaction when using server-side tools extensively28392840#### Tool use edge cases28412842When the SDK triggers compaction while a tool use response is pending, it removes the tool use block from the message history before generating the summary. Claude will re-issue the tool call after resuming from the summary if still needed.28432844### Monitoring compaction28452846Understanding when compaction triggers helps you tune thresholds and verify expected behavior.28472848<Tabs>2849 <Tab title="cURL">2850 <Note>2851 Compaction runs client-side in the SDK `tool_runner` helpers, so it has no direct HTTP equivalent. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers.2852 </Note>2853 </Tab>28542855 <Tab title="CLI">2856 <Note>2857 The CLI does not include a `tool_runner` helper. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead, which handles compaction on Anthropic's servers without SDK-side integration.2858 </Note>2859 </Tab>28602861 <Tab title="Python">2862 <Note>2863 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.2864 </Note>2865 </Tab>28662867 <Tab title="TypeScript">2868 The TypeScript SDK's `toolRunner` supports compaction but does not log events. Detect compaction by watching `runner.params.messages.length` shrink between turns:28692870 ```typescript TypeScript2871 let prevMsgCount = 0;2872 for await (const message of runner) {2873 const currMsgCount = runner.params.messages.length;2874 if (currMsgCount < prevMsgCount) {2875 console.log(`Compaction occurred: ${prevMsgCount} -> ${currMsgCount} messages`);2876 console.log(`Input tokens after compaction: ${message.usage.input_tokens}`);2877 }2878 prevMsgCount = currMsgCount;2879 }2880 ```2881 </Tab>28822883 <Tab title="C#">2884 <Note>2885 The C# SDK's tool runner does not support `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead.2886 </Note>2887 </Tab>28882889 <Tab title="Go">2890 <Note>2891 The Go SDK's tool runner does not support `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead.2892 </Note>2893 </Tab>28942895 <Tab title="Java">2896 <Note>2897 The Java SDK's tool runner does not support `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead.2898 </Note>2899 </Tab>29002901 <Tab title="PHP">2902 <Note>2903 The PHP SDK's tool runner does not support `compaction_control`. Use [server-side compaction](https://platform.claude.com/docs/en/build-with-claude/compaction) instead.2904 </Note>2905 </Tab>29062907 <Tab title="Ruby">2908 The Ruby SDK supports an `on_compact:` callback that fires when compaction occurs. Add it to your `compaction_control` configuration:29092910 ```ruby Ruby2911 client = Anthropic::Client.new29122913 runner = client.beta.messages.tool_runner(2914 model: "claude-opus-5",2915 max_tokens: 1024,2916 tools: [ReadFile.new],2917 messages: [{ role: "user", content: "What's in config.json?" }],2918 compaction_control: {2919 enabled: true,2920 context_token_threshold: 100000,2921 on_compact: ->(tokens_before, tokens_after) do2922 puts "Compaction occurred: #{tokens_before} -> #{tokens_after} tokens"2923 end2924 }2925 )29262927 runner.each_message do |message|2928 puts "Tokens: #{message.usage.input_tokens}"2929 end2930 ```2931 </Tab>2932</Tabs>29332934### When to use compaction29352936**Good use cases:**29372938* Long-running agent tasks that process many files or data sources2939* Research workflows that accumulate large amounts of information2940* Multistep tasks with clear, measurable progress2941* Tasks that produce artifacts (files, reports) that persist outside the conversation29422943**Less ideal use cases:**29442945* Tasks requiring precise recall of early conversation details2946* Workflows using server-side tools extensively2947* Tasks that need to maintain exact state across many variables29482949## Next steps29502951<CardGroup cols={2}>2952 <Card title="Compaction" icon="arrows-clockwise" href="https://platform.claude.com/docs/en/build-with-claude/compaction">2953 Manage long conversations with server-side compaction, the recommended strategy for most use cases.2954 </Card>29552956 <Card title="Prompt caching" icon="database" href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">2957 Reduce cost and latency by caching prompt prefixes, and learn how context editing interacts with the cache.2958 </Card>2959</CardGroup>2960