Community程式設計與開發github.com

上下文優化

此技能應用於提升上下文效率:上下文預算管理、觀察遮罩、前綴或 KV 快取策略、分割、減少 Token 成本、檢索範圍限定,以及在不降低回答品質的情況下擴展有效上下文容量。

上下文優化 是什麼?

上下文優化技能專注於透過策略性壓縮、遮罩、快取和分割,來擴展有限上下文視窗的有效容量。它提供了一套完整的決策框架與具體技術,包括 KV 快取優化、觀察遮罩、內容壓縮和上下文分割,並明確指出何時應用何種技術以及其影響與風險。此技能支援多種 AI 代理平台,適用於任何受上下文預算或 Token 成本限制的場景。其核心原則是「品質重於數量」,所有優化都必須在測量紀律下進行,且提供了可量化的效能目標(如壓縮達到 50-70% Token 減少且品質下降低於 5%),幫助開發者平衡 Token 節省與任務品質。

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

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

在你喜歡的 AI 中提問

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

說明文件

上下文優化技術

上下文優化透過策略性壓縮、遮罩、快取和分割,擴展有限上下文視窗的有效容量。有效的優化能在不要求更大模型或更長視窗的情況下增加有用容量——但前提是必須在測量紀律下應用。以下技術按影響與風險排序。

何時啟動

在下列情況啟動此技能:

  • 上下文預算或 Token 成本限制了任務複雜度
  • 觀察遮罩可以將冗長的工具輸出替換為可檢索的參考
  • 前綴或 KV 快取命中率需要改善
  • 檢索範圍限定可以減少載入的無關上下文
  • 上下文分割可以在多個代理之間擴展有效容量
  • 需要預算觸發器來執行遮罩、壓縮或分割

不要將此技能用於其他技能負責的相關工作:

  • 解釋注意力或上下文視窗的行為原理:請使用 context-fundamentals。
  • 診斷活躍的中間遺失、中毒、分心、混淆或衝突:請使用 context-degradation。
  • 為長對話設計結構化的交接摘要:請使用 context-compression。
  • 將大型輸出、計劃或日誌儲存為檔案:請使用 filesystem-context。
  • 模型自行重寫其上下文及其重新填充成本:請使用 self-managed-context。
  • 鑑定特定模型以觸發其自身的壓縮,而非依賴框架閾值:請使用 compaction-control-profiling。

核心概念

按此優先順序應用四種主要策略:

  1. KV 快取優化 — 重新排列並穩定提示結構,使推理引擎能重複使用快取的 Key/Value 張量。當執行環境支援前綴快取時,這是最便宜的優化:品質風險低,可立即節省成本與延遲。當存在穩定的前綴時,優先應用此策略。

  2. 觀察遮罩 — 一旦工具輸出的目的已達成,就將其替換為簡潔的參考。工具輸出會佔據代理軌跡的主導地位(claim-context-optimization-tool-output-dominance),因此遮罩常能帶來最大的容量增益。原始內容在後續流程中仍可檢索。

  3. 壓縮 — 當上下文利用率超過 70% 時,對累積的上下文進行摘要,然後用該摘要重新初始化。這能提煉視窗內容,同時保留任務關鍵狀態。壓縮是有損的——應在遮罩已移除大量低價值內容後再應用。

  4. 上下文分割 — 當單一視窗無法容納完整問題時,將工作拆分給具有隔離上下文的子代理。每個子代理在一個專注於其子任務的乾淨上下文中運作。保留此策略用於估計上下文超過視窗限制 60% 的任務,因為協調開銷是真實存在的。

指導原則:上下文品質比數量更重要。每項優化都在減少雜訊的同時保留了訊號。在優化前進行測量,然後測量優化的效果。

詳細主題

壓縮策略

當上下文利用率超過 70% 時觸發壓縮:對當前上下文進行摘要,然後用該摘要重新初始化。這能以高保真度提煉視窗內容,使任務能以最小的效能衰減繼續進行。優先壓縮工具輸出(它們消耗了 80% 以上的 Token),然後是舊的對話輪次,最後是檢索到的文件。永遠不要壓縮系統提示——它錨定了模型的行為,移除它會導致不可預測的效能降低。

按訊息類型保留不同元素:

  • 工具輸出:提取關鍵發現、指標、錯誤碼和結論。刪除冗長的原始輸出、堆疊追蹤(除非正在進行除錯)和樣板標頭。
  • 對話輪次:保留決策、承諾、使用者偏好和上下文轉變。刪除填充詞、客套話以及已導致結論的探索性來回對話。
  • 檢索到的文件:保留與當前任務相關的主張、事實和資料點。刪除僅用於一次性推理的佐證和詳細說明。

目標是達到 50-70% 的 Token 減少,且品質下降低於 5%。如果壓縮超過 70% 的減少量,請審核摘要是否有關鍵資訊遺失——過度壓縮是最常見的失敗模式。

觀察遮罩

根據新近性和持續相關性來選擇性地遮罩觀察結果——而非均勻地遮罩。應用以下規則:

  • 永不遮罩:對當前任務至關重要的觀察結果、最近一輪的觀察結果、用於活躍推理鏈的觀察結果,以及正在進行除錯時的錯誤輸出。
  • 3 輪後遮罩:關鍵點已萃取到對話流程中的冗長輸出。替換為簡潔參考:[Obs:{ref_id} 已省略。關鍵點:{summary}。可檢索完整內容。]
  • 立即永遠遮罩:重複/冗餘輸出、樣板標頭和頁尾、已在對話中較早摘要過的輸出。

遮罩應在遮罩的觀察結果上達到 60-80% 的減少,且品質影響低於 2%。關鍵在於保持可檢索性——將完整內容儲存在外部,並在上下文中保留參考 ID,以便代理在需要時可以請求原始內容。

KV 快取優化

透過結構化提示,使穩定內容位於前綴、動態內容位於結尾,來最大化前綴快取命中率。KV 快取儲存在推理期間計算的 Key 與 Value 張量;當連續請求共用相同的前綴時,快取的張量會被重複使用,從而節省成本與延遲。

在每個提示中應用此順序:

  1. 系統提示(最穩定——在一個 session 內永不改變)
  2. 工具定義(在請求間穩定)
  3. 頻繁重複使用的模板和少樣本範例
  4. 對話歷史(會增長,但與先前輪次共用前綴)
  5. 當前查詢和動態內容(最不穩定——永遠放在最後)

為快取穩定性設計提示:從系統提示中移除時間戳、session 計數器和請求 ID。將動態元資料移動到單獨的使用者訊息或工具結果中,使其不會破壞前綴。即使前綴中的一個空白字元變更,也會使該變更點之後的整個快取區塊失效。同樣的規則適用於任何對較早歷史應用的壓縮或遮罩編輯:其成本是其後的文字,因此應批次處理此類編輯,並優先將它們放在上下文末端附近。

對於穩定工作負載,目標是達到 70% 以上的快取命中率。在規模化時,這意味著快取 Token 的成本降低 50% 以上,延遲降低 40% 以上。

上下文分割

當單一上下文無法容納完整問題,且若不分割就會觸發積極壓縮時,將工作分割給子代理。每個子代理在其乾淨、聚焦的上下文中處理子任務,然後將結構化結果返回給協調器代理。

當估計的任務上下文超過視窗限制的 60% 時,規劃分割。將任務分解為獨立的子任務,將每個子任務分配給一個子代理,並彙總結果。在所有分割完成後進行驗證,合併相容的結果,如果彙總後的輸出仍超出預算,則應用摘要。

這種方法實現了關注點分離——詳細的搜尋上下文隔離在子代理中,而協調器則專注於綜合。然而,協調具有真實的 Token 成本:協調器提示、結果彙總和錯誤處理都會消耗 Token。僅在節省超過此開銷時才進行分割。

預算管理

在 session 開始前,為上下文類別分配明確的 Token 預算:系統提示、工具定義、檢索到的文件、訊息歷史、工具輸出以及一個保留緩衝區(總量的 5-10%)。持續監控使用情況與預算的對比,並在任何類別超出其分配或總利用率超過 70% 時觸發最佳化。

使用觸發式最佳化,而非定期最佳化。監控這些訊號:

  • Token 利用率超過 80% —— 觸發壓縮
  • 注意力衰減指標(重複、遺漏指令)—— 觸發遮罩 + 壓縮
  • 品質分數低於基準線 —— 在最佳化前審核上下文組成

實務指導

最佳化決策框架

根據上下文由何者主導來選擇最佳化技術:

上下文組成首要行動次要行動
工具輸出主導 (>50%)觀察遮罩對其餘輪次進行壓縮
檢索到的文件主導摘要如果文件相互獨立則進行分割
訊息歷史主導選擇性保留的壓縮為新的子任務進行分割
多個元件共同貢獻先進行 KV 快取優化,然後疊加遮罩 + 壓縮
接近限制且正在進行除錯僅遮罩已解決的工具輸出 — 保留錯誤詳細資訊

效能目標

追蹤以下指標以驗證最佳化效果:

  • 壓縮:50-70% Token 減少,<5% 品質下降,壓縮步驟本身帶來 <10% 的延遲開銷
  • 遮罩:遮罩的觀察結果減少 60-80%,<2% 品質影響,接近零的延遲開銷
  • 快取優化:穩定工作負載的命中率 >70%,成本降低 >50%,延遲降低 >40%
  • 分割:扣除協調器開銷後的淨 Token 節省;通常需要 3 個以上的子任務才能達到損益平衡

根據測量結果迭代策略。如果某個最佳化技術未能顯著改善目標指標,則移除它——最佳化機制本身會消耗 Token 並增加延遲。

範例

範例 1:壓縮觸發

if context_tokens / context_limit > 0.8:
    context = compact_context(context)

範例 2:觀察遮罩

if len(observation) > max_length:
    ref_id = store_observation(observation)
    return f"[Obs:{ref_id} 已省略。關鍵點:{extract_key(observation)}]"

範例 3:快取友善的排序

# 穩定內容在前
context = [system_prompt, tool_definitions]  # 可快取
context += [reused_templates]  # 可重複使用
context += [unique_content]  # 獨一無二

範例 4:預算觸發的最佳化政策

budgets:
  tool_outputs: 35%
  message_history: 30%
  retrieved_documents: 20%
  reserved_buffer: 15%
triggers:
  tool_outputs_over_budget: mask resolved observations
  total_context_over_70_percent: compact message history
  repeated_irrelevant_retrievals: tighten retrieval scope

指導方針

  1. 在最佳化前進行測量——了解當前狀態
  2. 在壓縮前先應用遮罩——先移除低價值的大量內容,再對剩餘內容進行摘要
  3. 使用一致的提示來設計快取穩定性
  4. 在上下文變得有問題之前進行分割
  5. 持續監控最佳化效果
  6. 在 Token 節省與品質保留之間取得平衡
  7. 在生產規模下測試最佳化
  8. 為邊緣情況實作優雅降級

常見陷阱

  1. 空白字元破壞 KV 快取:提示前綴中即使一個空白字元或換行變更,也會使該點之後的整個 KV 快取區塊失效。將系統提示固定為不可變字串——不要將時間戳、版本號或 session ID 插入其中。在部署之間逐字元比較提示模板。

  2. 系統提示中的時間戳破壞快取命中率:在系統提示中包含 當前日期:{today} 或類似動態內容,會迫使每個新的一天(或者如果使用一天中的時間,每個請求)都完全快取未命中。將動態元資料移動到附加在穩定前綴之後的使用者訊息或單獨的工具結果中。

  3. 在壓力下壓縮會遺失關鍵狀態:當執行壓縮的模型本身處於上下文壓力下(利用率 >85%)時,其摘要品質會下降——它會遺漏任務目標、丟棄使用者約束,並扁平化細微的狀態。在 70-80% 時觸發壓縮,而非 90% 以上。如果必須在後期進行壓縮,請使用一個只包含要摘要材料的乾淨上下文的單獨模型呼叫。

  4. 遮罩錯誤輸出會中斷除錯迴圈:過度積極的遮罩會隱藏錯誤訊息、堆疊追蹤和失敗細節,而代理在後續輪次中需要這些來診斷和修復問題。在活躍除錯期間(最近 3 輪內有錯誤),暫停所有與錯誤相關觀察的遮罩,直到問題解決。

  5. 分割開銷可能超過節省:每個子代理都需要自己的系統提示、工具定義和協調訊息。對於少於 3 個獨立子任務的任務,協調開銷通常會超過上下文節省。在決定進行分割前,先估算總 Token 數(協調器 + 所有子代理)。

  6. 部署變更後的快取未命中成本飆升:在部署之間重新排序工具、改寫系統提示或更改少樣本範例,會使整個前綴快取失效,導致暫時性的成本飆升(2-5 倍),直到新快取預熱。逐步推出提示變更,並在部署期間監控快取命中率。

  7. 壓縮會對過時的摘要產生虛假信心:一旦上下文被壓縮,摘要看起來權威,但可能反映過時的狀態。如果任務在壓縮後有所演進(新的使用者需求、修正過的假設),摘要會默默地攜帶過時資訊。壓縮後,在繼續之前,應根據當前任務目標重新驗證摘要。

整合

此技能負責 Token 效率戰術和預算政策。相鄰技能負責診斷、儲存和架構:

  • context-fundamentals: 關於為何上下文品質和注意力位置很重要的心智模型。
  • context-degradation: 在輸出品質已經下降時的診斷。
  • context-compression: 有損摘要和交接策略。
  • filesystem-context: 用於完整輸出和日誌的檔案卸載。
  • multi-agent-architecture: 子代理協調模式。

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-compression

This skill should be used when long-running agent sessions need context compression, structured summarization, compaction, token-per-task optimization, or durable handoff summaries that preserve decisions, files, risks, and next actions.

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.

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.

相關技能