<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>上下文工程 on On My Way</title>
    <link>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/</link>
    <description>Recent content in 上下文工程 on On My Way</description>
    <generator>Hugo</generator>
    <language>zh-CN</language>
    <lastBuildDate>Sun, 06 Sep 2026 00:00:00 +0800</lastBuildDate>
    <atom:link href="https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Context Engineering · Overview</title>
      <link>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/context-engineering-overview/</link>
      <pubDate>Sun, 06 Sep 2026 00:00:00 +0800</pubDate>
      <guid>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/context-engineering-overview/</guid>
      <description>Context Engineering 综述：Context Window、Token 限制、Context Rot 与长上下文管理。</description>
      <content:encoded><![CDATA[<h2 id="1-context-windows-上下文窗口token-限制context-rot长上下文管理">1. Context Windows: 上下文窗口、Token 限制、Context Rot、长上下文管理</h2>
<p><a href="https://platform.claude.com/docs/en/build-with-claude/context-windows?utm_source=chatgpt.com">https://platform.claude.com/docs/en/build-with-claude/context-windows</a></p>
<p>↓</p>
<h3 id="2-context-engineering-in-agents-agent-上下文工程model-contexttool-context生命周期上下文summarizationmemory">2. Context Engineering in Agents: Agent 上下文工程、Model Context、Tool Context、生命周期上下文、Summarization、Memory</h3>
<p><a href="https://docs.langchain.com/oss/python/langchain/context-engineering?utm_source=chatgpt.com">https://docs.langchain.com/oss/python/langchain/context-engineering</a></p>
<p>↓</p>
<h3 id="3-compaction-对话历史压缩自动总结长时间-agent-的上下文压缩机制">3. Compaction: 对话历史压缩、自动总结、长时间 Agent 的上下文压缩机制</h3>
<p><a href="https://platform.claude.com/docs/en/build-with-claude/compaction?utm_source=chatgpt.com">https://platform.claude.com/docs/en/build-with-claude/compaction</a></p>
<p>↓</p>
<h3 id="4-context-editing-tool-result-清理thinking-block-清理context-compactiontoken-threshold">4. Context Editing: Tool Result 清理、Thinking Block 清理、Context Compaction、Token Threshold</h3>
<p><a href="https://platform.claude.com/docs/en/build-with-claude/context-editing?utm_source=chatgpt.com">https://platform.claude.com/docs/en/build-with-claude/context-editing</a></p>
<p>↓</p>
<h3 id="5-context-compaction-context-compaction-的工程实现token-based-compactionsliding-window-compactionoverlap">5. Context Compaction: Context Compaction 的工程实现、Token-based Compaction、Sliding-window Compaction、Overlap</h3>
<p><a href="https://adk.dev/context/compaction/?utm_source=chatgpt.com">https://adk.dev/context/compaction/</a></p>
<p>↓</p>
<h3 id="6-deep-agents--memory-short-term-memorylong-term-memory跨-session-的持久化记忆">6. Deep Agents — Memory: Short-term Memory、Long-term Memory、跨 Session 的持久化记忆</h3>
<p><a href="https://docs.langchain.com/oss/python/deepagents/memory?utm_source=chatgpt.com">https://docs.langchain.com/oss/python/deepagents/memory</a></p>
<p>↓</p>
<h3 id="7-context-engineering-in-deep-agents-context-compressionoffloadingfilesystemsubagentcontext-isolationmemory">7. Context Engineering in Deep Agents: Context Compression、Offloading、Filesystem、Subagent、Context Isolation、Memory</h3>
<p><a href="https://docs.langchain.com/oss/python/deepagents/context-engineering?utm_source=chatgpt.com">https://docs.langchain.com/oss/python/deepagents/context-engineering</a></p>
<p>↓</p>
<h3 id="8-context-management-for-deep-agents-长时间-agent-的-context-managementcompressionoffloadingsubagentsfilesystem">8. Context Management for Deep Agents: 长时间 Agent 的 Context Management、Compression、Offloading、Subagents、Filesystem</h3>
<p><a href="https://www.langchain.com/blog/context-management-for-deepagents?utm_source=chatgpt.com">https://www.langchain.com/blog/context-management-for-deepagents</a></p>
<p>↓</p>
<h3 id="9-context-engineering-concepts-context-engineeringskillsagentssubagentscontext-hubagent-配置">9. Context Engineering Concepts: Context Engineering、Skills、Agents、Subagents、Context Hub、Agent 配置</h3>
<p><a href="https://docs.langchain.com/langsmith/context-engineering-concepts?utm_source=chatgpt.com">https://docs.langchain.com/langsmith/context-engineering-concepts</a></p>
]]></content:encoded>
    </item>
    <item>
      <title>Context Management · Compaction</title>
      <link>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/claude_context_management/context-compaction/</link>
      <pubDate>Sun, 06 Sep 2026 00:00:00 +0800</pubDate>
      <guid>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/claude_context_management/context-compaction/</guid>
      <description>Claude 的 Server-side Compaction：自动压缩会话上下文以突破窗口限制。</description>
      <content:encoded><![CDATA[<h1 id="compaction">Compaction</h1>
<p>Server-side context compaction for managing long conversations that approaching context window limits</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">Server-side compaction is the recommended strategy for managing context in long-running conversations and agentic workflows. It handles context management automatically, without client-side summarization code.
</span></span></code></pre></td></tr></table>
</div>
</div><p>as a conversation grows, response quality degrades,Compaction extends the effective context length for long-running conversations and tasks
compaction replaces older content with a concise summary.</p>
<p>This is ideal for:</p>
<ul>
<li>Chat-based, multi-turn conversations where you want users to use one chat for a long period of time</li>
<li>Task-oriented prompts that require a lot of follow-up work (often tool use) that might exceed the context window</li>
</ul>
<h2 id="how-compaction-works">How compaction works</h2>
<p>four steps:</p>
<ol>
<li>Detects when input tokens reach your specified trigger threshold.</li>
<li>Generates a summary of the current conversation.</li>
<li>Creates a <code>compaction</code> block containing the summary.</li>
<li>Continues the response with the compacted context.</li>
</ol>
<h2 id="basic-usage">Basic usage</h2>
<p>Enable compaction by adding the <code>compact_20260112</code> strategy to <code>context_management.edits</code> in your Messages API request.</p>
<h2 id="parameters">Parameters</h2>
<table>
	<thead>
			<tr>
					<th style="text-align: left">Parameter</th>
					<th style="text-align: left">Type</th>
					<th style="text-align: left">Default</th>
					<th style="text-align: left">Description</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td style="text-align: left"><code>type</code></td>
					<td style="text-align: left">string</td>
					<td style="text-align: left">Required</td>
					<td style="text-align: left">Must be <code>&quot;compact_20260112&quot;</code></td>
			</tr>
			<tr>
					<td style="text-align: left"><code>trigger</code></td>
					<td style="text-align: left">object</td>
					<td style="text-align: left"><code>{&quot;type&quot;: &quot;input_tokens&quot;, &quot;value&quot;: 150000}</code></td>
					<td style="text-align: left">When to trigger compaction. <code>input_tokens</code> is the only supported trigger type. <code>value</code> must be at least 50,000 tokens.</td>
			</tr>
			<tr>
					<td style="text-align: left"><code>pause_after_compaction</code></td>
					<td style="text-align: left">boolean</td>
					<td style="text-align: left"><code>false</code></td>
					<td style="text-align: left">Whether to pause after generating the compaction summary</td>
			</tr>
			<tr>
					<td style="text-align: left"><code>instructions</code></td>
					<td style="text-align: left">string</td>
					<td style="text-align: left"><code>null</code></td>
					<td style="text-align: left">Custom summarization prompt. Completely replaces the default prompt when provided.</td>
			</tr>
	</tbody>
</table>
<p>ps:
type must be &ldquo;compact_20260112&rdquo;:
if u use Claude API, for sure; but if u def your own compaction function, it change use other value</p>
<h2 id="trigger-configuration">Trigger configuration</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">client = anthropic.Anthropic()
</span></span><span class="line"><span class="cl">messages = [{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;Hello, Claude&#34;}]
</span></span><span class="line"><span class="cl">response = client.beta.messages.create(
</span></span><span class="line"><span class="cl">    betas=[&#34;compact-2026-01-12&#34;],
</span></span><span class="line"><span class="cl">    model=&#34;claude-opus-5&#34;,
</span></span><span class="line"><span class="cl">    max_tokens=4096,
</span></span><span class="line"><span class="cl">    messages=messages,
</span></span><span class="line"><span class="cl">    context_management={
</span></span><span class="line"><span class="cl">        &#34;edits&#34;: [
</span></span><span class="line"><span class="cl">            {
</span></span><span class="line"><span class="cl">                &#34;type&#34;: &#34;compact_20260112&#34;,
</span></span><span class="line"><span class="cl">                &#34;trigger&#34;: {&#34;type&#34;: &#34;input_tokens&#34;, &#34;value&#34;: 150000},
</span></span><span class="line"><span class="cl">            }
</span></span><span class="line"><span class="cl">        ]
</span></span><span class="line"><span class="cl">    },
</span></span><span class="line"><span class="cl">)
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="custom-summarization-instructions">Custom summarization instructions</h2>
<p>/compaction <instruction></p>
<p>default instructions:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">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 &lt;summary&gt;&lt;/summary&gt; block.
</span></span></code></pre></td></tr></table>
</div>
</div><p>Custom instructions don&rsquo;t supplement the default prompt. They replace it completely</p>
<p>On Claude Fable 5.1 and Claude Mythos 5.1, a request with custom <code>instructions</code> summarizes from the visible conversation only: earlier thinking blocks are not part of the summarizer&rsquo;s input.</p>
<h2 id="pausing-after-compaction">Pausing after compaction</h2>
<p>Use <code>pause_after_compaction</code> to pause the API after generating the compaction summary. This allows you to add additional content blocks</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl"> context_management={
</span></span><span class="line"><span class="cl">        &#34;edits&#34;: [{&#34;type&#34;: &#34;compact_20260112&#34;, &#34;pause_after_compaction&#34;: True}]
</span></span><span class="line"><span class="cl">    }
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="enforce-a-total-token-budget">Enforce a total token budget</h2>
<p>When a model works on long tasks with many tool-use iterations, total token consumption can grow significantly. You can combine <code>pause_after_compaction</code> with a compaction counter to estimate cumulative usage and gracefully wrap up the task once a budget is reached.</p>
<p>This example appears in the SDK languages only: its value is the budget-tracking logic around the request. The raw request combines the <code>trigger</code> from <a href="https://platform.claude.com/docs/en/build-with-claude/compaction#trigger-configuration">Trigger configuration</a> with <code>pause_after_compaction</code> from <a href="https://platform.claude.com/docs/en/build-with-claude/compaction#pausing-after-compaction">Pausing after compaction</a>.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">client = anthropic.Anthropic()
</span></span><span class="line"><span class="cl">messages = [{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: &#34;Hello, Claude&#34;}]
</span></span><span class="line"><span class="cl">TRIGGER_THRESHOLD = 100_000
</span></span><span class="line"><span class="cl">TOTAL_TOKEN_BUDGET = 3_000_000
</span></span><span class="line"><span class="cl">n_compactions = 0
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">response = client.beta.messages.create(
</span></span><span class="line"><span class="cl">    betas=[&#34;compact-2026-01-12&#34;],
</span></span><span class="line"><span class="cl">    model=&#34;claude-opus-5&#34;,
</span></span><span class="line"><span class="cl">    max_tokens=4096,
</span></span><span class="line"><span class="cl">    messages=messages,
</span></span><span class="line"><span class="cl">    context_management={
</span></span><span class="line"><span class="cl">        &#34;edits&#34;: [
</span></span><span class="line"><span class="cl">            {
</span></span><span class="line"><span class="cl">                &#34;type&#34;: &#34;compact_20260112&#34;,
</span></span><span class="line"><span class="cl">                &#34;trigger&#34;: {&#34;type&#34;: &#34;input_tokens&#34;, &#34;value&#34;: TRIGGER_THRESHOLD},
</span></span><span class="line"><span class="cl">                &#34;pause_after_compaction&#34;: True,
</span></span><span class="line"><span class="cl">            }
</span></span><span class="line"><span class="cl">        ]
</span></span><span class="line"><span class="cl">    },
</span></span><span class="line"><span class="cl">)
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">if response.stop_reason == &#34;compaction&#34;:
</span></span><span class="line"><span class="cl">    n_compactions += 1
</span></span><span class="line"><span class="cl">    messages.append({&#34;role&#34;: &#34;assistant&#34;, &#34;content&#34;: response.content})
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    # Estimate total tokens consumed; prompt wrap-up if over budget
</span></span><span class="line"><span class="cl">    if n_compactions * TRIGGER_THRESHOLD &gt;= TOTAL_TOKEN_BUDGET:
</span></span><span class="line"><span class="cl">        messages.append(
</span></span><span class="line"><span class="cl">            {
</span></span><span class="line"><span class="cl">                &#34;role&#34;: &#34;user&#34;,
</span></span><span class="line"><span class="cl">                &#34;content&#34;: &#34;Please wrap up your current work and summarize the final state.&#34;,
</span></span><span class="line"><span class="cl">            }
</span></span><span class="line"><span class="cl">        )
</span></span></code></pre></td></tr></table>
</div>
</div><p>pause能够允许用户能够塞入自己的判断逻辑,防止超过总预算但是task未停止</p>
<h2 id="working-with-compaction-blocks">Working with compaction blocks</h2>
<p>When compaction is triggered, the API returns a <code>compaction</code> block at the start of the assistant response.
The new compaction block will replace the old one</p>
<h3 id="passing-compaction-blocks-back">Passing compaction blocks back</h3>
<p>You must pass the <code>compaction</code> block back to the API on subsequent requests to continue the conversation with the shortened prompt.</p>
<p>When the API receives a <code>compaction</code> block, <strong>all content blocks before it are ignored</strong>. You can either:</p>
<ul>
<li>Keep the original messages in your list and let the API handle removing the compacted content</li>
<li>Manually drop the compacted messages and only include the compaction block onwards</li>
</ul>
<h3 id="streaming">Streaming</h3>
<p>The compaction block streams differently from text blocks. You receive a <code>content_block_start</code> event, followed by a single <code>content_block_delta</code> with the complete summary content (no intermediate streaming), and then a <code>content_block_stop</code> event.</p>
<p>content_block_start -&gt; content_block_delta -&gt; content_block_stop</p>
<p>content_block_delta has the  complete summary content</p>
<h3 id="prompt-caching">Prompt caching</h3>
<p>Compaction works well with <a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">prompt caching</a>. You can add a <code>cache_control</code> breakpoint on compaction blocks to cache the summarized content.</p>
<h3 id="maximining-cache-hits-with-system-prompts">Maximining cache hits with system prompts</h3>
<p>系统提示词的缓存和压缩新写入的内容会分开,这样写入的就只有压缩后的内容,而系统提示词的缓存不会失效,实现的方法是在你的系统提示词的后面打一个断点</p>
<p>When compaction occurs, the summary becomes new content that needs to be written to the cache. Without additional cache breakpoints, this would also invalidate any cached system prompt, requiring it to be re-cached along with the compaction summary.</p>
<p>To maximize cache hit rates, add a <code>cache_control</code> breakpoint at the end of your system prompt. This keeps the system prompt cached separately from the conversation, so when compaction occurs:</p>
<ul>
<li>The system prompt cache remains valid and is read from cache</li>
<li>Only the compaction summary needs to be written as a new cache entry</li>
</ul>
<p>his keeps long system prompts cached across multiple compaction events throughout a conversation.</p>
<h2 id="understanding-usage">Understanding usage</h2>
<p>Compaction requires an additional sampling step, which contributes to rate limits and billing. The API returns detailed usage information in the response:</p>
<p>Output</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">{
</span></span><span class="line"><span class="cl">  &#34;usage&#34;: {
</span></span><span class="line"><span class="cl">    &#34;input_tokens&#34;: 23000,
</span></span><span class="line"><span class="cl">    &#34;output_tokens&#34;: 1000,
</span></span><span class="line"><span class="cl">    &#34;iterations&#34;: [
</span></span><span class="line"><span class="cl">      {
</span></span><span class="line"><span class="cl">        &#34;type&#34;: &#34;compaction&#34;,
</span></span><span class="line"><span class="cl">        &#34;input_tokens&#34;: 180000,
</span></span><span class="line"><span class="cl">        &#34;output_tokens&#34;: 3500
</span></span><span class="line"><span class="cl">      },
</span></span><span class="line"><span class="cl">      {
</span></span><span class="line"><span class="cl">        &#34;type&#34;: &#34;message&#34;,
</span></span><span class="line"><span class="cl">        &#34;input_tokens&#34;: 23000,
</span></span><span class="line"><span class="cl">        &#34;output_tokens&#34;: 1000
</span></span><span class="line"><span class="cl">      }
</span></span><span class="line"><span class="cl">    ]
</span></span><span class="line"><span class="cl">  }
</span></span><span class="line"><span class="cl">}
</span></span></code></pre></td></tr></table>
</div>
</div><p>The <code>iterations</code> array shows usage for each sampling iteration. When compaction occurs, you&rsquo;ll see a <code>compaction</code> iteration followed by the main <code>message</code> iteration. The top-level <code>input_tokens</code> and <code>output_tokens</code> match the <code>message</code> iteration exactly in this example because there is only one non-compaction iteration. The final iteration&rsquo;s token counts reflect the effective context size after compaction.</p>
<p>inerations数组中comapaction部分记录了压缩之前的上下文大小和压缩后的上下文大小,上面的usage和message相同是因为:
上述只有一次非compaction迭代</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">The top-level input_tokens and output_tokens do not include compaction iteration usage. They reflect the sum of all non-compaction iterations. To calculate total tokens consumed and billed for a request, sum across all entries in the usage.iterations array.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">If you previously relied on usage.input_tokens and usage.output_tokens for cost tracking or auditing, you&#39;ll need to update your tracking logic to aggregate across usage.iterations when compaction is enabled. With the compaction beta enabled, every response includes usage.iterations, even if no compaction occurred. A compaction entry appears only when a new compaction is triggered during the request. Re-applying a previous compaction block incurs no additional compaction cost, and the top-level usage fields remain accurate in that case.
</span></span></code></pre></td></tr></table>
</div>
</div><p>顶端的input_token和output_token不包含压缩迭代所产生的使用量,反应的是非压缩迭代的总和
要计算一次实际请求用量,要对usage.iteration中数组中的所有条目求和依赖usage.input_token和usage.output.token来进行成本统计的方式需要转变逻辑结构,转化为对于usage.interation中的每一项进行汇总
在启用compaction Beta之后,每个响应都会柏寒usage.interation,即使没有发生上下文压缩
但是只有出现了compaction,才会在interation中出现compaction条目
重新应用原来已经存在的compaction block不会产生额外的上下文压缩费用</p>
<h2 id="combing-with-other-features">Combing With other Features</h2>
<h3 id="server-tools">Server tools</h3>
<p>When using server tools (such as web search), the compaction trigger is checked at the start of each sampling iteration. Compaction might occur multiple times within a single request depending on your trigger threshold and the amount of output generated.
系统会在每个迭代之前检查是否需要压缩,这取决于你的设置和产出的数量</p>
<h3 id="token-counting">Token counting</h3>
<p>The token counting endpoint (<code>/v1/messages/count_tokens</code>) applies existing <code>compaction</code> blocks in your prompt but does not trigger new compactions. Use it to check your effective token count after previous compactions
使用现存的compaction块而不会激活compaction,所哟不会产生新的上下文费用</p>
<h2 id="current-limitations">Current limitations</h2>
<ul>
<li><strong>Same model for summarization:</strong> The model specified in your request is used for summarization. There is no option to use a different (for example, cheaper) model for the summary.</li>
</ul>
<p>有点变态的是,Claudecode会给每一个模型都开新的缓存</p>
<ul>
<li><strong>Compaction might fail when tools are defined:</strong> When your request includes <code>tools</code>, the model occasionally calls a tool during the internal summarization step instead of writing a summary. When this occurs, the response contains a <code>compaction</code> block with <code>content: null</code>. To prevent this, set <a href="https://platform.claude.com/docs/en/build-with-claude/compaction#custom-summarization-instructions"><code>instructions</code></a> to a prompt that explicitly tells the model not to call tools, for example:
当你的请求中包含tools是,有时候压缩会因为调用工具而失败
解决方法:在Instruction中显式地声明不调用工具</li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>Context Management · Context Windows</title>
      <link>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/claude_context_management/context-windows/</link>
      <pubDate>Sun, 06 Sep 2026 00:00:00 +0800</pubDate>
      <guid>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/claude_context_management/context-windows/</guid>
      <description>Claude 的 Context Window 机制：Token 限制、Context Rot 与长上下文管理。</description>
      <content:encoded><![CDATA[<h1 id="context-windows">Context windows</h1>
<p>Understand how the context window works, how extended thinking and tool use count toward it, and how to manage context as conversations grow.</p>
<p>the primary strategy is <strong>server-side-compaction</strong></p>
<h2 id="how-the-context-window-works">How the context window works</h2>
<h3 id="what-is-the-context-window">what is the context window:</h3>
<p>The &ldquo;context window&rdquo; refers to all the text a language model can reference when generating a response, <strong>including the response itself.</strong>
<a href="https://platform.claude.com/docs/images/context-window.svg">https://platform.claude.com/docs/images/context-window.svg</a></p>
<p>As token count grows, accuracy and recall degrade, a phenomenon known as <strong><em>context rot</em>.</strong></p>
<p>Chat interfaces manage the context window on a rolling &ldquo;first in,first out &ldquo;basis</p>
<ul>
<li>Progressive token accumulation: user message and assistant response accumulates within the context window and previous is preserved</li>
<li>Context window capacity:</li>
<li>Input-Output flow: Each turn consists of
<ul>
<li>input phase</li>
<li>output phase</li>
</ul>
</li>
</ul>
<p>Everything in the turns counts:</p>
<ul>
<li>the system prompt,every message in messages(including tool results,images, and documents) and your tool definition</li>
<li>the output LLM generates, including the extended thinking</li>
</ul>
<p>If you use <a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">prompt caching</a>, the input count is split across <code>input_tokens</code>, <code>cache_read_input_tokens</code>, and <code>cache_creation_input_tokens</code></p>
<h2 id="context-window-sizes-by-model">Context window sizes by model</h2>
<p>the max length of context window is up to the model</p>
<h2 id="the-context-window-with-thinking">The context window with thinking</h2>
<p>Thinking tokens are a subset of your <code>max_tokens</code> parameter, are billed as <strong>output tokens</strong> .
Whether thinking blocks from previous assistant turns stay in the context window depends on the model.
Most of LLMs  keep previous thinking blocks by default, and they count toward the context window like any other <strong>input tokens</strong>.</p>
<p>The following diagram shows how tokens are managed when thinking is enabled on a model that strips previous thinking blocks:
<a href="https://platform.claude.com/docs/images/context-window-thinking.svg">https://platform.claude.com/docs/images/context-window-thinking.svg</a></p>
<p><strong>Billing:</strong> Thinking tokens are billed as output tokens once, when they are generated. On models that keep previous thinking blocks, the kept blocks are then part of later requests&rsquo; input and are billed as input tokens, like the rest of the conversation history.</p>
<h2 id="the-context-with-thinking-and-tool-use">The context with thinking and tool use</h2>
<p>The following diagram illustrates how tokens are managed when you combine thinking with tool use on a model that <strong>strips</strong> previous thinking blocks:
<a href="https://platform.claude.com/docs/images/context-window-thinking-tools.svg">https://platform.claude.com/docs/images/context-window-thinking-tools.svg</a></p>
<p>A little bit different from my previous thought</p>
<ol>
<li>
<h3 id="first-turn-architecture">First turn architecture</h3>
<ul>
<li><strong>Input components:</strong> Tools configuration and user message</li>
<li><strong>Output components:</strong> Thinking + text response + tool use request</li>
<li><strong>Token calculation:</strong> All input and output components count toward the context window, and all output components are billed as output tokens.</li>
</ul>
</li>
<li>
<p>Tool result handling (turn 2)</p>
<ul>
<li><strong>Input components:</strong> Every block in the first turn and the <code>tool_result</code>. You must return the thinking block with the corresponding tool results. This is the only case where you have to return thinking blocks.</li>
<li><strong>Output components:</strong> After tool results have been passed back to Claude, Claude responds with only text (no additional thinking until the next <code>user</code> message, unless <a href="https://platform.claude.com/docs/en/build-with-claude/thinking#interleaved-thinking">interleaved thinking</a> is enabled).</li>
<li><strong>Token calculation:</strong> All input and output components count toward the context window, and all output components are billed as output tokens.</li>
</ul>
</li>
<li>
<p>New user turn (turn 3)</p>
<ul>
<li><strong>Input components:</strong> All inputs and the output from the previous turn are carried forward. The thinking block from the completed tool use cycle no longer has to stay in context: on models that strip previous thinking blocks, the API drops it automatically when you pass it back, and on models that keep previous thinking blocks, it stays unless you clear it with <a href="https://platform.claude.com/docs/en/build-with-claude/context-editing#thinking-block-clearing">thinking block clearing</a>. This is also where you add the next <code>user</code> turn.</li>
<li><strong>Output components:</strong> Because there is a new <code>user</code> turn outside the tool use cycle, Claude generates a new thinking block and continues from there.</li>
<li><strong>Token calculation:</strong> On models that strip previous thinking blocks, the previous thinking tokens no longer count toward the context window. All other previous blocks still count toward the context window, as does the thinking block in the current <code>assistant</code> turn.</li>
</ul>
</li>
</ol>
<h3 id="interleaved-thinking">Interleaved thinking:</h3>
<p>Let LLMs think between tool calls.,including after it receives tool results</p>
<h2 id="context-awareness">Context awareness</h2>
<p>these models track their remaining context window (their &ldquo;token budget&rdquo;) throughout a conversation.</p>
<h2 id="how-it-works">How it works</h2>
<p>In the system prompt of every request, the API gives Claude its total context window:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">&lt;budget:token_budget&gt;200000&lt;/budget:token_budget&gt;
</span></span></code></pre></td></tr></table>
</div>
</div><p>After each tool call, the API gives Claude an update on its remaining capacity:</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">&lt;system_warning&gt;Token usage: 35000/200000; 165000 remaining&lt;/system_warning&gt;
</span></span></code></pre></td></tr></table>
</div>
</div><p>For agents that span multiple sessions, design your state artifacts so that context recovery is fast when a new session starts. The <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool#multisession-software-development-pattern">memory tool&rsquo;s multisession pattern</a> walks through a concrete approach. See also <a href="https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents">Effective harnesses for long-running agents</a>.</p>
<h2 id="manage-context-with-compaction">Manage context with compaction</h2>
<p>If your conversations regularly approach context window limits, use <a href="https://platform.claude.com/docs/en/build-with-claude/compaction">server-side compaction</a>. Compaction automatically summarizes earlier parts of the conversation on the server, so the conversation can continue past the context window limit. It is available in beta for Claude 4.6 and later models and <a href="https://anthropic.com/glasswing">Claude Mythos Preview</a>.</p>
<ul>
<li><strong>Tool result clearing:</strong> Clear old tool results in agentic workflows</li>
<li><strong>Thinking block clearing:</strong> Manage thinking blocks when you use extended thinking</li>
</ul>
<h2 id="context-window-overflow-behavior">Context window overflow behavior</h2>
<p>If the input alone already exceeds the model&rsquo;s context window, the API returns a 400 <code>invalid_request_error</code> (&ldquo;prompt is too long&rdquo;) on every model.</p>
<p>On Claude 4.5 models and newer, if input tokens plus <code>max_tokens</code> exceeds the context window size, the API accepts the request. If generation then reaches the context window limit, it stops with <code>stop_reason: &quot;model_context_window_exceeded&quot;</code></p>
<p>On earlier models, the API returns a <a href="https://platform.claude.com/docs/en/api/errors">validation error</a> instead.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Context Management · Context Editing</title>
      <link>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/claude_context_management/context-editing/</link>
      <pubDate>Sun, 06 Sep 2026 00:00:00 +0800</pubDate>
      <guid>https://tuanzi-wow.cn/%E4%B8%8A%E4%B8%8B%E6%96%87%E5%B7%A5%E7%A8%8B/claude_context_management/context-editing/</guid>
      <description>Claude 的 Context Editing：自动清理过时的工具调用结果以管理对话上下文。</description>
      <content:encoded><![CDATA[<h1 id="context-editing">Context editing</h1>
<p>Automatically manage conversation context as it grows with context editing
注意断句</p>
<h2 id="overview">Overview</h2>
<p>The strategies on this page are useful for specific scenarios where you need more fine-grained control over what content is cleared.</p>
<p>更适用于在特定场景中,你需要清楚哪些内容进行更加细粒度的控制</p>
<p>Context editing allows you to selectively clear specific content from conversation history as it grows. Beyond optimizing costs and staying within limits, this is about actively curating what Claude sees: context is a finite resource with diminishing returns, and irrelevant content degrades model focus. Context editing gives you fine-grained runtime control over that curation. For the broader principles behind context management, see <a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents">Effective context engineering</a>.</p>
<p>上下文编辑允许你选择性地清楚会话内容</p>
<p>除了控制成本和避免超出限制以外,这也是在主动管理Claude对于上下文的可见性:上下文是一种有限的资源,且存在边界效应;无关内容会导致模型降级和降低注意力</p>
<p>主要提供了三种方法:</p>
<ul>
<li>Tool result clearing: 适用于工具调用频繁且旧的工具调用结果不再需要的场景</li>
<li>Thinking block clear:可有有选择性地保留最近地think block</li>
<li>Client-side SDK compaction:An SDK-based alternative for summary-based context management (server-side compaction is generally preferred)官方Compaction的替代</li>
</ul>
<table>
	<thead>
			<tr>
					<th>Approach</th>
					<th>Where it runs</th>
					<th>Strategies</th>
					<th>How it works</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><strong>Server-side</strong></td>
					<td>API</td>
					<td>Tool result clearing (<code>clear_tool_uses_20250919</code>) Thinking block clearing (<code>clear_thinking_20251015</code>)</td>
					<td>Applied before the prompt reaches Claude. Clears specific content from conversation history. Each strategy <strong>can be configured independently.</strong></td>
			</tr>
			<tr>
					<td><strong>Client-side</strong></td>
					<td>SDK</td>
					<td>Compaction</td>
					<td>Available in <a href="https://platform.claude.com/docs/en/cli-sdks-libraries/overview">TypeScript and Ruby SDKs</a> when using <a href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner"><code>tool_runner</code></a>. Generates a summary and replaces full conversation history. See <a href="https://platform.claude.com/docs/en/build-with-claude/context-editing#client-side-compaction-sdk">Client-side compaction</a>.</td>
			</tr>
	</tbody>
</table>
<h2 id="server-side-strategies">Server-side Strategies</h2>
<h3 id="tool-result-clearing">Tool result clearing</h3>
<p>when conversation context grows beyond your configured threshold
Best  for agentic workflows with heavy tool use and Older tool results are no longer needed once Claude has processed them.</p>
<p>通过清楚oldest tool result并且使用占位文本进行替换来告知模型结果已经被移除
默认情况下,只有results会被移除,但是你也可以在配置文件中将clear_tool_call 甚至为True,这样会同时清楚tool_calls以及调用时的tool use parameters和tool_results</p>
<h3 id="think-block-clearing">Think block clearing</h3>
<p>The <code>clear_thinking_20251015</code> strategy manages <code>thinking</code> 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.
用于启用了extend_thinking的会话中的think_blocks;
你可以选择保留更多的thinking_block也可以积极清理来节省上下文空间</p>
<p><strong>Default behavior:</strong> The default varies by model class.</p>
<table>
	<thead>
			<tr>
					<th>Model class</th>
					<th>Keep all prior thinking</th>
					<th>Keep only the last turn&rsquo;s thinking</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Opus</td>
					<td>Claude Opus 4.5 and later</td>
					<td>Claude Opus 4.1 and earlier</td>
			</tr>
			<tr>
					<td>Sonnet</td>
					<td>Claude Sonnet 4.6 and later</td>
					<td>Claude Sonnet 4.5 and earlier</td>
			</tr>
			<tr>
					<td>Haiku</td>
					<td>(none)</td>
					<td>All models through Claude Haiku 4.5</td>
			</tr>
			<tr>
					<td>Fable and Mythos</td>
					<td>All models</td>
					<td>(none)</td>
			</tr>
	</tbody>
</table>
<p>You can override the default,if your code runs across multiple models tiers,ser **keep **explicitly rather than relying on the per-model default</p>
<p>With interleaved thinking,there includes multiple thinking blocks</p>
<h3 id="context-editing-happens-server-side">Context editing happens server-side</h3>
<p>Context editing is applied server-side before the prompt reaches Claude.</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
