压缩 - Amazon Bedrock

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

压缩

提示

建议使用服务器端压缩来管理长时间运行的对话和代理工作流程中的上下文,因为它可以自动处理上下文管理,而集成工作量最少。

注意

Compaction 目前处于测试阶段。要使用此功能,请在您的 API 请求compact-2026-01-12中添加测试版标头。ConverseAPI 目前不支持压缩,但支持压缩。InvokeModel

Compaction 在接近上下文窗口限制时自动总结旧的上下文,从而延长了长时间运行的对话和任务的有效上下文长度。这非常适合:

  • 基于聊天的多回合对话,您希望用户长时间使用一次聊天

  • 以任务为导向的提示,需要大量的后续工作(通常是使用工具),可能超过 20 万的上下文窗口

以下型号支持压实:

模型 模型 ID

Claude Sonnet 4.6

anthropic.claude-sonnet-4-6

Claude Opus 4.6

anthropic.claude-opus-4-6-v1

注意

顶级input_tokensusage字段output_tokens中不包括压缩迭代的用法,它们反映了所有非压缩迭代的总和。要计算请求消耗和计费的代币总数,请计算usage.iterations数组中所有条目的总和。

如果您以前依赖usage.input_tokensusage.output_tokens进行成本跟踪或审计,则需要更新跟踪逻辑,以便在启用压缩usage.iterations时进行汇总。只有在请求期间触发新的压缩时,该iterations数组才会出现。重新应用之前的compaction区块不会产生额外的压缩成本,在这种情况下,顶级使用字段保持准确。

压实的工作原理

启用压缩功能后,当对话接近配置的令牌阈值时,Claude会自动对其进行汇总。API:

  1. 检测输入令牌何时超过您指定的触发阈值。

  2. 生成当前对话的摘要。

  3. 创建一个包含摘要的compaction块。

  4. 在紧凑的上下文中继续响应。

在后续请求中,将回复附加到您的消息中。API 会自动删除屏蔽之前的所有消息compaction块,继续摘要中的对话。

基本用法

通过context_management.edits在您的消息 API 请求中添加compact_20260112策略来启用压缩。

CLI
aws bedrock-runtime invoke-model \ --model-id "us.anthropic.claude-opus-4-6-v1" \ --body '{ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["compact-2026-01-12"], "max_tokens": 4096, "messages": [ { "role": "user", "content": "Help me build a website" } ], "context_management": { "edits": [ { "type": "compact_20260112" } ] } }' \ --cli-binary-format raw-in-base64-out \ /tmp/response.json echo "Response:" cat /tmp/response.json | jq '.content[] | {type, text: .text[0:500]}'
Python
import boto3 import json bedrock_runtime = boto3.client(service_name='bedrock-runtime') messages = [{"role": "user", "content": "Help me build a website"}] response = bedrock_runtime.invoke_model( modelId="us.anthropic.claude-opus-4-6-v1", body=json.dumps({ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["compact-2026-01-12"], "max_tokens": 4096, "messages": messages, "context_management": { "edits": [ { "type": "compact_20260112" } ] } }) ) response_body = json.loads(response["body"].read()) # Append the response (including any compaction block) to continue the conversation messages.append({"role": "assistant", "content": response_body["content"]}) for block in response_body["content"]: if block.get("type") == "compaction": print(f"[COMPACTION]: {block['content'][:200]}...") elif block.get("type") == "text": print(f"[RESPONSE]: {block['text']}")
TypeScript
import { BedrockRuntimeClient, InvokeModelCommand } from "@aws-sdk/client-bedrock-runtime"; async function main() { const client = new BedrockRuntimeClient({}); const messages: Array<{role: string, content: string | object[]}> = [ { role: "user", content: "Help me build a website" } ]; const command = new InvokeModelCommand({ modelId: "us.anthropic.claude-opus-4-6-v1", body: JSON.stringify({ anthropic_version: "bedrock-2023-05-31", anthropic_beta: ["compact-2026-01-12"], max_tokens: 4096, messages, context_management: { edits: [ { type: "compact_20260112" } ] } }) }); const response = await client.send(command); const responseBody = JSON.parse(new TextDecoder().decode(response.body)); // Append response to continue conversation messages.push({ role: "assistant", content: responseBody.content }); for (const block of responseBody.content) { if (block.type === "compaction") { console.log(`[COMPACTION]: ${block.content.substring(0, 200)}...`); } else if (block.type === "text") { console.log(`[RESPONSE]: ${block.text}`); } } } main().catch(console.error);

参数

参数 Type 默认值 说明
type 字符串 必需 必须是 "compact_20260112"
trigger object 15 万个代币 何时触发压实。必须至少有 50,000 个代币。
pause_after_compaction 布尔值 false 生成压缩摘要后是否暂停
instructions 字符串 null 自定义摘要提示。完全取代了提供的默认提示。

触发器配置

使用以下trigger参数配置何时触发压缩:

import boto3 import json bedrock_runtime = boto3.client(service_name='bedrock-runtime') response = bedrock_runtime.invoke_model( modelId="us.anthropic.claude-opus-4-6-v1", body=json.dumps({ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["compact-2026-01-12"], "max_tokens": 4096, "messages": [{"role": "user", "content": "Help me build a website"}], "context_management": { "edits": [ { "type": "compact_20260112", "trigger": { "type": "input_tokens", "value": 100000 } } ] } }) ) response_body = json.loads(response["body"].read()) print(response_body["content"][-1]["text"])

自定义摘要说明

默认情况下,compaction 使用以下摘要提示:

You have written a partial transcript for the initial task above. Please write a summary of the transcript. The purpose of this summary is to provide continuity so you can continue to make progress towards solving the task in a future context, where the raw history above may not be accessible and will be replaced with this summary. Write down anything that would be helpful, including the state, next steps, learnings etc. You must wrap your summary in a <summary></summary> block.

您可以通过instructions参数提供自定义指令来完全替换此提示。自定义说明并不能补充默认指令;它们完全取代了默认指令:

import boto3 import json bedrock_runtime = boto3.client(service_name='bedrock-runtime') response = bedrock_runtime.invoke_model( modelId="us.anthropic.claude-opus-4-6-v1", body=json.dumps({ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["compact-2026-01-12"], "max_tokens": 4096, "messages": [{"role": "user", "content": "Help me build a website"}], "context_management": { "edits": [ { "type": "compact_20260112", "instructions": "Focus on preserving code snippets, variable names, and technical decisions." } ] } }) ) response_body = json.loads(response["body"].read()) print(response_body["content"][-1]["text"])

压实后暂停

用于pause_after_compaction在生成压缩摘要后暂停 API。这允许您在 API 继续响应之前添加其他内容块(例如保留最近的消息或特定的面向指令的消息)。

启用后,API 将在生成压缩块后返回一条包含compaction停止原因的消息:

import boto3 import json bedrock_runtime = boto3.client(service_name='bedrock-runtime') messages = [{"role": "user", "content": "Help me build a website"}] response = bedrock_runtime.invoke_model( modelId="us.anthropic.claude-opus-4-6-v1", body=json.dumps({ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["compact-2026-01-12"], "max_tokens": 4096, "messages": messages, "context_management": { "edits": [ { "type": "compact_20260112", "pause_after_compaction": True } ] } }) ) response_body = json.loads(response["body"].read()) # Check if compaction triggered a pause if response_body.get("stop_reason") == "compaction": # Response contains only the compaction block messages.append({"role": "assistant", "content": response_body["content"]}) # Continue the request response = bedrock_runtime.invoke_model( modelId="us.anthropic.claude-opus-4-6-v1", body=json.dumps({ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["compact-2026-01-12"], "max_tokens": 4096, "messages": messages, "context_management": { "edits": [{"type": "compact_20260112"}] } }) ) response_body = json.loads(response["body"].read()) print(response_body["content"][-1]["text"])

使用压实块

当触发压缩时,API 会在助手响应开始时返回一个compaction区块。

长时间进行的对话可能会导致多次压缩。最后一个压缩块反映了提示的最终状态,将之前的内容替换为生成的摘要。

{ "content": [ { "type": "compaction", "content": "Summary of the conversation: The user requested help building a web scraper..." }, { "type": "text", "text": "Based on our conversation so far..." } ] }

流式传输

启用压缩功能的流式传输响应时,您将在压缩开始时收到一个content_block_start事件。压缩块的流式传输方式与文本块不同。您将收到一个content_block_start活动,然后是包含完整摘要内容content_block_delta的单曲(没有中间直播),然后是一个content_block_stop活动。

提示缓存

你可以在 compaction blocks 上添加一个cache_control断点,它会缓存完整的系统提示以及摘要内容。原始压缩内容将被忽略。请注意,当触发压缩时,可能会导致后续请求出现缓存失误。

{ "role": "assistant", "content": [ { "type": "compaction", "content": "[summary text]", "cache_control": {"type": "ephemeral"} }, { "type": "text", "text": "Based on our conversation..." } ] }

了解使用情况

压缩需要额外的采样步骤,这会导致费率限制和计费。API 在响应中返回详细的使用信息:

{ "usage": { "input_tokens": 45000, "output_tokens": 1234, "iterations": [ { "type": "compaction", "input_tokens": 180000, "output_tokens": 3500 }, { "type": "message", "input_tokens": 23000, "output_tokens": 1000 } ] } }

iterations数组显示每次采样迭代的使用情况。当压缩发生时,你会看到一个compaction迭代,然后是主message迭代。最后一次迭代的代币数量反映了压缩后的有效上下文大小。