The whole hunk
from line 1755, old and new numbered
/
lines
from line 1755
17551755 context_management={"edits": [{"type": "compact_20260112"}]},
17561756 ) as stream:
17571757 for event in stream:
1758 if event.type == "content_block_start":
1759 if event.content_block.type == "compaction":
1760 print("Compaction started...")
1761 elif event.content_block.type == "text":
1762 print("Text response started...")
1758 match event.type:
1759 case "content_block_start":
1760 block = event.content_block
1761 match block.type:
1762 case "compaction":
1763 print("Compaction started...")
1764 case "text":
1765 print("Text response started...")
17631766
1764 elif event.type == "content_block_delta":
1765 if event.delta.type == "compaction_delta":
1766 print(f"Compaction complete: {len(event.delta.content or '')} chars")
1767 elif event.delta.type == "text_delta":
1768 print(event.delta.text, end="", flush=True)
1767 case "content_block_delta":
1768 delta = event.delta
1769 match delta.type:
1770 case "compaction_delta":
1771 print(f"Compaction complete: {len(delta.content or '')} chars")
1772 case "text_delta":
1773 print(delta.text, end="", flush=True)
17691774
17701775 # Get the final accumulated message
17711776 message = stream.get_final_message()
from line 1794
17891794 });
17901795
17911796 for await (const event of stream) {
1792 if (event.type === "content_block_start") {
1793 if (event.content_block.type === "compaction") {
1794 console.log("Compaction started...");
1795 } else if (event.content_block.type === "text") {
1796 console.log("Text response started...");
1797 }
1798 } else if (event.type === "content_block_delta") {
1799 if (event.delta.type === "compaction_delta") {
1800 console.log(`Compaction complete: ${event.delta.content?.length ?? 0} chars`);
1801 } else if (event.delta.type === "text_delta") {
1802 process.stdout.write(event.delta.text);
1803 }
1797 switch (event.type) {
1798 case "content_block_start":
1799 switch (event.content_block.type) {
1800 case "compaction":
1801 console.log("Compaction started...");
1802 break;
1803 case "text":
1804 console.log("Text response started...");
1805 break;
1806 }
1807 break;
1808 case "content_block_delta":
1809 switch (event.delta.type) {
1810 case "compaction_delta":
1811 console.log(`Compaction complete: ${event.delta.content?.length ?? 0} chars`);
1812 break;
1813 case "text_delta":
1814 process.stdout.write(event.delta.text);
1815 break;
1816 }
1817 break;
18041818 }
18051819 }
18061820
from line 1949
19351949 ```
19361950
19371951 ```php PHP
1952 use Anthropic\Beta\Messages\BetaCompactionBlock;
1953 use Anthropic\Beta\Messages\BetaCompactionContentBlockDelta;
1954 use Anthropic\Beta\Messages\BetaRawContentBlockDeltaEvent;
1955 use Anthropic\Beta\Messages\BetaRawContentBlockStartEvent;
1956 use Anthropic\Beta\Messages\BetaTextBlock;
1957 use Anthropic\Beta\Messages\BetaTextDelta;
1958
19381959 $client = new Client();
19391960 $messages = [['role' => 'user', 'content' => 'Hello, Claude']];
19401961
from line 1972
19511972 );
19521973
19531974 foreach ($stream as $event) {
1954 if ($event->type === 'content_block_start') {
1955 if ($event->contentBlock->type === 'compaction') {
1956 echo "Compaction started...\n";
1957 } elseif ($event->contentBlock->type === 'text') {
1958 echo "Text response started...\n";
1959 }
1960 } elseif ($event->type === 'content_block_delta') {
1961 if ($event->delta->type === 'compaction_delta') {
1962 echo "Compaction complete: " . strlen($event->delta->content ?? '') . " chars\n";
1963 } elseif ($event->delta->type === 'text_delta') {
1964 echo $event->delta->text;
1965 }
1975 switch (true) {
1976 case $event instanceof BetaRawContentBlockStartEvent:
1977 switch (true) {
1978 case $event->contentBlock instanceof BetaCompactionBlock:
1979 echo "Compaction started...\n";
1980 break;
1981 case $event->contentBlock instanceof BetaTextBlock:
1982 echo "Text response started...\n";
1983 break;
1984 }
1985 break;
1986 case $event instanceof BetaRawContentBlockDeltaEvent:
1987 switch (true) {
1988 case $event->delta instanceof BetaCompactionContentBlockDelta:
1989 echo "Compaction complete: " . strlen($event->delta->content ?? '') . " chars\n";
1990 break;
1991 case $event->delta instanceof BetaTextDelta:
1992 echo $event->delta->text;
1993 break;
1994 }
1995 break;
19661996 }
19671997 }
19681998 ```
from line 2012
19822012 )
19832013
19842014 stream.each do |event|
1985 case event.type
1986 when :content_block_start
1987 if event.content_block.type == :compaction
2015 case event
2016 when Anthropic::Models::BetaRawContentBlockStartEvent
2017 case event.content_block
2018 when Anthropic::Models::BetaCompactionBlock
19882019 puts "Compaction started..."
1989 elsif event.content_block.type == :text
2020 when Anthropic::Models::BetaTextBlock
19902021 puts "Text response started..."
19912022 end
1992 when :content_block_delta
1993 if event.delta.type == :compaction_delta
1994 puts "Compaction complete: #{(event.delta.content || "").length} chars"
1995 elsif event.delta.type == :text_delta
1996 print event.delta.text
2023 when Anthropic::Models::BetaRawContentBlockDeltaEvent
2024 delta = event.delta
2025 case delta
2026 when Anthropic::Models::BetaCompactionContentBlockDelta
2027 puts "Compaction complete: #{(delta.content || "").length} chars"
2028 when Anthropic::Models::BetaTextDelta
2029 print delta.text
19972030 end
19982031 end
19992032 end
from line 3454
34213454
34223455### Request a summary
34233456
3424Send the conversation as it stands with `"compaction": {"type": "summarize"}`. The API summarizes every message in the request once, generates no reply after it, and returns the block alone with `stop_reason` `"compaction"`. Send the same `system` prompt and `tools` that you use for the rest of the conversation. The summarizer reads them, and on models with preserved thinking, the turns you keep stay valid only if they match:
3457Send the conversation as it stands with `"compaction": {"type": "summarize"}`. The API summarizes every message in the request once, generates no reply after it, and returns the block alone with `stop_reason` `"compaction"`. Send the same `system` prompt and `tools` that you use for the rest of the conversation. The summarizer reads them, and on models with preserved thinking, the turns you keep stay valid only if they match. The conversation in this example has no `system` prompt or tools, so the request sends neither:
34253458
3426<CodeGroup exclude="python, typescript, csharp, go, java, php, ruby">
3459<CodeGroup>
34273460 ```bash cURL
3461 # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
34283462 curl https://api.anthropic.com/v1/messages \
34293463 -H "x-api-key: $ANTHROPIC_API_KEY" \
34303464 -H "anthropic-version: 2023-06-01" \
from line 3484
34503484 <File filename="request.yaml">
34513485 ```yaml
34523486 model: claude-opus-5
3487 # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
34533488 max_tokens: 4096
34543489 messages:
34553490 - role: user
from line 3498
34633498 ```
34643499 </File>
34653500 </MultiFileExample>
3501
3502 ```python Python
3503 from anthropic.types.beta import BetaMessageParam
3504
3505 client = anthropic.Anthropic()
3506
3507 history: list[BetaMessageParam] = [
3508 {
3509 "role": "user",
3510 "content": "I am building a recipe app. Help me name the main entities in the data model.",
3511 },
3512 {
3513 "role": "assistant",
3514 "content": "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.",
3515 },
3516 {"role": "user", "content": "Good. Now suggest field names for Recipe."},
3517 ]
3518
3519 response = client.beta.messages.create(
3520 model="claude-opus-5",
3521 # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3522 max_tokens=4096,
3523 betas=["compact-2026-09-04"],
3524 messages=history,
3525 compaction={"type": "summarize"},
3526 )
3527 print(f"Stop reason: {response.stop_reason}")
3528 ```
3529
3530 ```typescript TypeScript
3531 const client = new Anthropic();
3532
3533 const history: Anthropic.Beta.Messages.BetaMessageParam[] = [
3534 {
3535 role: "user",
3536 content: "I am building a recipe app. Help me name the main entities in the data model."
3537 },
3538 {
3539 role: "assistant",
3540 content:
3541 "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe."
3542 },
3543 { role: "user", content: "Good. Now suggest field names for Recipe." }
3544 ];
3545
3546 const response = await client.beta.messages.create({
3547 model: "claude-opus-5",
3548 // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3549 max_tokens: 4096,
3550 betas: ["compact-2026-09-04"],
3551 messages: history,
3552 compaction: { type: "summarize" }
3553 });
3554 console.log(`Stop reason: ${response.stop_reason}`);
3555 ```
3556
3557 ```csharp C#
3558 using Anthropic.Models.Beta;
3559 using Anthropic.Models.Beta.Messages;
3560 using Model = Anthropic.Models.Messages.Model;
3561
3562 AnthropicClient client = new();
3563
3564 List<BetaMessageParam> history =
3565 [
3566 new()
3567 {
3568 Role = Role.User,
3569 Content = "I am building a recipe app. Help me name the main entities in the data model.",
3570 },
3571 new()
3572 {
3573 Role = Role.Assistant,
3574 Content = "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.",
3575 },
3576 new() { Role = Role.User, Content = "Good. Now suggest field names for Recipe." },
3577 ];
3578
3579 var response = await client.Beta.Messages.Create(new MessageCreateParams
3580 {
3581 Model = Model.ClaudeOpus5,
3582 // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3583 MaxTokens = 4096,
3584 Betas = [AnthropicBeta.Compact2026_09_04],
3585 Messages = history,
3586 Compaction = new BetaCompactionConfig(), // type defaults to "summarize"
3587 });
3588
3589 Console.WriteLine($"Stop reason: {response.StopReason?.Raw()}");
3590 ```
3591
3592 ```go Go
3593 client := anthropic.NewClient()
3594
3595 history := []anthropic.BetaMessageParam{
3596 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("I am building a recipe app. Help me name the main entities in the data model.")),
3597 {
3598 Role: anthropic.BetaMessageParamRoleAssistant,
3599 Content: []anthropic.BetaContentBlockParamUnion{anthropic.NewBetaTextBlock("Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.")},
3600 },
3601 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Good. Now suggest field names for Recipe.")),
3602 }
3603
3604 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{
3605 Model: anthropic.ModelClaudeOpus5,
3606 // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3607 MaxTokens: 4096,
3608 Betas: []anthropic.AnthropicBeta{anthropic.AnthropicBetaCompact2026_09_04},
3609 Messages: history,
3610 Compaction: anthropic.BetaCompactionConfigUnionParam{
3611 OfSummarize: &anthropic.BetaSummarizeCompactionParam{},
3612 },
3613 })
3614 if err != nil {
3615 log.Fatal(err)
3616 }
3617 fmt.Println("Stop reason:", response.StopReason)
3618 ```
3619
3620 ```java Java
3621 import com.anthropic.models.beta.AnthropicBeta;
3622 import com.anthropic.models.beta.messages.BetaCompactionConfig;
3623 import com.anthropic.models.beta.messages.MessageCreateParams;
3624
3625 void main() {
3626 var client = AnthropicOkHttpClient.fromEnv();
3627
3628 var params = MessageCreateParams.builder()
3629 .model(Model.CLAUDE_OPUS_5)
3630 // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3631 .maxTokens(4096)
3632 .addBeta(AnthropicBeta.COMPACT_2026_09_04)
3633 .addUserMessage("I am building a recipe app. Help me name the main entities in the data model.")
3634 .addAssistantMessage("Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.")
3635 .addUserMessage("Good. Now suggest field names for Recipe.")
3636 .compaction(BetaCompactionConfig.builder().build()) // type defaults to "summarize"
3637 .build();
3638
3639 var response = client.beta().messages().create(params);
3640 response.stopReason().ifPresent(reason -> IO.println("Stop reason: " + reason));
3641 }
3642 ```
3643
3644 ```php PHP
3645 use Anthropic\Beta\AnthropicBeta;
3646 use Anthropic\Beta\Messages\BetaCompactionConfig;
3647 use Anthropic\Beta\Messages\BetaMessageParam;
3648 use Anthropic\Beta\Messages\BetaMessageParam\Role;
3649
3650 $client = new Client();
3651
3652 $history = [
3653 BetaMessageParam::with(
3654 role: Role::USER,
3655 content: 'I am building a recipe app. Help me name the main entities in the data model.',
3656 ),
3657 BetaMessageParam::with(
3658 role: Role::ASSISTANT,
3659 content: 'Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe.',
3660 ),
3661 BetaMessageParam::with(role: Role::USER, content: 'Good. Now suggest field names for Recipe.'),
3662 ];
3663
3664 $response = $client->beta->messages->create(
3665 model: Model::CLAUDE_OPUS_5,
3666 // max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3667 maxTokens: 4096,
3668 betas: [AnthropicBeta::COMPACT_2026_09_04],
3669 messages: $history,
3670 compaction: BetaCompactionConfig::with(), // type defaults to 'summarize'
3671 );
3672
3673 echo "Stop reason: {$response->stopReason}", PHP_EOL;
3674 ```
3675
3676 ```ruby Ruby
3677 client = Anthropic::Client.new
3678
3679 history = [
3680 {
3681 role: "user",
3682 content: "I am building a recipe app. Help me name the main entities in the data model."
3683 },
3684 {
3685 role: "assistant",
3686 content: "Start with Recipe, Ingredient, and Step. Add a RecipeIngredient entry that holds the quantity and unit for each ingredient in a recipe."
3687 },
3688 { role: "user", content: "Good. Now suggest field names for Recipe." }
3689 ]
3690
3691 response = client.beta.messages.create(
3692 model: Anthropic::Model::CLAUDE_OPUS_5,
3693 # max_tokens caps the whole call, including any thinking, so allow several thousand tokens.
3694 max_tokens: 4096,
3695 betas: [Anthropic::AnthropicBeta::COMPACT_2026_09_04],
3696 messages: history,
3697 compaction: { type: "summarize" }
3698 )
3699 puts "Stop reason: #{response.stop_reason}"
3700 ```
34663701</CodeGroup>
34673702
34683703```json Response