Community程式設計與開發github.com

基礎脈絡工程

用於解釋或推理脈絡工程的基本概念:什麼是脈絡、脈絡視窗的結構、注意力機制如何運作、U型注意力曲線、為何脈絡品質比數量更重要,以及解讀其他脈絡工程決策所需的心智模型。適用於概念說明、入門引導和背景閱讀。

基礎脈絡工程 是什麼?

此技能為脈絡工程的概念基礎,說明什麼是脈絡、注意力機制如何運作、為何脈絡品質重於數量,以及解讀其他脈絡工程決策所需的心智模型。它將脈絡視為有限的注意力預算,而非儲存空間,並強調基於位置感知的放置、漸進式揭露與疊代篩選等原則。此技能專注於概念性工作,例如解釋脈絡如何影響LLM行為、入門引導新貢獻者,以及從基本原理推理脈絡設計決策。操作任務(如調試注意力失敗、降低token成本、壓縮對話)則應導向專門技能,如context-degradation、context-optimization與context-compression。支援的平台包括Claude Code、Cursor與Codex等代理開發工具,提供結構化的Markdown指南,涵蓋系統提示、工具定義、檢索文件與訊息歷史等主題。

相容平台✓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 的新對話。

說明文件

脈絡工程基礎

脈絡是指在推論時間提供給語言模型的完整狀態:系統提示、工具定義、檢索文件、訊息歷史與工具輸出。脈絡工程是一門學科,致力於策劃最小的高訊號 token 集合,以最大化期望結果的可能性。

此技能是集合中所有其他技能的基礎概念。它解釋了什麼是脈絡、注意力機制如何運作、為何脈絡品質比數量更重要,以及解讀其他脈絡工程決策所需的心智模型。它不擁有操作工作:調試注意力失敗屬於 context-degradation,token 效率策略屬於 context-optimization,對話摘要屬於 context-compression,基於檔案的卸載屬於 filesystem-context,專案形狀決策屬於 project-development。

啟動時機

當工作屬於概念性質時啟動此技能:

  • 解釋什麼是脈絡以及注意力機制如何限制代理行為。
  • 入門引導需要先建立心智模型才能深入操作技能的新貢獻者。
  • 從基本原理推理脈絡相關設計決策(此約束意味著什麼?為何存在此取捨?),然後再選擇特定策略。
  • 撰寫或審閱需要以底層機制為基礎的操作指南文件。

不要將此技能用於操作工作。專業技能負責執行部分:

  • 診斷 Lost-in-the-Middle、脈絡毒化或注意力失敗:context-degradation。
  • 透過遮罩、分割、前綴快取、預算降低 token 成本:context-optimization。
  • 將長對話壓縮成交接摘要:context-compression。
  • 卸載大型工具輸出或維護持久化暫存空間:filesystem-context。
  • 決定 LLM 專案或管線的形狀:project-development。

核心概念

將脈絡視為有限的注意力預算,而非儲存空間。新增的每個 token 都會競爭模型的注意力,並耗盡無法在推論過程中補充的預算。工程問題在於最大化每個 token 的效用,同時面對三個約束:硬性的 token 限制、較軟的有效容量上限,以及懲罰放在脈絡中間資訊的 U 型注意力曲線 (claim-context-degradation-lost-middle-ruler)。

組合脈絡時應用四項原則:

  1. 資訊性重於詳盡性 — 只包含對當前決策重要的資訊;設計能夠按需檢索額外資訊的系統。
  2. 位置感知放置 — 將關鍵約束放在脈絡的開頭和結尾,因為長脈絡評估顯示中間位置的資訊比邊緣位置的資訊更難可靠恢復 (claim-context-degradation-lost-middle-ruler)。
  3. 漸進式揭露 — 啟動時僅載入技能名稱與摘要;僅當技能為特定任務啟用時才載入完整內容。
  4. 疊代篩選 — 脈絡工程不是一次性的提示撰寫練習,而是在每次將內容傳遞給模型時都應持續應用的學科。

詳細主題

脈絡的結構

系統提示 使用 XML 標籤或 Markdown 標題將系統提示組織成不同的部分(背景、指令、工具指引、輸出格式)。系統提示在對話中持續存在,因此將最關鍵的約束放在注意力最強的開頭和結尾。

校準指令高度以平衡兩種失敗模式。高度過低會將脆弱的邏輯硬編碼,當條件改變時便會失效。高度過高則提供模糊的指引,無法為期望行為提供具體訊號。目標是提供啟發式驅動的指令:具體到足以引導行為,又靈活到足以泛化——例如編號步驟,每一步都留有判斷空間。

先從最小配置開始,然後根據觀察到的失敗模式被動添加指令,而不是預先堆疊所有邊界情況。策劃多樣化且經典的少量樣本,展示期望行為,而不是列出每個可能場景。

工具定義 撰寫回答三個問題的工具描述:此工具做什麼、何時使用、以及返回什麼。包含使用脈絡、參數預設值和錯誤情況——一個人類工程師無法區分的工具,代理也無法區分。

保持工具集合最小化。合併重疊的工具,因為臃腫的工具集合會造成模糊的決策點,並在 JSON 序列化後消耗不成比例的脈絡(工具架構通常比等效的純文字描述膨脹 2-3 倍)。

檢索文件 維護輕量級識別符(檔案路徑、儲存查詢、網頁連結)並使用即時檢索將資料動態載入脈絡。這模仿了人類認知——維護索引,而非副本。強識別符(例如 customer_pricing_rates.json)讓代理即使沒有搜尋工具也能定位相關檔案;弱識別符(例如 data/file1.json)會強制進行不必要的載入。

在分割大型文件時,應在自然的語義邊界(章節標題、段落分隔)處進行,而不是在任意的字元限制處切斷概念。

訊息歷史 訊息歷史作為代理的暫存記憶,用於追蹤進度、維護任務狀態以及在多輪對話中保留推理過程。對於長期運行的任務,它可能增長到佔據脈絡使用的主導地位——監控並在其擠壓活躍指令之前應用壓縮。

循環地精煉歷史:一旦工具在對話後期被調用,原始結果通常無需逐字保留。將過時的冗長工具輸出替換為簡潔摘要或引用,以減少低訊號的資訊量。

工具輸出 在代理軌跡中,工具輸出通常佔據脈絡的主導地位 (claim-context-optimization-tool-output-dominance)。應用觀察遮罩:一旦代理處理完結果,將冗長輸出替換為簡潔引用。只保留最近相關的檔案內容;壓縮或捨棄較舊的內容。

脈絡視窗與注意力機制

注意力預算 對於 n 個 token,注意力機制會計算 n 的平方成對關係。隨著脈絡增長,模型維持這些關係的能力會下降——不是硬性懸崖,而是效能梯度。主要在較短序列上訓練的模型,用於脈絡範圍依賴關係的專門參數較少,這會形成遠低於名義視窗大小的有效容量上限。

針對此梯度進行設計:假設在目標工作負載上衡量之前,有效容量遠低於廣告中的視窗大小。大的名義脈絡視窗並不能消除進行特定任務退化測試的必要性 (claim-context-degradation-lost-middle-ruler)。

位置編碼限制 位置編碼插值擴展了超出訓練長度的序列處理能力,但會導致位置精確度退化。與較短輸入上的效能相比,在擴展脈絡上進行資訊檢索和長程推理時,精度會降低。

實務中的漸進式揭露 在三個層級實施漸進式揭露:

  1. 技能選擇 — 啟動時僅載入名稱和描述;按需啟用完整技能內容。
  2. 文件載入 — 首先載入摘要;僅當任務需要時才提取詳細章節。
  3. 工具結果保留 — 完整保留近期結果;壓縮或捨棄較舊的結果。

保持邊界清晰:如果技能或文件被啟用,應完整載入而非部分載入——部分載入會造成令人困惑的資訊缺口,降低推理品質。

脈絡品質 vs 數量

拒絕接受較大的脈絡視窗能解決記憶問題的假設。處理成本隨著脈絡長度不成比例地增長——不僅是線性成本擴展,還有超出有效容量閾值後的模型效能退化。即使使用前綴快取,長輸入仍然成本高昂。

應用訊號密度測試:對於每一段脈絡,問問如果移除它是否會改變模型的輸出。如果不會,就移除它。冗餘內容不僅浪費 token,還會積極稀釋對高訊號內容的注意力。

實務指引

本節提供概念性的應用建議。對操作技能的明確指引已標示。

推理脈絡決策

當需要做出與脈絡相關的設計決策時,將概念性問題與操作性問題分開。概念性問題是「這意味著什麼,為什麼重要」;操作性問題是「我們應用哪種特定技術」。使用此技能來回答前者;將後者導向擁有該技術的專門技能。

例如,決定是否要摘要一個長代理對話包含兩部分:(1)為何需要摘要(注意力預算有限,U 型曲線使中間內容退化,訊號密度比數量更重要——此技能)以及(2)哪種壓縮策略能保留正確狀態,以及在何種利用率閾值下觸發它 (context-compression)。

新貢獻者的閱讀順序

初次接觸脈絡工程的貢獻者應依序閱讀:

  1. 此技能,以內化注意力預算框架和 U 型曲線。
  2. context-degradation,了解脈絡失敗在實踐中如何展現以及如何診斷。
  3. context-optimization、context-compression、filesystem-context、memory-systems 中的兩到三個,取決於哪個操作問題與其專案最相關。

跳過第一步會產生應用技術卻不理解原因的執行者;跳過操作技能則會產生不知哪種技術適合哪種失敗模式的理論家。

範例

範例 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. 基於字元的 token 估計會悄然漂移:英文散文約 4 個字元/token 的啟發式規則,對於程式碼(2-3 個字元/token)、URL 和檔案路徑(每個斜線、點、冒號都是一個單獨 token)以及非英文文字(通常 1-2 個字元/token)會失效。對於任何預算關鍵的計算,請使用提供者的實際 tokenizer(例如 OpenAI 模型的 tiktoken、Anthropic 的 token 計數 API)。

  3. 工具架構在 JSON 序列化後膨脹 2-3 倍:在原始碼中看起來緊湊的工具定義,序列化後會顯著擴展——括號、引號、冒號和逗號分別消耗 token。在發送單一訊息之前,十個具有中等架構的工具可能消耗 5,000-8,000 個 token。請審計序列化後的 token 數量,而不是原始碼行數。

  4. 訊息歷史在代理迴圈中悄然膨脹:每次工具調用都會將請求和完整回應都加入歷史。經過 20-30 次迭代後,歷史可能佔據視窗的 70-80%,而代理在推理品質崩潰之前不會顯示出明顯症狀。設定歷史的硬性 token 上限,並主動觸發壓縮。

  5. 中間的關鍵指令會遺失:U 型注意力曲線意味著脈絡中間部分的回憶準確度比開頭和結尾低 10-40%。切勿將安全約束、輸出格式要求或行為防護欄放在長系統提示的中間——將它們錨定在頂部或底部。

  6. 過於急切載入的漸進式揭露會適得其反:在第一次出現相關性提示時就載入每個「可能相關」的技能或文件,會重新產生脈絡填充問題。設定嚴格的啟動閾值——技能僅應在任務明確符合其觸發條件時載入,而不僅僅是主題相近。

  7. 混合不同高度的指令會導致行為不一致:將超具體規則(「總是恰好使用 3 個要點」)與模糊目標(「表現得有用」)結合,會在代理行為中產生隨機的切換點。將微觀行為約束清單放在頂部的專用區段中;將策略目標放在底部的單獨區段中。

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.

相關技能