Community编程与开发github.com

上下文优化

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

上下文优化 是什么?

上下文优化技能旨在通过战略性压缩、遮蔽、缓存和分区技术,扩展有限上下文窗口的有效容量。有效的优化可以在不依赖更大模型或更长窗口的情况下提升可用容量,但前提是必须结合度量纪律。该技能涵盖四种主要策略:KV缓存优化(通过稳定前缀降低延迟和成本)、观察结果遮蔽(用紧凑引用替换冗长工具输出)、压缩(当上下文利用率超过70%时进行总结并重新初始化)以及上下文分区(将工作拆分为独立子任务,每个子任务由子代理在独立上下文中处理)。此外,还包括预算管理、触发式优化决策框架以及性能指标追踪。技能强调在优化前进行度量,并根据度量结果迭代优化策略,避免过度优化导致质量下降或增加不必要的开销。支持平台包括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-optimization

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

上下文优化技术

上下文优化通过战略性压缩、遮蔽、缓存和分区,扩展了有限上下文窗口的有效容量。有效的优化可以在不依赖更大模型或更长窗口的情况下提升可用容量——但前提是必须结合度量纪律。以下技术按影响和风险排序。

何时激活

当以下情况时激活此技能:

  • 上下文预算或令牌成本限制了任务复杂性
  • 观察结果遮蔽可以将冗长的工具输出替换为可检索的引用
  • 前缀或KV缓存命中率需要改善
  • 检索范围限制可以减少加载的无关上下文
  • 上下文分区可以跨代理扩展有效容量
  • 需要预算触发器来触发遮蔽、压缩或分区

对于应由其他技能处理的相邻工作,请勿激活此技能:

  • 解释注意力或上下文窗口行为的原因:context-fundamentals。
  • 诊断活跃的 Lost-in-Middle、中毒、注意力分散、混淆或冲突:context-degradation。
  • 为长对话设计结构化的交接总结:context-compression。
  • 将大型输出、计划或日志存储为文件:filesystem-context。
  • 模型主动重写自身上下文及其重新填充成本:self-managed-context。

核心概念

按照以下优先级应用四种主要策略:

  1. KV缓存优化 — 重新排序并稳定提示结构,使推理引擎重用缓存的键/值张量。当运行环境支持前缀缓存时,这是最廉价的优化:质量风险低,即时节省成本和延迟。当存在稳定前缀时,优先应用此策略。

  2. 观察结果遮蔽 — 一旦工具输出的目的已经达成,就用紧凑引用替换冗长的输出。工具输出可能主导代理轨迹(claim-context-optimization-tool-output-dominance),因此遮蔽通常能带来最大的容量增益。原始内容在需要时仍可检索。

  3. 压缩 — 当上下文利用率超过70%时,总结当前上下文,然后用总结重新初始化。这会提炼窗口内容,同时保留任务关键状态。压缩是有损的——应先在遮蔽去除低价值内容之后应用。

  4. 上下文分区 — 当单个窗口无法容纳完整问题时,将工作拆分为具有独立上下文的子代理。每个子代理在专注于子任务的干净上下文中操作。当预计上下文超过窗口限制的60%时保留此策略,因为协调开销是真实存在的。

指导原则:上下文质量比数量更重要。每次优化都要保留信号并减少噪声。在优化前进行度量,然后度量优化效果。

详细主题

压缩策略

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

根据不同消息类型保留不同的元素:

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

目标:减少50-70%的令牌,质量下降低于5%。如果压缩超过70%的减少,请审计总结是否存在关键信息丢失——过度激进的压缩是最常见的失败模式。

观察结果遮蔽

根据时效性和持续相关性选择性遮蔽观察结果——而不是统一处理。应用以下规则:

  • 永不遮蔽:对当前任务关键的观察结果、最近的观察结果、在活跃推理链中使用的观察结果,以及调试过程中的错误输出。
  • 3轮后遮蔽:关键点已被提取到对话流中的冗长输出。用紧凑引用替换:[Obs:{ref_id} 已略去。关键点:{summary}。完整内容可检索。]
  • 立即遮蔽:重复/重复输出、样板标头和页脚,以及已在对话中总结过的输出。

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

KV缓存优化

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

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

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

为缓存稳定性设计提示:从系统提示中移除时间戳、会话计数器和请求ID。将动态元数据移到单独的用户消息或工具结果中,使其不会破坏前缀。即使前缀中有一个空格更改,也会使下游的整个缓存块失效。对历史早期部分进行的任何压缩或遮蔽编辑也有同样的代价:其成本是后续文本,因此批量进行此类编辑,并优先放在接近上下文末尾的位置。

对于稳定工作负载,目标缓存命中率为70%以上。在规模上,这意味着50%以上的成本降低和40%以上的延迟减少。

上下文分区

当单个上下文无法容纳完整问题且不触发激进压缩时,将工作分区到子代理。每个子代理在其子任务的干净、聚焦的上下文中操作,然后将结构化结果返回给协调代理。

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

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

预算管理

在会话开始前,在上下文类别之间分配显式令牌预算:系统提示、工具定义、检索到的文档、消息历史、工具输出以及预留缓冲区(总预算的5-10%)。持续监控使用情况与预算,当任何类别超出分配或总利用率超过70%时触发优化。

使用触发式优化而不是定期优化。监控以下信号:

  • 令牌利用率超过80% — 触发压缩
  • 注意力退化指标(重复、遗漏指令) — 触发遮蔽+压缩
  • 质量分数低于基线 — 在优化前审计上下文组成

实用指导

优化决策框架

根据上下文的主要组成选择优化技术:

上下文组成首要操作次要操作
工具输出占主导(>50%)观察结果遮蔽压缩剩余轮次
检索到的文档占主导总结如果文档独立,进行分区
消息历史占主导选择性保留的压缩对新子任务进行分区
多个组成部分共同贡献首先KV缓存优化,然后分层遮蔽+压缩
接近限制且有活跃调试仅遮蔽已解决的工具输出——保留错误细节

性能目标

跟踪这些指标以验证优化有效性:

  • 压缩:减少50-70%令牌,质量下降<5%,压缩步骤本身的延迟开销<10%
  • 遮蔽:被遮蔽观察结果减少60-80%,质量影响<2%,延迟开销接近零
  • 缓存优化:稳定工作负载命中率>70%,成本降低>50%,延迟降低>40%
  • 分区:扣除协调开销后的净令牌节省;通常需要3个以上子任务才能达到盈亏平衡

根据度量结果迭代策略。如果某项优化技术未能在目标指标上带来可测量的改善,请移除它——优化机制本身也会消耗令牌并增加延迟。

示例

示例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: 遮蔽已解决的观察
  total_context_over_70_percent: 压缩消息历史
  repeated_irrelevant_retrievals: 收紧检索范围

指南

  1. 在优化前进行度量——了解当前状态
  2. 先应用遮蔽再压缩——先移除低价值内容,然后总结剩余部分
  3. 通过一致的提示设计实现缓存稳定性
  4. 在上下文变得有问题之前进行分区
  5. 持续监控优化效果
  6. 在令牌节省与质量保持之间取得平衡
  7. 在生产规模下测试优化
  8. 为边缘情况实施优雅降级

陷阱

  1. 空格破坏KV缓存:提示前缀中即使是单个空格或换行符更改,也会使下游的整个KV缓存块失效。将系统提示固定为不可变字符串——不要将时间戳、版本号或会话ID插值到其中。在部署之间逐字节比较提示模板。

  2. 系统提示中的时间戳破坏缓存命中率:在系统提示中包含Current date: {today}或类似的动态内容会导致每天(或每次请求,如果使用当天时间)完全缓存未命中。将动态元数据移动到稳定前缀之后的用户消息或单独工具结果中。

  3. 压力下的压缩丢失关键状态:当执行压缩的模型本身处于上下文压力下(利用率>85%),其总结质量会下降——它会遗漏任务目标、丢弃用户约束、并使微妙的上下文变得扁平。在70-80%时触发压缩,而不是90%+。如果必须延迟压缩,应使用单独的模型调用,使用仅包含要总结材料的干净上下文。

  4. 遮蔽错误输出破坏调试循环:过度激进的遮蔽隐藏了错误消息、堆栈跟踪和失败细节,而代理在后续轮次中需要这些信息来诊断和修复问题。在活跃调试期间(最近3轮内有错误),暂停对所有错误相关观察结果的遮蔽,直到问题解决。

  5. 分区开销可能超过节省:每个子代理都需要自己的系统提示、工具定义和协调消息。对于少于3个独立子任务的任务,协调开销通常会超过上下文节省。在承诺分区之前,估算总令牌数(协调器+所有子代理)。

  6. 部署更改后的缓存未命中成本飙升:重新排序工具、重新措辞系统提示或更改部署之间的少样本示例会使整个前缀缓存失效,导致2-5倍的临时成本飙升,直到新缓存预热。逐步推出提示更改,并在部署窗口期间监控缓存命中率。

  7. 压缩导致对过时总结的虚假信心:一旦上下文被压缩,总结看起来权威,但可能反映的是过时的状态。如果自压缩以来任务发生了变化(新的用户需求、修正的假设),总结会默默地携带过时信息。压缩后,在继续之前根据当前任务目标重新验证总结。

集成

此技能拥有令牌效率策略和预算政策的所有权。相邻技能拥有诊断、存储和架构:

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

相关技能