Community程式設計與開發github.com

上下文最佳化

此技能應在用於提升上下文效率時啟用:上下文預算、觀察遮罩、前綴或 KV-cache 策略、分割、token 成本降低、檢索範圍限制,以及在不高回答品質的前提下擴展有效上下文容量。

上下文最佳化 是什麼?

上下文最佳化透過策略性壓縮、遮罩、快取和分割來擴展有限上下文視窗的容量。它依序應用四種主要策略:KV-cache 最佳化(透過結構化提示最大化前綴快取命中率)、觀察遮罩(以可檢索的參考取代冗長的工具輸出)、壓縮(在容量利用率超過 70% 時摘要上下文並重新初始化)和上下文分割(當單一視窗無法容納整個問題時,將工作分配給多個子代理)。此技能支援各種平台和執行環境,並強調「先測量,再最佳化」的紀律,以驗證最佳化效果。關鍵注意事項包括:空白字元會破壞 KV-cache、錯誤輸出遮罩會中斷除錯循環、分割的協調開銷可能超過節省的 token,以及壓縮會因過時的摘要而導致錯誤的自信。為開發人員提供具體的效能目標(例如壓縮達 50-70% token 減少且品質下降低於 5%)、決策框架和範例。

相容平台~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-cache 命中率需要提升
  • 檢索範圍限制可以減少不相關的載入上下文
  • 上下文分割可以跨代理擴展有效容量
  • 需要預算觸發器來進行遮罩、壓縮或分割

請勿對其他技能負責的相關工作啟用此技能:

  • 解釋注意力或上下文視窗為何如此運作:context-fundamentals。
  • 診斷活躍的「中間遺失」、中毒、分心、混淆或衝突:context-degradation。
  • 為長對話設計結構化的交接摘要:context-compression。
  • 將大型輸出、計畫或日誌儲存為檔案:filesystem-context。
  • 模型自行改寫其上下文及其重新填充成本:self-managed-context。

核心概念

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

  1. KV-cache 最佳化 — 重新排序並穩定提示結構,使推理引擎能重複使用快取的 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-Cache 最佳化

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

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

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

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

對於穩定工作負載,目標是達到 70% 以上的快取命中率。在大規模應用時,這可轉化為 50% 以上的成本降低和 40% 以上的快取 token 延遲降低。

上下文分割

當單一上下文無法容納完整問題而不觸發激進壓縮時,將工作分割給子代理。每個子代理在其子任務上以乾淨、專注的上下文運作,然後將結構化的結果返回給協調器代理。

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

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

預算管理

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

使用觸發式最佳化,而不是定期最佳化。監控以下信號:

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

實務指引

最佳化決策框架

根據上下文中佔主導地位的內容來選擇最佳化技術:

上下文組成第一步行動第二步行動
工具輸出佔主導地位 (>50%)觀察遮罩壓縮剩餘的回合
檢索到的文件佔主導地位摘要如果文件彼此獨立則進行分割
訊息歷史佔主導地位具有選擇性保留的壓縮為新子任務進行分割
多個組成部分共同貢獻先進行 KV-cache 最佳化,然後疊加遮罩 + 壓縮
接近限制且正在進行除錯僅遮罩已解決的工具輸出——保留錯誤詳細資訊

效能目標

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

  • 壓縮: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-cache:即使提示前綴中只有一個空白字元或換行符號的變更,都會使該變更點之後的整個 KV-cache 區塊失效。將系統提示固定為不可變字串——不要將時間戳、版本號或 session ID 插入其中。在部署之間按位元組比對提示模板。

  2. 系統提示中的時間戳會破壞快取命中率:在系統提示中包含 Current date: {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-patterns:跨隔離代理上下文的工作分割。
  • latent-briefing:跨編排的選擇性 KV 保留

…

[翻譯截斷]

Individual skills in this repo

This repo contains 19 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.

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.

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.

tool-design

This skill should be used for the tool-interface layer of an agent system specifically: writing tool descriptions agents can route on, designing tool schemas and response formats, naming conventions, actionable error recovery messages, MCP server design, tool-set consolidation, and deciding when to add or remove an individual tool. Use this when the unit of work is a single tool or a set of tools. Route project-shape, pipeline architecture, and task-model-fit decisions to project-development; route deciding whether to introduce sub-agents to multi-agent-patterns.

相關技能