Community程式設計與開發github.com

語境退化診斷與緩解

此技能用於診斷與緩解語境退化問題,包含「迷失在中間」、「語境中毒」、「語境干擾」、「語境混淆」和「語境衝突」,協助處理代理人性能因累積或衝突語境而下降的情況。

語境退化診斷與緩解 是什麼?

此技能專注於診斷與緩解 AI 代理人系統中的語境退化問題,這是一個非二元、可預測的連續現象,包含五種明確模式:迷失在中間 (Lost-in-Middle)、語境中毒 (Poisoning)、語境干擾 (Distraction)、語境混淆 (Confusion) 和語境衝突 (Clash)。每個模式都有特定的檢測訊號與緩解策略,將退化視為有可衡量閾值的工程問題。 技能支援的關鍵觀念包括:利用注意力曲線 (U-curve) 結構化放置語境,將關鍵資訊置於開頭與結尾;將語境中毒視為斷路器問題,需追溯至污染點前進行截斷或重新啟動;強調在載入語境前積極過濾,因為即使單一文檔也可能顯著降低相關任務的性能;隔離任務語境以防止混淆,透過明確的任務分段與獨立窗口來消除交叉污染;以及透過優先規則而非累積來解決語境衝突。 實務指引包含四桶緩解框架:Write(將語境寫出至外部儲存)、Select(透過檢索與過濾選擇相關語境)、Compress(透過摘要與抽象化壓縮語境)以及 Isolate(將語境分割至子代理人或工作階段)。技能也提供架構模式,如即時載入語境、觀察遮罩以及子代理人架構,確保語境大小不超過觸發退化的閾值。 此技能適用於多種平台,包括但不限於 Claude Code、Cursor 及其他 AI 編碼代理工具,主要用於診斷長期對話中代理人性能意外下降、錯誤輸出、或需要處理大型語境的生產系統設計。

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

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

在你喜歡的 AI 中提問

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

說明文件

語境退化模式

在退化連鎖反應發生之前進行診斷與修復。語境退化並非二元狀態——它是一個連續體,透過五種明確、可預測的模式表現出來:迷失在中間、中毒、干擾、混淆和衝突。每種模式都有特定的檢測訊號與緩解策略。請將退化視為具有可測量閾值的工程問題,而非不可預測的故障模式。

何時啟用

在以下情況啟用此技能:

  • 代理人在長時間對話中意外出現性能下降
  • 調試代理人產出不正確或不相關輸出的案例
  • 設計必須可靠處理大型語境的系統
  • 評估生產系統的語境工程選擇
  • 調查代理人輸出中的「迷失在中間」現象
  • 分析代理人行為中與語境相關的故障

不要在以下情況啟用此技能,這些工作屬於其他技能:

  • 在沒有主動故障的情況下解釋基礎語境機制:context-fundamentals。
  • 在已知故障模式後應用 token 效率策略:context-optimization。
  • 設計壓縮或交接摘要策略:context-compression。
  • 在提示之外持久化大型輸出、日誌或暫存狀態:filesystem-context。

核心概念

圍繞注意力 U 曲線結構化語境放置:開頭和結尾位置獲得可靠的注意力,而中間位置在長時間上下文的實驗中(claim-context-degradation-lost-middle-ruler)顯示出顯著降低的召回準確度。這不是模型錯誤,而是注意力機制帶來的後果——第一個 token(通常是 BOS)充當「注意力滙集處」,吸收了不成比例的注意力預算,隨著語境增長,中間 token 的注意力變得不足。

將語境中毒視為斷路器問題。一旦幻覺、工具錯誤或不正確的檢索事實進入語境,它會通過反覆自我引用而加劇。一個中毒的目標部分會導致每個下游決策強化錯誤假設。檢測需要追蹤宣稱來源;恢復需要截斷到中毒點之前或僅使用經過驗證的語境重新啟動。

在載入語境之前積極過濾——即使一篇不相關的文檔也會顯著降低相關任務的性能。模型無法「跳過」不相關的語境;它們必須關注所提供的所有內容,這會造成相關與不相關內容之間的注意力競爭。將可能需要但並非立即相關的資訊放在工具呼叫之後,而不是預先載入。

隔離任務語境以防止混淆。當語境包含多種任務類型或在目標之間切換時,模型會從錯誤任務中納入限制條件,呼叫適用於不同語境的工具,或混合來自多個來源的需求。使用明確的任務分割與獨立語境窗口來消除交叉污染。

透過優先規則而非累積來解決語境衝突。當語境中出現多個正確但相互矛盾的來源(版本衝突、觀點衝突、多來源檢索)時,模型無法確定哪一個適用。明確標記矛盾,建立來源優先級,並在過時版本進入語境之前將其過濾掉。

詳細主題

迷失在中間:檢測與放置策略

將關鍵資訊放置在語境的開頭和結尾,絕對不要放在中間。U 形注意力曲線意味著放置在中間的資訊召回準確度會降低 10-40%。對於超過 4K token 的語境,此效果會變得顯著。

使用摘要結構在注意力偏好的位置呈現關鍵發現。添加明確的分節標題和結構標記——這些可以幫助模型通過創建注意力錨點來導航長語境。當必須完整包含一個文檔時,在其前面添加關鍵點摘要,並在末尾附上關鍵結論。

監控迷失在中間的症狀:正確資訊存在於語境中但模型忽略它、回應與提供的資料相矛盾、或者模型「忘記」在長提示中較早給出的指令。

語境中毒:預防與恢復

在所有外部輸入進入語境之前對其進行驗證。工具輸出、檢索文檔和模型生成的摘要是三個主要的中毒載體。每個都可能引入未經驗證的宣稱,後續推理會將其視為事實。

通過以下信號檢測中毒:先前成功的任務輸出品質下降、工具不對齊(使用了錯誤的工具或參數)、以及即使明確糾正仍持續存在的幻覺。當這些信號同時出現時,懷疑是中毒而不是模型能力問題。

通過移除中毒內容來恢復,而不是在頂層添加糾正。截斷到中毒點之前,使用僅保留經過驗證資訊的乾淨語境重新啟動,或明確標記中毒部分並請求從頭重新評估。在中毒語境之上疊加糾正很少有效——原始錯誤仍會保留注意力權重。

語境干擾:策展而非累積

策展進入語境的內容,而不是依賴模型忽略不相關的內容。研究顯示,即使一篇干擾文檔也會觸發可測量的性能下降——其效果遵循階梯函數,而非線性曲線。多篇干擾文檔會加劇問題。

在載入檢索文檔之前應用相關性過濾。使用命名空間和結構化組織使分節邊界清晰。偏好基於工具呼叫的訪問而非預載入:將參考資料儲存在檢索工具之後,使其僅在與當前推理步驟直接相關時才進入語境。

語境混淆:任務隔離

將不同任務分割到獨立的語境窗口中。語境混淆與干擾不同——它涉及模型將錯誤語境的限制條件應用於當前任務,而不僅僅是注意力稀釋。跡象包括回應針對查詢的錯誤方面、呼叫適用於不同任務的工具、以及輸出混合了來自多個來源的需求。

在任務語境之間實施清晰的轉換。使用隔離每個任務目標、限制條件和工具定義的狀態管理。當在單一會話中不可避免地需要任務切換時,使用明確的「語境重置」標記來指示哪些限制條件適用於當前區段。

語境衝突:衝突解決協議

在衝突發生之前建立來源優先規則。語境衝突不同於中毒——多條資訊各自正確但相互矛盾(版本衝突、觀點差異、具有分歧事實的多來源檢索)。

實施版本過濾以在過時資訊進入語境之前將其排除。當矛盾不可避免時,使用結構化的衝突註解明確標記它們:說明衝突的是什麼、每個宣稱來自哪個來源、以及哪個來源具有優先權。如果沒有明確的優先規則,模型解決矛盾的方式將不可預測。

實證基準與閾值

使用這些基準來設定設計限制——不要將它們視為普遍真理。RULER 風格的證據顯示,廣告中支援的長語境並不能保證在該長度下令人滿意的任務性能(claim-context-degradation-lost-middle-ruler)。近乎完美的「大海撈針」分數並不能預測真實世界的長語境性能。

模型特定退化閾值

退化的起始點因模型系列和任務類型而異。一般規則是,對於複雜的檢索任務,退化預計在廣告語境窗口的 60-70% 時開始(RULER 基準發現,只有 50% 聲稱支援 32K+ 語境的模型在該長度下維持令人滿意的性能)。關鍵模式:

  • 具有擴展思維的模型通過逐步驗證減少幻覺,但延遲和 token 成本更高
  • 針對代理人/編碼優化的模型對於工具輸出密集型語境具有更好的注意力管理
  • 具有非常大語境窗口(1M+)的模型可以處理更多原始語境,但仍遵循 U 形退化曲線——更大的窗口並不能消除問題,只是延遲它

始終使用您的特定工作負載來基準測試退化閾值,而不是依賴已發佈的基準。模型特定閾值會隨著每次模型更新而過時(參見陷阱 2)。

反直覺發現

在設計語境策略時考慮以下經研究支持的意外結果:

混亂的語境可能勝過有條理的語境。 研究發現,對於某些檢索任務,無序(混亂)的乾草堆可以勝過邏輯有序的乾草堆(claim-context-degradation-distractor-shuffled)。有條理的語境可能創建混淆檢索的虛假關聯;無序語境可以強制進行精確匹配。不要假設組織得更好的語境總是產生更好的結果——測試兩種排列。

單一干擾物的影響不成比例。 一篇不相關文檔帶來的性能損失相對於添加更多干擾物是巨大的。將干擾物預防視為二元問題:保持語境乾淨,否則接受顯著退化。

低針問題相似性加速退化。 需要跨不相似內容進行推理的任務隨著語境長度增長退化速度比高表面相似性的任務更快。設計檢索以最大化查詢與檢索內容之間的語義重疊。

何時更大的語境會造成傷害

不要假設更大的語境窗口會提高性能。性能在達到模型特定閾值之前保持穩定,然後急劇下降——曲線是非線性的,具有懸崖邊緣,而不是平緩的斜坡。對於許多模型,即使窗口支援更大的尺寸,在 8K-16K token 時就會開始有意義的退化。

考慮成本:處理 400K token 語境的時間和計算成本是指數級增長,而非線性。對於許多應用,這使得大語境處理在經濟上不可行。

認識到認知瓶頸:即使擁有無限的語境,要求單個模型在數十個獨立任務中維持品質也會產生更多語境無法解決的退化。將任務拆分到子代理人,而不是擴充語境。

實務指引

四桶緩解框架

根據活躍的退化模式應用以下四種策略:

寫出 — 使用暫存、檔案系統或外部儲存將語境保存到窗口之外。當語境利用率超過窗口的 70% 時使用。這可以保持活躍語境精簡,同時通過工具呼叫保留資訊存取。

選擇 — 通過檢索、過濾和優先排序僅將相關語境拉入窗口。當出現干擾或混淆症狀時使用。在載入之前應用相關性評分;排除低於閾值的內容,而不是包括所有可用的內容。

壓縮 — 通過摘要、抽象化和觀察遮罩減少 token 同時保留資訊。當語境在增長但所有內容都相關時使用。用緊湊的結構化摘要替換冗長的工具輸出;將重複模式抽象為單一引用。

隔離 — 將語境分割到子代理人或工作階段,以防止任何單個語境超過其退化閾值。當出現混淆或衝突症狀,或當任務獨立時使用。這是最激進的策略,但對於複雜的多任務系統通常最有效。

用於彈性的架構模式

實施即時語境載入:僅在當前推理步驟需要時才檢索資訊,而不是預先載入。使用觀察遮罩在處理後用緊湊引用替換冗長的工具輸出。部署子代理人架構,其中每個代理人僅持有與任務相關的語境。在語境超過模型特定退化起始閾值之前觸發壓縮——而不是在出現症狀之後。

範例

範例 1:檢測退化

# 語境在長時間對話中增長
turn_1: 1000 tokens
turn_5: 8000 tokens
turn_10: 25000 tokens
turn_20: 60000 tokens (退化開始)
turn_30: 90000 tokens (顯著退化)

範例 2:緩解迷失在中間

# 將關鍵資訊放在邊緣來組織語境

[CURRENT TASK]                      # 開頭
- 目標:生成季度報告
- 截止日期:本週末

[DETAILED CONTEXT]                  # 中間(注意力較少)
- 50 頁數據
- 多個分析部分
- 支持證據

[KEY FINDINGS]                     # 結尾
- 營收增長 15%
- 成本下降 8%
- A 區域增長

範例 3:語境中毒斷路器

症狀:代理人在糾正後仍持續引用不正確的檢索宣稱
診斷:語境中毒,非缺少指令問題
行動:
  1. 識別不正確資訊進入的第一個輪次
  2. 截斷或從該點之前重新啟動
  3. 僅重新載入經過驗證的來源
  4. 記錄被拒絕的宣稱和來源出處

範例 4:語境衝突註解

衝突:
  主題:計費 API 版本
  來源_a:docs/v1.md 說端點是 /charges
  來源_b:docs/v2.md 說端點是 /payments
  優先權:docs/v2.md
  原因:當前生產版本

指導原則

  1. 在開發期間監控語境長度和性能相關性
  2. 將關鍵資訊置於語境的開頭或結尾
  3. 在退化變得嚴重之前實施壓縮觸發器
  4. 在將檢索文檔添加到語境之前驗證其準確性
  5. 使用版本控制防止過時資訊導致衝突
  6. 分段任務以防止不同目標之間的語境混淆
  7. 設計優雅退化而非……

…… [為翻譯而截斷]

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

相關技能