Community编程与开发github.com

上下文基础

此技能用于解释或推理上下文工程的基础概念:什么是上下文、上下文窗口的构成、注意力机制的工作原理、U形注意力曲线、为什么上下文质量比数量更重要,以及解读所有其他上下文工程决策所需的思维模型。适用于概念解释、新手上路和背景阅读。将操作任务分配给专门的技能:调试注意力失败请使用“上下文退化”,令牌效率工作请使用“上下文优化”,对话摘要请使用“上下文压缩”,项目形态决策请使用“项目开发”。

上下文基础 是什么?

此技能提供了上下文工程的基础概念框架,适用于所有AI代理和LLM应用平台(如Claude Code、Cursor、Codex等)。它解释了上下文的完整定义(包括系统指令、工具定义、检索文档、消息历史和工具输出),以及如何将其视为有限的注意力预算而非存储空间。核心内容包括:内在于长上下文中的U形注意力曲线(中间位置信息恢复可靠性较低)、注意力机制随n²计算增长而退化、有效容量通常低于标语窗口大小,以及“信息性优于穷举性”、“位置感知放置”、“渐进式披露”和“迭代策展”四项关键原则。该技能强调通过应用信号密度测试(评估移除某段内容是否会改变模型输出)来提升上下文质量而非数量,并鼓励在达到70-80%利用率时实施压缩触发。它明确将所有操作任务委托给专门的技能,保持对基础理解的关注。

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

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

在你喜欢的 AI 中提问

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

文档

上下文工程基础

上下文是推理时语言模型可用的完整状态:系统指令、工具定义、检索文档、消息历史和工具输出。上下文工程是一种训练有素的方法,用于策展最小的高信号令牌集合,以最大化期望结果的可能性。

此技能是本集合中所有其他技能构建的概念基础。它解释了什么是上下文、注意力机制如何工作、为什么上下文质量比数量更重要,以及解读所有其他上下文工程决策所需的思维模型。它不拥有操作任务:调试注意力失败属于context-degradation,令牌效率策略属于context-optimization,对话摘要属于context-compression,基于文件的卸载属于filesystem-context,项目形态决策属于project-development。

何时激活

在工作属于概念性时激活此技能:

  • 解释什么是上下文以及注意力机制如何约束代理行为。
  • 培训新贡献者,他们需要在深入操作技能之前掌握思维模型。
  • 从第一性原理推理与上下文相关的设计决策(此约束意味着什么,为什么存在此权衡),然后再选择特定策略。
  • 编写或审查需要将操作指南植根于底层机制的文档。

不要为操作任务激活此技能。专门的技能处理具体实施:

  • 诊断“中间丢失”、上下文中毒或注意力失败:context-degradation。
  • 通过掩码、分区、前缀缓存、预算等方式减少令牌成本:context-optimization。
  • 将长会话压缩为交接摘要:context-compression。
  • 卸载大型工具输出或维护持久记事板:filesystem-context。
  • 决定LLM项目或管道的形态:project-development。

核心概念

将上下文视为有限的注意力预算,而不是存储箱。添加的每个令牌都在争夺模型的注意力,并消耗一个在推理过程中无法补充的预算。工程问题是在三个约束下最大化每个令牌的效用:硬令牌限制、较软的有效容量上限,以及惩罚放置在上下文中间信息的U形注意力曲线(claim-context-degradation-lost-middle-ruler)。

在组装上下文时应用四项原则:

  1. 信息性优于穷举性 — 只包含对当前决策重要的内容;设计能够按需检索额外信息的系统。
  2. 位置感知放置 — 将关键约束放在上下文的开头和结尾,因为长上下文评估显示中间位置的信息不如边缘位置的信息可靠(claim-context-degradation-lost-middle-ruler)。
  3. 渐进式披露 — 在启动时加载技能名称和摘要;仅在技能为特定任务激活时才加载完整内容。
  4. 迭代策展 — 上下文工程不是一次性的提示编写练习,而是每次将内容传递给模型时持续应用的纪律。

详细主题

上下文的构成

系统提示 使用XML标签或Markdown标题将系统提示组织成不同的部分(背景、指令、工具指南、输出格式)。系统提示在对话中持续存在,因此将最关键的约束放在开头和结尾,那里注意力最强。

校准指令高度以平衡两种失败模式。高度太低会固化脆弱的逻辑,当条件变化时会崩溃。高度太高会提供模糊的指导,无法为期望行为提供具体信号。目标是指南驱动的指令:具体到足以指导行为,灵活到足以泛化 —— 例如,带有步骤编号的步骤列表,每个步骤都有判断空间。

从最小值开始,然后根据观察到的失败模式被动添加指令,而不是预先塞入边缘情况。策展多样化、规范的少量样本示例,描述期望的行为,而不是列出每个可能的场景。

工具定义 编写回答三个问题的工具描述:该工具做什么、何时使用它以及它返回什么。包括使用上下文、参数默认值和错误情况 —— 代理无法区分人类工程师也无法区分的工具。

保持工具集最小。合并重叠的工具,因为臃肿的工具集创建模糊的决策点,并在JSON序列化后消耗不成比例的上下文(与等效的纯文本描述相比,工具模式通常膨胀2-3倍)。

检索文档 维护轻量级标识符(文件路径、存储的查询、Web链接),并使用即时检索动态将数据加载到上下文中。这反映了人类认知 —— 维护索引,而不是副本。强标识符(例如customer_pricing_rates.json)使代理即使没有搜索工具也能找到相关文件;弱标识符(例如data/file1.json)会强制不必要的加载。

在分块大型文档时,在自然语义边界(章节标题、段落分隔符)处拆分,而不是在会切断中间概念的任意字符限制处拆分。

消息历史 消息历史充当代理的记事板内存,用于跨轮次跟踪进度、维护任务状态和保留推理。对于长时间运行的任务,它可能会增长到主导上下文使用 —— 在它挤占活动指令之前监控并应用压缩。

循环精炼历史:一旦工具在对话深处被调用,原始结果很少需要逐字保留。用紧凑的摘要或引用替换陈旧的工具输出,以减少低信号体积。

工具输出 工具输出通常在代理轨迹中主导上下文(claim-context-optimization-tool-output-dominance)。应用观察掩码:一旦代理处理了结果,就用紧凑的引用替换冗长的输出。仅保留最近相关的文件内容;压缩或驱逐较旧的内容。

上下文窗口和注意力机制

注意力预算 对于n个令牌,注意力机制计算n的平方个成对关系。随着上下文增长,模型维护这些关系的能力会退化 —— 不是作为硬性悬崖,而是作为性能梯度。主要在较短序列上训练的模型具有较少的用于上下文范围依赖关系的专门参数,从而在名义窗口大小以下创建一个有效容量上限。

为此梯度设计:假设有效容量在目标工作负载上测量之前,实质性低于广告窗口。大的名义上下文窗口不会消除任务特定退化测试的必要性(claim-context-degradation-lost-middle-ruler)。

位置编码限制 位置编码插值扩展了超出训练长度的序列处理,但在位置精度方面引入了退化。与较短输入的性能相比,期望在扩展上下文中的信息检索和长程推理准确度降低。

实践中的渐进式披露 在三个层次实施渐进式披露:

  1. 技能选择 — 在启动时仅加载名称和描述;按需激活完整技能内容。
  2. 文档加载 — 首先加载摘要;仅当任务需要时才获取详细章节。
  3. 工具结果保留 — 保留最近的完整结果;压缩或驱逐较旧的结果。

保持边界清晰:如果技能或文档被激活,则完全加载而非部分加载 —— 部分加载会创建混乱的间隙,降低推理质量。

上下文质量与数量

拒绝“更大的上下文窗口解决内存问题”的假设。处理成本随上下文长度不成比例地增长 —— 不仅是线性成本扩展,而且超出有效容量阈值时模型性能退化。即使使用前缀缓存,长输入仍然昂贵。

应用信号密度测试:对于上下文的每个部分,问“移除它是否会改变模型的输出”。如果不会,就移除它。冗余内容不仅浪费令牌 —— 它还会主动从高信号内容中稀释注意力。

实用指南

本节提供概念应用建议。指向操作技能的指针是显式的。

推理上下文决策

当需要做出与上下文相关的设计决策时,将概念性问题与操作性问题分开。概念性问题是“这意味着什么以及为什么重要”;操作性问题是“我们应用什么具体技术”。使用此技能回答前者;将后者路由到拥有它的专门技能。

例如,决定是否摘要长代理会话有两个部分:(1) 为什么需要摘要(注意力预算有限,U形曲线降低中间内容,信号密度比数量更重要 - 此技能)以及 (2) 什么压缩策略保留正确的状态以及在什么利用率阈值触发它(context-compression)。

新贡献者的阅读顺序

首次接触上下文工程的贡献者应按以下顺序阅读:

  1. 此技能,以内化注意力预算框架和U形曲线。
  2. context-degradation,以了解上下文失败在实践中看起来像什么以及如何诊断它们。
  3. 根据情况选择两个或三个 context-optimization、context-compression、filesystem-context、memory-systems,取决于哪个操作关注点与其项目最相关。

跳过步骤1会产生应用技术而不理解原因的操作者;跳过操作技能会产生不知道哪种技术适合哪种失败模式的理论家。

示例

示例1:组织系统提示

说明了关键约束应放在注意力偏好的位置(开头和结尾),以及显式章节边界有助于模型解析提示的概念点:

<BACKGROUND_INFORMATION>
您是一位帮助开发团队的Python专家。
当前项目:Python 3.9+中的数据管道
</BACKGROUND_INFORMATION>

<INSTRUCTIONS>
- 编写清晰、惯用的Python代码
- 包括函数签名的类型提示
- 为公共函数添加文档字符串
- 遵循PEP 8风格指南
</INSTRUCTIONS>

<OUTPUT_DESCRIPTION>
提供带有语法高亮的代码块。
在注释中解释非显而易见的决策。
</OUTPUT_DESCRIPTION>

示例2:注意力预算作为思维模型

一个长上下文模型并没有同等关注的上下文。有效容量是工作负载特定的,U形曲线惩罚放置在中间位置的信息。在决定加载多少上游知识库时,这是思维模型:不要问“能否装下”,问“模型是否仍会关注重要的部分”。

相应的操作问题(哪种技术应该减少加载)属于context-optimization。

指南

  1. 将上下文视为具有递减收益的有限资源
  2. 将关键信息放在注意力偏好的位置(开头和结尾)
  3. 使用渐进式披露推迟加载直到需要
  4. 用清晰的章节边界组织系统提示
  5. 在开发期间监控上下文使用情况
  6. 在70-80%利用率时实施压缩触发
  7. 设计以适应上下文退化,而不是希望避免它
  8. 偏好较小的高信号上下文而不是较大的低信号上下文

注意事项

  1. 名义窗口不是有效容量:声称具有大上下文窗口的模型可能在复杂检索或推理任务上远在该限制之前就退化。在您自己的退化测试证明之前,预算低于名义窗口。

  2. 基于字符的令牌估算会悄悄漂移:英文散文约4个字符/令牌的启发式在代码(2-3字符/令牌)、URL和文件路径(每个斜杠、点和冒号是单独的令牌)以及非英文文本(通常1-2字符/令牌)上会失效。对于任何预算关键计算,使用提供者的实际分词器(例如OpenAI模型的tiktoken,Anthropic的令牌计数API)。

  3. 工具模式在JSON序列化后膨胀2-3倍:在源代码中看起来紧凑的工具定义在序列化时会显著扩展 —— 方括号、引号、冒号和逗号每个都消耗令牌。十个中等模式的工具在发送第一条消息之前可以消耗5,000-8,000个令牌。审计序列化工具的令牌计数,而不是源代码行计数。

  4. 消息历史在代理循环中悄悄膨胀:每个工具调用都会向历史记录添加请求和完整响应。经过20-30次迭代,历史记录可以消耗窗口的70-80%,而代理直到推理质量崩溃才显示可见症状。在历史上设置硬令牌上限,并主动触发压缩。

  5. 中间位置的关键指令会丢失:U形注意力曲线意味着上下文的中间位置比开头和结尾的召回准确度低10-40%。永远不要将安全约束、输出格式要求或行为护栏放在长系统提示的中间 —— 将它们锚定在顶部或底部。

  6. 过于急切加载的渐进式披露会适得其反:在第一次暗示相关性时加载每个“可能相关”的技能或文档会重新创建上下文填充问题。设置严格的激活阈值 —— 技能仅在任务明确匹配其触发条件时才应加载,而不是在主题仅仅相邻时。

  7. 混合指令高度会导致不一致的行为:将超具体规则(“始终恰好使用3个要点”)与模糊愿景陈述(“为简单性优化”)结合会创建冲突的信号。保持指令组内的高度一致,并在需要不同高度时使用清晰的章节边界。

  8. 冗余内容稀释注意力:重复指令、重叠工具定义或相同示例的多个变体不会强化消息;它们通过将注意力预算分散到重复令牌上来稀释所有内容。每个令牌应提供唯一的信号。

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

相关技能