Community程式設計與開發github.com

context-compression

此技能應於長時間運行的代理會話需要上下文壓縮、結構化摘要、壓縮、按任務優化令牌或持久性交接摘要(保留決策、檔案、風險和後續行動)時使用。

context-compression 是什麼?

此技能旨在解決 AI 代理開發中的一個關鍵問題:長時間運行會話產生的上下文過長,超出上下文視窗限制。它提供了三種生產就緒的壓縮方法:錨定迭代摘要、不透明壓縮和再生式完整摘要。該技能的核心優化目標是「每任務令牌數」而非「每請求令牌數」,因為過度壓縮遺失關鍵資訊(如文件路徑或決策理由)可能導致代理重新探索和重新讀取文件,從而消耗更多令牌。它特別強調結構化摘要方法,使用強制性章節(例如會話意圖、已修改檔案、決策)來防止資訊遺失,並透過探針式評估方法來驗證壓縮品質。該技能支援主要的開發環境和工具鏈,並為具有清晰階段邊界的長時間運行開發會話提供策略性壓縮觸發器和三階段壓縮工作流程。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/context-compression

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

上下文壓縮策略

當代理會話生成數百萬令牌的對話歷史時,壓縮變得至關重要。天真的做法是使用激進壓縮來最小化每個請求的令牌數。正確的優化目標是「每任務令牌數」:完成一個任務所消耗的總令牌數,包括當壓縮遺失關鍵資訊時重新擷取的成本。

何時啟動

在以下情況啟動此技能:

  • 代理會話超出上下文視窗限制
  • 程式碼庫超出上下文視窗(超過 500 萬令牌的系統)
  • 設計對話摘要策略
  • 除錯代理「忘記」修改了哪些檔案的情況
  • 建立壓縮品質評估框架
  • 建立持久性交接摘要,保留決策、檔案、風險和後續行動

請勿為其他技能所屬的相關工作啟動此技能:

  • 一般的令牌效率策略,例如遮罩、前綴快取或分割:請使用 context-optimization。
  • 在選擇緩解措施之前診斷長上下文為何失敗:請使用 context-degradation。
  • 將原始輸出、日誌或計劃寫入檔案而不進行摘要:請使用 filesystem-context。
  • 跨會話設計長期語義記憶:請使用 memory-systems。
  • 模型決定何時以及如何改寫自己的上下文:請使用 self-managed-context。此技能仍然負責決定替代文字必須保留哪些內容。
  • 決定特定模型或調用框架應觸發壓縮,並跨上下文預算測量該行為:請使用 compaction-control-profiling。

核心概念

上下文壓縮在節省令牌和資訊損失之間進行權衡。根據會話特性,從三種生產就緒的方法中選擇:

  1. 錨定迭代摘要:為檔案追蹤重要的長時間運行會話實施此方法。維護結構化、持久性的摘要,包含會話意圖、檔案修改、決策和下一步驟的明確章節。當壓縮觸發時,僅對新截斷的跨度進行摘要,並與現有摘要合併,而不是從頭開始重新生成。這可以防止在整體重新生成摘要時累積的偏差——每次重新生成都有遺失模型認為優先級較低但任務所需的細節的風險。結構強制了保留,因為專用章節扮演著摘要器必須填充的檢查表角色,從而捕捉到無聲的資訊遺失。

  2. 不透明壓縮:保留用於重新擷取成本低且需要最大令牌節省的短會話。它產生針對重建保真度最佳化的壓縮表示,實現了超過 99% 的壓縮比,但完全犧牲了可解釋性。這個權衡很重要:如果不執行基於探針的評估,就無法驗證保留了什麼,因此絕不在需要除錯或工件追蹤時使用它。

  3. 再生式完整摘要:在摘要可讀性至關重要且會話具有清晰階段邊界時使用。它在每次壓縮觸發時生成詳細的結構化摘要。其缺點是在重複循環中累積性細節遺失——每次完整再生都是一個全新的過程,可能會降低先前摘要中保留的細節的優先級。

詳細主題

針對每任務令牌數進行最佳化,而非每請求令牌數

測量從任務開始到完成消耗的總令牌數,而不是每個單獨請求的令牌數。當壓縮丟棄文件路徑、錯誤訊息或決策理由時,代理必須重新探索、重新讀取檔案並重新推導結論——浪費的令牌遠遠超過壓縮節省的數量。一個每請求節省 0.5% 更多令牌但導致 20% 更多重新擷取成本的策略總體上成本更高。將重新擷取頻率作為主要的品質訊號進行追蹤:如果代理反覆要求重新讀取已處理過的檔案,則壓縮過於激進。

首先解決工件追蹤問題

工件追蹤完整性通常是壓縮評估中最薄弱的維度(claim-context-compression-factory-benchmark測試)。積極主動地處理這個問題,因為一般的摘要無法可靠地維護它。

在每個壓縮循環中明確保留以下類別:

  • 建立了哪些檔案(完整路徑)
  • 修改了哪些檔案以及更改了什麼(包含函數名稱,而不僅僅是檔案名稱)
  • 讀取但未更改的檔案
  • 特定的識別碼:函數名稱、變數名稱、錯誤訊息、錯誤代碼

在代理腳手架中實施單獨的工件索引或明確的檔案狀態追蹤,而不是依賴摘要器來捕捉這些細節。即使是具有專用檔案章節的結構化摘要,在長時間會話中也難以保持完整性。

使用強制性章節構建摘要

建立具有明確章節的結構化摘要,以防止無聲的資訊遺失。每個章節都扮演著摘要器必須填寫的檢查表角色,使遺漏變得可見而不是無聲。

## 會話意圖
[使用者嘗試完成的目標]

## 已修改的檔案
- auth.controller.ts:修復了 JWT 令牌生成
- config/redis.ts:更新了連線池
- tests/auth.test.ts:為新配置新增了模擬設定

## 已做出的決策
- 使用 Redis 連線池而不是每請求連線
- 針對暫時性失敗採用指數退避的重試邏輯

## 當前狀態
- 14 個測試通過,2 個失敗
- 剩餘:為會話服務測試設定模擬

## 下一步驟
1. 修復剩餘的測試失敗
2. 執行完整測試套件
3. 更新文件

使章節適應代理的領域。除錯代理需要「根本原因」和「錯誤訊息」;遷移代理需要「來源架構」和「目標架構」。結構遠比特定的章節重要——任何明確的 schema 都勝過自由形式的摘要。

策略性地選擇壓縮觸發器

何時觸發壓縮與如何壓縮同樣重要。根據會話可預測性選擇觸發策略:

策略觸發點權衡
固定閾值70-80% 上下文使用率簡單但可能過早壓縮
滑動視窗保留最近 N 輪 + 摘要可預測的上下文大小
基於重要性先壓縮低相關性的章節複雜但能保留訊號
任務邊界在邏輯任務完成時壓縮摘要清晰但時機不可預測

對於編碼代理,預設使用帶有結構化摘要的滑動視窗——它在可預測性和品質之間提供了最佳平衡。當會話具有清晰的階段過渡(例如,研究然後實現然後測試)時,使用任務邊界觸發器。

使用探針而非指標評估壓縮

傳統指標如 ROUGE 或嵌入相似度無法捕捉功能性的壓縮品質。一個摘要可能詞彙重疊得分很高,但卻遺漏了代理繼續工作所需的唯一檔案路徑。

使用基於探針的評估:壓縮後,提出問題以測試關鍵資訊是否存活。如果代理正確回答,則壓縮保留了正確的資訊。如果沒有,它就會猜測或產生幻覺。

探針類型測試內容示例問題
召回事實保留"原來的錯誤訊息是什麼?"
工件檔案追蹤"我們修改了哪些檔案?"
延續任務規劃"我們接下來應該做什麼?"
決策推理鏈"我們關於 Redis 問題做了什麼決定?"

從六個維度評分壓縮

針對編碼代理,從這些維度評估壓縮品質。準確性和工件追蹤保留往往比詞彙相似度更能區分方法(claim-context-compression-factory-benchmark測試),因此壓縮需要超越一般摘要的專門處理。

  1. 準確性:技術細節是否正確——檔案路徑、函數名稱、錯誤代碼?
  2. 上下文感知:回應是否反映當前的會話狀態?
  3. 工件追蹤:代理是否知道讀取或修改了哪些檔案?
  4. 完整性:回應是否解決了問題的所有部分?
  5. 連續性:工作能否在無需重新擷取資訊的情況下繼續?
  6. 指令遵循:回應是否尊重所陳述的約束?

實用指導

對大型程式碼庫應用三階段壓縮工作流程

對於超出上下文視窗的程式碼庫或代理系統,透過三個連續階段進行壓縮。每個階段都會縮小上下文,以便下一個階段在預算內運作。

  1. 研究階段:探索架構圖、文件和關鍵介面。將探索壓縮為組件、依賴項和邊界的結構化分析。輸出:替換原始探索的單一研究文件。

  2. 規劃階段:將研究文件轉換為具有函數簽名、類型定義和資料流程的實作規範。一個 500 萬令牌的程式碼庫在此階段壓縮至約 2,000 字的規範。

  3. 實作階段:根據規範執行。上下文保持聚焦於規範加上當前活躍的工作檔案,而不是原始的程式碼庫探索。由於規範已經很緊湊,此階段很少需要進一步壓縮。

使用示例工件作為壓縮種子

當提供手動遷移示例或參考 PR 時,將其用作模板來理解目標模式,而不是從頭開始探索程式碼庫。該示例揭示了靜態分析無法發現的約束條件:哪些不變量必須保持,哪些服務會因更改而中斷,以及乾淨的實作是什麼樣子。

當代理無法區分基本複雜度(業務需求)和偶發複雜度(舊有解決方法)時,這一點最為重要。示例工件隱式編碼了這種區別,從而節省了本來會用於試錯探索的令牌。

逐步實施錨定迭代摘要

  1. 定義與代理領域(除錯、遷移、功能開發)匹配的明確摘要章節
  2. 在第一次壓縮觸發時,將截斷的歷史摘要到這些章節中
  3. 在後續壓縮時,僅對新截斷的內容進行摘要——不要重新摘要現有摘要
  4. 將新資訊合併到現有章節中,而不是重新生成它們,並按檔案路徑和決策身份進行去重
  5. 標記哪些資訊來自哪個壓縮循環——這使得在摘要偏移時能夠進行除錯

根據會話概況選擇正確的方法

在以下情況使用錨定迭代摘要:

  • 會話是長時間運行的(超過 100 條訊息)
  • 檔案追蹤很重要(編碼、除錯)
  • 需要驗證保留的資訊

在以下情況使用不透明壓縮:

  • 需要最大令牌節省
  • 會話相對較短
  • 重新擷取成本低(例如,無需檔案系統存取)

在以下情況使用再生式摘要:

  • 摘要的可解釋性對於人類審查至關重要
  • 會話具有清晰的階段邊界
  • 在每次壓縮觸發時接受完整的上下文審查

按方法校準壓縮比

方法壓縮比品質分數權衡
錨定迭代98.6%3.70最佳品質,略低的壓縮率
再生式98.7%3.44良好品質,適中的壓縮率
不透明99.3%3.35最佳壓縮率,品質損失

將這些用作特定來源的基準數字,而不是通用常數(claim-context-compression-factory-benchmark測試)。對於任何存在重新擷取成本的任務,這種權衡通常有利於結構化方法。

示例

示例 1:除錯會話壓縮

原始上下文(89,000 個令牌,178 條訊息):

  • /api/auth/login 端點上的 401 錯誤
  • 追蹤了 auth 控制器、中介軟體、會話儲存
  • 發現了過時的 Redis 連線
  • 修復了連線池,新增了重試邏輯
  • 14 個測試通過,2 個失敗

壓縮後的結構化摘要:

## 會話意圖
除錯儘管憑證有效但在 /api/auth/login 上出現 401 未授權錯誤。

## 根本原因
會話儲存中的過時 Redis 連線。JWT 正確生成,但會話無法持久化。

## 已修改的檔案
- auth.controller.ts:無變更(僅讀取)
- middleware/cors.ts:無變更(已檢查)
- config/redis.ts:修復了連線池配置
- services/session.service.ts:為暫時性失敗新增了重試邏輯
- tests/auth.test.ts:更新了模擬設定

## 測試狀態
14 個通過,2 個失敗(模擬設定問題)

## 下一步驟
1. 修復剩餘的測試失敗(模擬會話服務)
2. 執行完整測試套件
3. 部署到暫存環境

示例 2:探針回應品質

壓縮後,詢問「原來的錯誤是什麼?」:

良好回應(結構化摘要):

「原來的錯誤是來自 /api/auth/login 端點的 401 未授權回應。使用者使用有效憑證收到了此錯誤。根本原因是會話儲存中的過時 Redis 連線。」

差勁回應(激進壓縮):

「我們正在除錯一個身份驗證問題。登入失敗了。我們修復了一些配置問題。」

結構化回應保留了端點、錯誤代碼和根本原因。激進回應遺失了所有技術細節。

指導方針

  1. 針對每任務令牌數進行最佳化,而非每請求令牌數
  2. 使用帶有明確章節的結構化摘要進行檔案追蹤
  3. 在上下文使用率達到 70-80% 時觸發壓縮
  4. 實施增量合併而不是完整重新生成
  5. 使用基於探針的評估測試壓縮品質
  6. 如果檔案追蹤至關重要,則單獨追蹤工件
  7. 接受略低的壓縮比以換取更好的品質保留
  8. 監控重新擷取頻率作為壓縮品質訊號

陷阱

  1. 切勿壓縮工具

…

[已截斷以供翻譯]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

advanced-evaluation

This skill should be used for advanced LLM evaluation: LLM-as-judge systems, direct scoring, pairwise comparison, rubric calibration, evaluator bias mitigation, confidence scoring, and automated quality assessment.

bdi-mental-states

This skill should be used when modeling agent mental states with BDI concepts: beliefs, desires, intentions, RDF-to-belief transformations, rational agency traces, cognitive agents, BDI ontologies, and neuro-symbolic AI integration.

book-sft-pipeline

This skill should be used for book-to-SFT pipelines: ePub extraction, literary segmentation, author-voice dataset construction, style-transfer training, LoRA workflows, and model evaluation for voice replication.

compaction-control-profiling

This skill should be used when deciding, for a specific model and workload, whether the harness or the model should control compaction, and when qualifying or calibrating that choice with measurements: context-budget sweeps that compare harness-driven and model-driven compaction on one harness, the context-pressure regime where delegation pays, a per-model compaction behavior profile (interface uptake, compression factor per call, reopen rate of archived content, context fill at first compaction, response to pressure warnings), context anxiety and timing-instruction calibration, reversible collapse-and-archive interfaces, and re-qualification after a model or prompt change. Route the editable-file protocol, harness invariants, and edit-position cache cost of self-editing agents to self-managed-context, summary content to context-compression, harness thresholds and cache layout to context-optimization, and general evaluation design to evaluation.

comprehensive-research-agent

Ensure thorough validation, error recovery, and transparent reasoning in research tasks with multiple tool calls

context-degradation

This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.

context-fundamentals

This skill should be used to explain or reason about the foundational concepts of context engineering: what context is, the anatomy of a context window, how attention mechanics work, the U-shaped attention curve, why context quality matters more than quantity, and the mental models needed to interpret every other context-engineering decision. Use this for conceptual explanation, onboarding, and background reading. Route operational work to the specialized skills: debugging attention failures goes to context-degradation, token-efficiency work goes to context-optimization, conversation summarization goes to context-compression, and project-shape decisions go to project-development.

context-optimization

This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.

evaluation

This skill should be used when building agent evaluation systems: deterministic checks, regression suites, multi-dimensional rubrics, quality gates, production monitoring, baseline comparison, and outcome measurement for agent pipelines.

filesystem-context

This skill should be used when agent work needs file-backed context: durable scratchpads, tool-output offloading, just-in-time discovery, cross-agent handoff files, filesystem memory, or cleanup policies for context stored outside the prompt.

harness-engineering

This skill should be used when designing autonomous agent harnesses: research loops, evaluation scaffolds, locked and editable surfaces, durable logs, novelty gates, pruning, rollback, PR preparation, and human approval boundaries.

hosted-agents

This skill should be used when designing hosted or background agent infrastructure: sandboxed execution, remote coding environments, warm pools, session persistence, multiplayer collaboration, self-spawning agents, or Modal-style sandboxes.

instruction-surface-security

Hardens agent runtimes against persistent prompt injection or unauthorized changes to instructions and permissions. Use to audit what agents auto-load, design reviewed activation for project rules, skills, memory, or tool configuration, and test whether trust boundaries hold after reload, restart, or delegation.

latent-briefing

This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

long-horizon-prompting

This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

memory-systems

This skill should be used for persistent semantic memory in agent systems: cross-session knowledge retention, entity tracking, temporal validity, graph or vector retrieval, memory consolidation, and memory benchmark selection. Route file-backed scratchpads to filesystem-context, handoff summaries to context-compression, and token-efficiency tactics to context-optimization.

multi-agent-patterns

This skill should be used when designing multi-agent systems that need context isolation, supervisor or swarm coordination, explicit handoffs, parallel execution, or a decision on whether multiple agents are justified.

project-development

This skill should be used for project-level decisions about LLM-powered systems: whether an LLM is the right primitive for the task at hand, the shape of a multi-stage batch or agent pipeline, token and cost estimation, choosing between single-agent and multi-agent at the project level, structured output design for downstream parsing, and structuring agent-assisted iteration. Use this when the unit of work is a whole project or a multi-stage pipeline. Route individual tool design to tool-design and individual skill-loading or context-budget tactics to context-optimization.

self-improvement-loops

This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

self-managed-context

This skill should be used when a model gets read-write control over its own live context window instead of a harness-scheduled compaction policy: the context exposed as an editable file the model rewrites with code tools, model-driven eviction and in-place updates, the harness invariants that keep self-editing safe (pinned prefix, edit gate, edit receipts, budget readouts, rollback on overflow), the prefix-cache cost of mid-context edits, and steering or training the model's own context-editing strategy. Route note content and fixed-threshold summarization to context-compression, cache-stable layout under harness control to context-optimization, file offloading to filesystem-context, and loop governance to self-improvement-loops.

相關技能