Community编程与开发github.com

上下文优化

该技能用于提升上下文效率:上下文预算、观察掩蔽、前缀或 KV 缓存策略、分区、Token 成本降低、检索范围限定,以及在不降低回答质量的情况下扩展有效上下文容量。

上下文优化 是什么?

该技能提供了一套系统化的上下文优化技术,旨在有限上下文窗口内最大程度提升有效容量。它涵盖了四种核心策略,并按影响和风险排序:KV 缓存优化(利用推理引擎复用缓存张量)、观察掩蔽(将冗长的工具输出替换为紧凑引用)、压缩(在利用率超过 70% 时汇总上下文)以及上下文分区(将任务拆分到多个子代理,各子代理拥有独立上下文)。该技能详细说明了何时激活(例如,上下文预算限制、观察掩蔽需求、KV 缓存命中率提升等),并明确划定了与相邻技能(如 `context-degradation`、`context-compression`)的责任边界。它提供了详细的决策框架、性能目标(如压缩应达到 50-70% 的 Token 减少且质量下降低于 5%)、实用指南和常见陷阱(例如,空白字符会破坏 KV 缓存,时间戳会降低缓存命中率)。该技能适用于多种平台,包括 AI 代理、开发工具和软件工程环境,强调“先测量再优化”的原则,并基于量化结果迭代优化策略。

兼容平台~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 缓存优化——重新排序并稳定提示结构,使推理引擎复用缓存的键/值张量。当运行时支持前缀缓存时,这是最便宜的优化:质量风险低,即时节省成本和延迟。当存在稳定前缀时优先应用。

  2. 观察掩蔽——一旦工具输出达到目的,将其替换为紧凑引用。工具输出可能主导代理轨迹(claim-context-optimization-tool-output-dominance),因此掩蔽通常能带来最大的容量增益。原始内容在必要时仍可检索。

  3. 压缩——当上下文利用率超过 70% 时,对累积的上下文进行汇总,然后使用摘要重新初始化。这会提炼窗口内容,同时保留任务关键状态。压缩是有损的——在掩蔽已移除低价值内容后应用。

  4. 上下文分区——当单个窗口无法容纳完整问题时,将工作拆分到具有隔离上下文的子代理。每个子代理在其子任务上以干净上下文运行。仅在估计上下文超过窗口限制 60% 时保留此选项,因为协调开销是真实存在的。

指导原则:上下文质量比数量更重要。每种优化都在降低噪声的同时保留信号。先测量再优化,然后测量优化的效果。

详细主题

压缩策略

当上下文利用率超过 70% 时触发压缩:汇总当前上下文,然后使用摘要重新初始化。这以高保真度提炼窗口内容,从而以最小的性能下降继续执行。优先压缩工具输出(它们消耗 80%+ 的 Token),然后是旧对话轮次,最后是检索到的文档。切勿压缩系统提示——它锚定模型行为,其移除会导致不可预测的性能下降。

按消息类型保留不同元素:

  • 工具输出:提取关键发现、指标、错误代码和结论。删除冗长的原始输出、堆栈跟踪(除非调试正在进行)和样板头文件。
  • 对话轮次:保留决策、承诺、用户偏好和上下文转换。删除填充词、客套话以及已得出已捕获结论的探索性来回对话。
  • 检索到的文档:保留与活动任务相关的声明、事实和数据点。删除仅用于一次性推理目的的支持性证据和阐述。

目标是实现 50-70% 的 Token 减少,质量下降低于 5%。如果压缩超过 70% 的减少量,请审计摘要是否存在关键信息丢失——过度压缩是最常见的失败模式。

观察掩蔽

根据最近性和持续相关性选择性地掩蔽观察结果——而不是统一掩蔽。应用以下规则:

  • 切勿掩蔽:对当前任务至关重要的观察结果、最近一轮的观察结果、活跃推理链中使用的观察结果,以及调试进行中的错误输出。
  • 在 3 轮之后掩蔽:其关键点已被提取到对话流中的冗长输出。替换为紧凑引用:[Obs:{ref_id} 已省略。关键点:{摘要}。完整内容可检索。]
  • 始终立即掩蔽:重复/重复输出、样板头文件和页脚,以及对话中早已汇总的输出。

掩蔽应实现被掩蔽观察结果 60-80% 的减少,质量影响低于 2%。关键在于保持可检索性——将完整内容存储在外部,并在上下文中保留引用 ID,以便代理在需要时可以请求原始内容。

KV 缓存优化

通过构建提示使稳定内容占据前缀,动态内容出现在末尾,从而最大化前缀缓存命中。KV 缓存存储在推理期间计算的键和值张量;当连续请求共享相同前缀时,缓存张量被复用,节省成本和延迟。

在每个提示中应用此顺序:

  1. 系统提示(最稳定——在会话中从不改变)
  2. 工具定义(在请求之间稳定)
  3. 频繁复用的模板和少量示例
  4. 对话历史(增长但与先前轮次共享前缀)
  5. 当前查询和动态内容(最不稳定——始终最后)

为缓存稳定性设计提示:从系统提示中移除时间戳、会话计数器和请求 ID。将动态元数据移动到单独的用户消息或工具结果中,使其不会破坏前缀。前缀中即使单个空白字符的更改也会使该点之后整个缓存块失效。相同的规则适用于对早期历史进行任何压缩或掩蔽编辑:其成本是其后面的文本,因此请批量进行此类编辑,并优先在上下文末尾附近进行。

针对稳定工作负载实现 70%+ 的缓存命中率。在规模化情况下,这相当于 50%+ 的成本降低和 40%+ 的缓存 Token 延迟降低。

上下文分区

当单个上下文无法容纳完整问题而不触发激进压缩时,在子代理之间分配工作。每个子代理在其子任务上以干净、集中的上下文运行,然后将结构化结果返回给协调代理。

当估计任务上下文超过窗口限制的 60% 时,规划分区。将任务分解为独立的子任务,分配给每个子代理,并汇总结果。验证所有分区是否完成,合并兼容结果,如果汇总输出仍超出预算,则应用汇总。

这种方法实现了关注点分离——详细的搜索上下文隔离在子代理内部,而协调代理专注于综合。然而,协调具有实际的 Token 成本:协调代理提示、结果汇总和错误处理都会消耗 Token。仅在节省超过此开销时才进行分区。

预算管理

在会话开始前,跨上下文类别分配显式 Token 预算:系统提示、工具定义、检索到的文档、消息历史、工具输出以及保留缓冲区(总 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 缓存块失效。将系统提示固定为不可变字符串——不要将时间戳、版本号或会话 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.

相关技能