Community编程与开发github.com

上下文压缩

当长时间运行的智能代理会话需要进行上下文压缩、结构化摘要、压缩、按令牌优化任务或持久的交接摘要(保留决策、文件、风险和下一步行动)时,应使用此技能。

上下文压缩 是什么?

上下文压缩策略是一项专门技能,适用于需要处理超过上下文窗口限制的长时间运行智能代理会话的场景。它解决了令牌消耗与关键信息保留之间的核心权衡,并推荐了三种生产就绪的方法:锚定迭代摘要(用于长期会话和文件跟踪)、不透明压缩(用于最大化节省令牌)和再生式摘要(当摘要可读性至关重要时)。该技能强调,优化目标是每个任务的令牌总数,而不是每个请求的令牌数,因为过度压缩可能导致代理重新获取信息的成本高于节省的成本。它提供了详细的结构化摘要格式,包含用于会话意图、文件修改、决策和后续步骤的强制性部分,并建议使用基于探针的评估来验证压缩质量。该技能特别适用于编码代理、调试场景以及代码库超过500万个令牌的系统。

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

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

在你喜欢的 AI 中提问

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

文档

上下文压缩策略

当代理会话生成数百万令牌的对话历史记录时,压缩变得必不可少。天真的方法是进行激进压缩,以最小化每个请求的令牌数。正确的优化目标是每个任务的令牌数:完成一个任务消耗的总令牌数,包括当压缩丢失关键信息时的重新获取成本。

何时激活

在以下情况下激活此技能:

  • 代理会话超过上下文窗口限制
  • 代码库超过上下文窗口(500万+令牌系统)
  • 设计对话摘要策略时
  • 调试代理“忘记”其修改了哪些文件的情况时
  • 构建压缩质量评估框架时
  • 创建持久的交接摘要,保留决策、文件、风险和下一步行动时

对于属于其他技能的相邻工作,请勿激活此技能:

  • 通用令牌效率策略,如掩码、前缀缓存或分区:请使用 context-optimization。
  • 在选择缓解措施之前诊断长上下文失败的原因:请使用 context-degradation。
  • 在未进行摘要的情况下,将原始输出、日志或计划写入文件:请使用 filesystem-context。
  • 跨会话设计长期语义记忆:请使用 memory-systems。
  • 模型决定何时以及何地重写其自己的上下文:请使用 self-managed-context。此技能仍然负责确定替换文本必须保留的内容。
  • 决定给定模型或工具链是否应触发压缩,并在不同上下文预算下衡量该行为:请使用 compaction-control-profiling。

核心概念

上下文压缩在节省令牌和丢失信息之间进行权衡。根据会话特征,从三种生产就绪的方法中选择:

  1. 锚定迭代摘要:对于文件跟踪至关重要的长时间运行会话,请实施此方法。维护结构化的、持久的摘要,其中包含会话意图、文件修改、决策和后续步骤的显式部分。当压缩触发时,仅对新截断的跨度进行摘要,并与现有摘要合并,而不是从头开始重新生成。这可以防止在完全重新生成摘要时累积的漂移——每次重新生成都可能丢失模型认为优先级低但任务需要的详细信息。结构化强制保留信息,因为专用部分充当摘要器必须填充的检查表,从而捕获静默信息丢失。

  2. 不透明压缩:将此方法保留给短期会话,其中重新获取成本低且需要最大令牌节省。它生成针对重建保真度优化的压缩表示,实现99%以上的压缩率,但完全牺牲了可解释性。这种权衡很重要:如果不进行基于探针的评估,就无法验证保留了哪些内容,因此在调试或工件跟踪至关重要时,切勿使用此方法。

  3. 再生式完整摘要:当摘要可读性至关重要且会话具有清晰的阶段边界时,请使用此方法。它在每次压缩触发时生成详细的结构化摘要。其弱点是在重复循环中累积的细节丢失——每次完全再生都是一次全新的传递,可能会降低早期摘要中保留的细节的优先级。

详细主题

优化每个任务的令牌数,而非每个请求的令牌数

衡量从任务开始到完成消耗的总令牌数,而不是每个单独请求的令牌数。当压缩丢弃文件路径、错误消息或决策理由时,代理必须重新探索、重新读取文件并重新推导结论——这比压缩节省的令牌要浪费得多。一种在每个请求上节省0.5%令牌但导致20%更多重新获取成本的策略,其总体成本更高。将重新获取频率作为主要质量信号进行跟踪:如果代理反复要求重新读取已经处理过的文件,则压缩过于激进。

首先解决工件追踪问题

工件追踪完整性通常是压缩评估中最薄弱的维度(引用:context-compression-factory-benchmark)。请主动解决此问题,因为通用摘要无法可靠地维护它。

在每个压缩周期中显式保留以下类别:

  • 创建了哪些文件(完整路径)
  • 修改了哪些文件以及更改了什么(包括函数名,而不仅仅是文件名)
  • 读取了但未更改的文件
  • 特定标识符:函数名、变量名、错误消息、错误代码

在代理工具链中实现单独的工件索引或显式文件状态跟踪,而不是依赖摘要器来捕获这些细节。即使是具有专用文件部分的结构化摘要,也难以在长时间会话中保持完整性。

使用强制性部分构建摘要

构建具有显式部分的结构化摘要,以防止静默信息丢失。每个部分都充当摘要器必须填充的检查表,使遗漏变得可见,而不是悄然发生。

## 会话意图
[用户试图完成什么]

## 已修改的文件
- auth.controller.ts:修复了 JWT 令牌生成
- config/redis.ts:更新了连接池
- tests/auth.test.ts:为新配置添加了模拟设置

## 已做出的决策
- 使用 Redis 连接池而非每个请求一个连接
- 对瞬时故障采用指数退避的重试逻辑

## 当前状态
- 14 个测试通过,2 个失败
- 待完成:会话服务测试的模拟设置

## 后续步骤
1. 修复剩余的测试失败
2. 运行完整的测试套件
3. 更新文档

根据代理的领域调整各部分。调试代理需要“根因”和“错误消息”部分;迁移代理需要“源模式”和“目标模式”部分。结构本身比特定的部分更重要——任何显式模式都优于自由形式的摘要。

战略性地选择压缩触发器

何时触发压缩与如何压缩同样重要。根据会话可预测性选择触发策略:

策略触发点权衡
固定阈值70-80% 的上下文利用率简单,但可能过早压缩
滑动窗口保留最后 N 轮对话 + 摘要可预测的上下文大小
基于重要性首先压缩低相关性部分复杂,但能保留信号
任务边界在逻辑任务完成时压缩摘要清晰,但时机不可预测

对于编码代理,默认使用滑动窗口加结构化摘要——它在可预测性和质量之间提供了最佳平衡。当会话具有清晰的阶段转换(例如,研究、实施、然后测试)时,使用任务边界触发器。

使用探针而非指标评估压缩效果

传统指标如 ROUGE 或嵌入相似度无法捕捉功能性的压缩质量。一个摘要可能在词汇重叠上得分很高,但同时遗漏了代理继续工作所需的关键文件路径。

使用基于探针的评估:压缩后,提出一些问题来测试关键信息是否幸存。如果代理正确回答,说明压缩保留了正确的信息。如果没有,它就会猜测或产生幻觉。

探针类型测试内容示例问题
召回事实性保留“原始错误消息是什么?”
工件文件跟踪“我们修改了哪些文件?”
连续性任务规划“我们接下来应该做什么?”
决策推理链“关于 Redis 问题我们做了什么决定?”

从六个维度评分压缩效果

在以下维度上评估编码代理的压缩质量。准确性和工件追踪完整性通常比词汇相似度更能区分不同的方法(引用:context-compression-factory-benchmark),因此压缩需要超出通用摘要的专业处理。

  1. 准确性:技术细节是否正确——文件路径、函数名、错误代码?
  2. 上下文感知:响应是否反映了当前对话状态?
  3. 工件追踪:代理是否知道哪些文件被读取或修改?
  4. 完整性:响应是否解决了问题的所有部分?
  5. 连续性:是否可以继续工作而无需重新获取信息?
  6. 指令遵循:响应是否遵守了声明的约束?

实用指南

对大型代码库应用三阶段压缩工作流

对于超过上下文窗口的代码库或代理系统,通过三个顺序阶段进行压缩。每个阶段缩小上下文,使下一阶段能在预算内运行。

  1. 研究阶段:探索架构图、文档和关键接口。将探索内容压缩成组件、依赖项和边界的结构化分析。输出:单个研究文档,替代原始探索内容。

  2. 规划阶段:将研究文档转换为包含函数签名、类型定义和数据流的实现规范。一个500万令牌的代码库在此阶段大约可压缩为2000字的规范。

  3. 实现阶段:根据规范执行。上下文保持集中在规范加上当前工作文件上,而不是原始代码库探索。此阶段很少需要进一步压缩,因为规范已经很紧凑。

使用示例工件作为压缩种子

当提供了手动迁移示例或参考 PR 时,将其用作模板来理解目标模式,而不是从头开始探索代码库。该示例揭示了静态分析无法发现的约束:哪些不变量必须保持,哪些服务会因更改而中断,以及一个干净的实现是什么样的。

当代理无法区分本质复杂性(业务需求)和偶然复杂性(遗留变通方法)时,这一点最为重要。示例工件隐式编码了这种区分,节省了原本会用于试错探索的令牌。

逐步实施锚定迭代摘要

  1. 定义与代理领域(调试、迁移、功能开发)匹配的显式摘要部分
  2. 在第一次压缩触发时,将截断的历史记录摘要到这些部分
  3. 在后续压缩中,仅摘要新截断的内容——不要重新摘要现有摘要
  4. 将新信息合并到现有部分中,而不是重新生成它们,通过文件路径和决策标识进行去重
  5. 标记哪些信息来自哪个压缩周期——这可以在摘要漂移时进行调试

根据会话特征选择正确的方法

在以下情况下使用锚定迭代摘要:

  • 会话是长时间运行的(100+ 条消息)
  • 文件跟踪很重要(编码、调试)
  • 需要验证保留的信息

在以下情况下使用不透明压缩:

  • 需要最大令牌节省
  • 会话相对较短
  • 重新获取成本低(例如,无需访问文件系统)

在以下情况下使用再生式摘要:

  • 摘要的可解释性对于人工审查至关重要
  • 会话具有清晰的阶段边界
  • 每次压缩触发时都可以接受完整的上下文审查

按方法校准压缩率

方法压缩率质量得分权衡
锚定迭代98.6%3.70最佳质量,压缩率略低
再生式98.7%3.44质量好,压缩率中等
不透明99.3%3.35压缩率最高,质量有损失

将这些作为特定来源的基准数据,而非通用常数(引用:context-compression-factory-benchmark)。对于任何存在重新获取成本的任务,这种权衡通常有利于结构化方法。

示例

示例 1:调试会话压缩

原始上下文(89,000 令牌,178 条消息):

  • /api/auth/login 端点上的 401 错误
  • 通过身份验证控制器、中间件、会话存储进行跟踪
  • 发现过时的 Redis 连接
  • 修复了连接池,添加了重试逻辑
  • 14 个测试通过,2 个失败

压缩后的结构化摘要:

## 会话意图
尽管凭据有效,但调试 /api/auth/login 上的 401 未授权错误。

## 根因
会话存储中的 Redis 连接过时。JWT 生成正确,但无法持久化会话。

## 已修改的文件
- auth.controller.ts:无更改(只读)
- middleware/cors.ts:无更改(已检查)
- config/redis.ts:修复了连接池配置
- services/session.service.ts:为瞬时故障添加了重试逻辑
- tests/auth.test.ts:更新了模拟设置

## 测试状态
14 个通过,2 个失败(模拟设置问题)

## 后续步骤
1. 修复剩余的测试失败(模拟会话服务)
2. 运行完整的测试套件
3. 部署到暂存环境

示例 2:探针响应质量

压缩后,询问“原始错误是什么?”:

良好响应(结构化摘要):

“原始错误是从 /api/auth/login 端点返回的 401 未授权响应。用户凭据有效但收到此错误。根本原因是会话存储中的 Redis 连接过时。”

不良响应(激进压缩):

“我们正在调试一个身份验证问题。登录失败。我们修复了一些配置问题。”

结构化响应保留了端点、错误代码和根本原因。激进的响应丢失了所有技术细节。

指南

  1. 优化每个任务的令牌数,而非每个请求的令牌数
  2. 使用带有显式文件跟踪部分的结构化摘要
  3. 在上下文利用率达到 70-80% 时触发压缩
  4. 实施增量合并而非完全重新生成
  5. 使用基于探针的评估来测试压缩质量
  6. 如果文件跟踪至关重要,则单独跟踪工件追踪
  7. 接受略低的压缩率以获得更好的质量保留
  8. 将重新获取频率作为压缩质量信号进行监控

陷阱

  1. 切勿压缩工具

…(为翻译而截断)

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

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.

相关技能