Community编程与开发github.com

上下文退化诊断

该技能用于诊断和缓解上下文退化:中间信息丢失、上下文污染、上下文冲突、上下文混淆以及由累积或冲突上下文导致的智能体性能下降。

上下文退化诊断 是什么?

该技能提供了一套系统化的工程方法,用于诊断和修复大语言模型(LLM)智能体在长对话或复杂任务中的上下文退化问题。它将退化视为一个连续谱系,涵盖五种可预测的模式:中间信息丢失(Lost-in-Middle)、上下文污染(Poisoning)、上下文干扰(Distraction)、上下文混淆(Confusion)和上下文冲突(Clash)。技能详细阐述了每种模式的检测信号和缓解策略,并基于注意力U型曲线等实证研究,提供了可操作的阈值和基准。主要支持平台包括Claude Code、Cursor、Codex等需要处理长上下文的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
  • 在已知故障模式后应用令牌效率策略:context-optimization
  • 设计压缩或交接摘要策略:context-compression
  • 在提示之外持久化大型输出、日志或暂存状态:filesystem-context

核心概念

围绕注意力U型曲线构建上下文放置:起始和结束位置获得可靠的注意力,而中间位置在长上下文实验中遭受显著的召回准确率下降(claim-context-degradation-lost-middle-ruler)。这不是模型错误,而是注意力机制的结果——第一个令牌(通常是BOS)充当“注意力沉洞”,吸收了不成比例的注意力预算,导致随着上下文增长,中间令牌的注意力不足。

将上下文污染视为电路断路器问题。一旦幻觉、工具错误或错误的检索事实进入上下文,它会通过重复的自我引用而加剧。一个被污染的目标部分会导致每个下游决策都强化错误的假设。检测需要追踪声明来源;恢复需要截断到污染点之前,或仅使用经过验证的上下文重新开始。

在加载上下文之前积极过滤——即使是一篇不相关的文档也会显著降低相关任务的性能。模型无法“跳过”不相关的上下文;它们必须处理提供的所有内容,从而在相关和不相关的内容之间产生注意力竞争。将可能需要但不立即相关的信息放在工具调用之后,而不是预加载。

隔离任务上下文以防止混淆。当上下文包含多种任务类型或在目标之间切换时,模型会合并错误任务的约束,调用适用于不同上下文的工具,或混合来自多个来源的需求。使用独立的上下文窗口进行显式任务分段可以消除交叉污染。

通过优先级规则而不是累积来解决上下文冲突。当多个正确但矛盾的来源出现在上下文中时(版本冲突、视角冲突、多源检索),模型无法确定哪个适用。显式标记矛盾,建立来源优先级,并在它们进入上下文之前过滤掉过时版本。

详细主题

中间信息丢失:检测与放置策略

将关键信息放置在上下文的开头和结尾,永远不要放在中间。U型注意力曲线意味着中间位置的信息召回准确率会下降10-40%。对于超过4000个令牌的上下文,这种影响变得显著。

使用摘要结构,在注意力偏好的位置呈现关键发现。添加显式的章节标题和结构标记——这些通过创建注意力锚点帮助模型导航长上下文。当必须完整包含一个文档时,先附上其关键点的摘要,并在最后加上关键结论。

监控中间信息丢失的症状:上下文中存在正确信息但模型忽略它,响应与提供的数据矛盾,或者模型“忘记”了长提示中早期给出的指令。

上下文污染:预防与恢复

在所有外部输入进入上下文之前进行验证。工具输出、检索到的文档和模型生成的摘要是三个主要的污染向量。每一个都会引入未经核实的声明,后续推理会将其视为基本事实。

通过以下信号检测污染:在以前成功的任务上输出质量下降,工具错位(错误的工具或参数),以及尽管显式纠正仍持续的幻觉。当这些聚集在一起时,要怀疑是污染而不是模型能力问题。

通过移除被污染的内容来恢复,而不是在之上添加修正。截断到污染点之前,仅保留经过验证的信息并重新开始使用干净的上下文,或者显式标记被污染的部分并请求从头开始重新评估。在被污染的上下文之上叠加修正很少有效——原始错误保持着注意力权重。

上下文干扰:策展而非累积

精选进入上下文的内容,而不是依赖模型忽略无关内容。研究表明,即使是单个干扰文档也会触发可测量的性能下降——这种影响遵循阶跃函数,而不是线性曲线。多个干扰项会加剧问题。

在加载检索到的文档之前应用相关性过滤。使用命名空间和结构组织使章节边界清晰。优先使用基于工具调用的访问而不是预加载:将参考材料存储在检索工具之后,这样它只会在与当前推理步骤直接相关时进入上下文。

上下文混淆:任务隔离

将不同的任务分段到独立的上下文窗口中。上下文混淆与干扰不同——它涉及模型将错误上下文约束应用于当前任务,而不仅仅是注意力分散。迹象包括响应解决查询的错误方面,调用适用于不同任务的工具,以及混合来自多个来源需求的输出。

在任务上下文之间实施清晰的转换。使用隔离每个任务的目标、约束和工具定义的状态管理。当在单个会话内进行任务切换不可避免时,使用显式的“上下文重置”标记,指示哪些约束适用于当前段。

上下文冲突:冲突解决协议

在冲突出现之前建立来源优先级规则。上下文冲突不同于中毒——多条信息各自正确但相互矛盾(版本冲突、视角差异、多源检索存在分歧)。

实施版本过滤,在过时信息进入上下文之前排除它。当矛盾不可避免时,使用结构化的冲突注释显式标记它们:说明什么冲突,每个声明来自哪个来源,以及哪个来源优先。没有显式的优先级规则,模型会不可预测地解决矛盾。

实证基准和阈值

使用这些基准来设置设计约束——而不是作为普遍真理。RULER风格的证据表明,广告中的长上下文支持并不能保证在该长度下令人满意的任务性能(claim-context-degradation-lost-middle-ruler)。近乎完美的针包搜索分数并不能预测现实世界的长上下文性能。

特定模型的退化阈值

退化起始点因模型系列和任务类型而异。作为一般规则,对于复杂的检索任务,退化预计在广告上下文窗口的60-70%处开始(RULER基准发现,在声称支持32K+上下文的模型中,只有50%在该长度下保持令人满意的性能)。关键模式:

  • 具有扩展思维的模型通过逐步验证减少幻觉,但延迟和令牌成本更高
  • 针对智能体/编码优化的模型往往对工具输出密集型上下文有更好的注意力管理
  • 具有非常大的上下文窗口(1M+)的模型可以处理更多原始上下文,但仍然遵循U型退化曲线——更大的窗口不能消除问题,只能延迟它

始终使用您特定的工作负载来基准测试退化阈值,而不是依赖已发布的基准。特定模型的阈值会随着每次模型更新而过时(参见陷阱2)。

反直觉的发现

在设计上下文策略时,考虑这些研究支持的反直觉结果:

**打乱的上下文可以胜过连贯的上下文。**研究发现,不连贯(打乱)的“干草堆”在某些检索任务中可能优于逻辑排序的干草堆(claim-context-degradation-distractor-shuffled)。连贯的上下文可能会创建混淆检索的错误关联;不连贯的上下文可以强制精确匹配。不要假设组织得更好的上下文总是产生更好的结果——测试两种安排。

**单个干扰项影响巨大。**与添加更多干扰项相比,一个不相关文档的性能损失不成比例地大。将干扰预防视为二元的:要么保持上下文干净,要么接受显著退化。

**低针问题相似性加速退化。**需要跨不相似内容进行推理的任务随着上下文长度的增加,退化速度比具有高表面相似性的任务更快。设计检索以最大化查询和检索内容之间的语义重叠。

当更大的上下文有害时

不要假设更大的上下文窗口能提高性能。性能在达到特定模型的阈值之前保持稳定,然后迅速下降——曲线是非线性的,有一个悬崖,而不是一个缓坡。对于许多模型,有意义的退化在8K-16K令牌处开始,即使窗口支持更大的尺寸。

考虑成本:处理400K令牌上下文的成本在时间和计算上都比200K呈指数级增长,而不是线性增长。对于许多应用,这使得大上下文处理在经济上不切实际。

认识到认知瓶颈:即使有无限的上下文,要求单个模型在数十个独立任务中保持质量也会产生更多上下文无法解决的退化。将任务拆分给子智能体而不是扩大上下文。

实践指导

四桶缓解框架

根据活跃的退化模式,应用以下四种策略:

写 —— 使用便签本、文件系统或外部存储将上下文保存在窗口之外。当上下文利用率超过窗口的70%时使用。这保持活动上下文精简,同时通过工具调用保持信息访问。

选 —— 通过检索、过滤和优先级排序,只将相关上下文拉入窗口。当出现干扰或混淆症状时使用。在加载之前应用相关性评分;排除低于阈值的任何内容,而不是包括所有可用内容。

压 —— 通过摘要、抽象和观察掩码减少令牌,同时保留信息。当上下文增长但所有内容都相关时使用。用紧凑的结构化摘要替换冗长的工具输出;将重复模式抽象为单个引用。

隔 —— 跨子智能体或会话拆分上下文,以防止任何单个上下文超过其退化阈值。当出现混淆或冲突症状,或任务独立时使用。这是最激进的策略,但对于复杂的多任务系统通常最有效。

弹性架构模式

实施即时上下文加载:仅在当前推理步骤需要时检索信息,而不是预先加载。在处理后使用观察掩码将冗长的工具输出替换为紧凑的引用。部署子智能体架构,每个智能体只持有任务相关的上下文。在上下文超过特定模型的退化起始阈值之前触发压缩——而不是在症状出现之后。

示例

示例1:检测退化

# 长对话期间上下文增长
回合_1: 1000令牌
回合_5: 8000令牌
回合_10: 25000令牌
回合_20: 60000令牌(退化开始)
回合_30: 90000令牌(显著退化)

示例2:缓解中间信息丢失

# 将关键信息组织在边缘

[当前任务]                      # 在开头
- 目标:生成季度报告
- 截止日期:本周末

[详细上下文]                  # 中间(注意力较少)
- 50页数据
- 多个分析章节
- 支持证据

[关键发现]                     # 在结尾
- 收入增长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.

相关技能