Communityコーディング&開発github.com

コンテキスト最適化

このスキルは、コンテキストの効率を向上させるために使用します。コンテキスト予算の管理、観測マスキング、プレフィックスまたはKVキャッシュ戦略、分割、トークンコスト削減、検索範囲の制限、回答品質を低下させずに実効的なコンテキスト容量を拡大することを目的とします。

コンテキスト最適化 とは?

このスキルは、限られたコンテキストウィンドウの実効容量を戦略的に拡大するためのコンテキスト最適化手法を提供します。KVキャッシュ最適化、観測マスキング、圧縮、コンテキスト分割の4つの主要戦略を優先順位に従って適用することで、トークンコストやレイテンシを削減しつつ、回答品質を維持します。特に、ツール出力の観測マスキングは最も大きな容量改善をもたらす可能性があり、KVキャッシュ最適化は安定したプレフィックスが存在する場合に最も低コストな最適化です。このスキルは、コンテキスト予算やトークンコストがタスクの複雑さを制約する場合、観測マスキングが必要な場合、プレフィックスやKVキャッシュのヒット率向上が必要な場合、検索範囲の制限やコンテキスト分割が必要な場合に有効です。測定に基づいた最適化が重要であり、圧縮は50-70%のトークン削減、マスキングは60-80%の削減を目標とし、品質低下は5%未満に抑えるべきとされています。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

コンテキスト最適化テクニック

コンテキスト最適化は、戦略的な圧縮、マスキング、キャッシング、分割を通じて、限られたコンテキストウィンドウの実効容量を拡大します。効果的な最適化は、より大きなモデルやより長いウィンドウを必要とせずに、有用な容量を増加させます。ただし、測定の規律をもって適用された場合に限ります。以下のテクニックは、影響度とリスクの順に並べられています。

アクティブ化のタイミング

以下の場合にこのスキルをアクティブ化してください:

  • コンテキスト予算またはトークンコストがタスクの複雑さを制約している場合
  • 観測マスキングにより、冗長なツール出力を検索可能な参照に置き換えられる場合
  • プレフィックスまたはKVキャッシュのヒット率を改善する必要がある場合
  • 検索範囲の制限により、無関係なロード済みコンテキストを削減できる場合
  • コンテキスト分割により、複数のエージェント間で実効容量を拡大できる場合
  • マスキング、圧縮、分割のための予算トリガーが必要な場合

他のスキルが担当する隣接作業では、このスキルをアクティブ化しないでください:

  • アテンションやコンテキストウィンドウがこのように動作する理由を説明する場合:context-fundamentals。
  • 進行中の「途中で迷子」、ポイズニング、気晴らし、混乱、衝突を診断する場合:context-degradation。
  • 長い会話のための構造化された引き継ぎサマリーを設計する場合:context-compression。
  • 大きな出力、計画、ログをファイルとして保存する場合:filesystem-context。
  • モデル自身によるコンテキストの書き換えとその再プリフィルコストを扱う場合:self-managed-context。

コアコンセプト

以下の4つの主要戦略をこの優先順位で適用します:

  1. KVキャッシュ最適化 — プロンプト構造を再配置して安定化し、推論エンジンがキャッシュされたKey/Valueテンソルを再利用できるようにします。ランタイムがプレフィックスキャッシングをサポートしている場合、これは最も安価な最適化です。品質リスクが低く、即時のコストとレイテンシの節約になります。安定したプレフィックスが存在する場合、最初に適用してください。

  2. 観測マスキング — 冗長なツール出力を、その目的が果たされたらコンパクトな参照に置き換えます。ツール出力はエージェントの軌跡を支配するため(claim-context-optimization-tool-output-dominance)、マスキングはしばしば最大の容量改善をもたらします。元のコンテンツは、後続で必要になった場合に取得可能なままです。

  3. 圧縮 — コンテキスト利用率が70%を超えた場合、累積されたコンテキストを要約し、そのサマリーで再初期化します。これにより、ウィンドウの内容を蒸留し、タスクに重要な状態を保持します。圧縮は非可逆です—マスキングで価値の低いバルクをすでに除去した後に適用してください。

  4. コンテキスト分割 — 単一のウィンドウで問題全体を保持できない場合、孤立したコンテキストを持つサブエージェント間で作業を分割します。各サブエージェントは、そのサブタスクに焦点を当てたクリーンなコンテキストで動作します。調整のオーバーヘッドは現実的であるため、推定コンテキストがウィンドウ制限の60%を超えるタスクのために予約してください。

統治原則:コンテキストの質は量よりも重要です。すべての最適化は、シグナルを保持しながらノイズを低減します。最適化前に測定し、次に最適化の効果を測定してください。

詳細トピック

圧縮戦略

コンテキスト利用率が70%を超えたときに圧縮をトリガーします。現在のコンテキストを要約し、そのサマリーで再初期化します。これにより、ウィンドウの内容を高忠実度で蒸留し、最小限のパフォーマンス低下で継続を可能にします。まずツール出力(トークンの80%以上を消費)を圧縮し、次に古い会話ターン、最後に取得されたドキュメントを圧縮します。システムプロンプトは決して圧縮しないでください—モデルの動作をアンカーし、その削除は予測不可能な劣化を引き起こします。

メッセージタイプごとに異なる要素を保持します:

  • ツール出力: 主要な発見、メトリクス、エラーコード、結論を抽出します。冗長な生の出力、スタックトレース(デバッグが進行中でない限り)、定型ヘッダーを取り除きます。
  • 会話ターン: 決定、コミットメント、ユーザープリファレンス、コンテキストの変化を保持します。すでにキャプチャされた結論に至ったフィラー、挨拶、探索的なやり取りを取り除きます。
  • 取得されたドキュメント: アクティブなタスクに関連する主張、事実、データポイントを保持します。一度きりの推論目的に役立った裏付け証拠や詳細な説明を取り除きます。

50-70%のトークン削減を目標とし、品質低下は5%未満にします。圧縮が70%の削減を超える場合、重要な情報の損失がないかサマリーを監査してください—過度な圧縮は最も一般的な障害モードです。

観測マスキング

観測を、最近性と継続的な関連性に基づいて選択的にマスクします—一律ではありません。以下のルールを適用します:

  • 決してマスクしない: 現在のタスクに重要な観測、最新のターンの観測、アクティブな推論チェーンで使用されている観測、デバッグが進行中のエラー出力。
  • 3ターン後にマスク: キーポイントがすでに会話の流れに抽出されている冗長な出力を、コンパクトなリファレンスに置き換えます。[Obs:{ref_id} elided. Key: {summary}. Full content retrievable.]
  • 常に即座にマスク: 繰り返し/重複した出力、定型ヘッダーとフッター、会話の前半ですでに要約された出力。

マスキングは、マスクされた観測で60-80%の削減を達成し、品質への影響は2%未満に抑える必要があります。鍵は、取得可能性を維持することです—完全なコンテンツを外部に保存し、参照IDをコンテキスト内に保持することで、エージェントが必要に応じてオリジナルを要求できます。

KVキャッシュ最適化

安定したコンテンツがプレフィックスを占め、動的コンテンツが末尾に表示されるようにプロンプトを構成することで、プレフィックスキャッシュヒットを最大化します。KVキャッシュは、推論中に計算されたKeyおよびValueテンソルを保存します。連続するリクエストが同一のプレフィックスを共有する場合、キャッシュされたテンソルが再利用され、コストとレイテンシの両方を節約します。

すべてのプロンプトで次の順序を適用します:

  1. システムプロンプト(最も安定—セッション内で変更されない)
  2. ツール定義(リクエスト間で安定)
  3. 頻繁に再利用されるテンプレートとFew-shotの例
  4. 会話履歴(増加するが、以前のターンとプレフィックスを共有)
  5. 現在のクエリと動的コンテンツ(最も不安定—常に最後)

キャッシュ安定性のためにプロンプトを設計します:システムプロンプトからタイムスタンプ、セッションカウンター、リクエストIDを削除します。動的メタデータを個別のユーザーメッセージまたはツール結果に移動し、プレフィックスを壊さないようにします。プレフィックス内の単一の空白文字の変更でさえ、その変更より後方のキャッシュされたブロック全体を無効にします。以前の履歴に適用される圧縮やマスキングの編集も同じルールが適用されます。そのコストは後続のテキストであるため、そのような編集はバッチ化し、コンテキストの末尾近くに適用することを好みます。

安定したワークロードで70%以上のキャッシュヒット率を目標とします。大規模では、これは50%以上のコスト削減と40%以上のキャッシュトークンのレイテンシ削減に変換されます。

コンテキスト分割

単一のコンテキストが問題全体を保持できない場合、攻撃的な圧縮をトリガーすることなく、サブエージェント間で作業を分割します。各サブエージェントは、そのサブタスクのためのクリーンで焦点を絞ったコンテキストで動作し、構造化された結果をコーディネーターエージェントに返します。

推定タスクコンテキストがウィンドウ制限の60%を超える場合、分割を計画します。タスクを独立したサブタスクに分解し、各サブタスクをサブエージェントに割り当て、結果を集約します。すべてのパーティションが完了したことを検証し、互換性のある結果をマージし、集約された出力がまだ予算を超えている場合は要約を適用します。

このアプローチは関心の分離を達成します—詳細な検索コンテキストはサブエージェント内で分離されたまま、コーディネーターは統合に集中します。ただし、調整には実際のトークンコストがかかります。コーディネータープロンプト、結果の集約、エラー処理はすべてトークンを消費します。節約がこのオーバーヘッドを超える場合にのみ分割してください。

予算管理

セッション開始前に、コンテキストカテゴリ全体に明示的なトークン予算を割り当てます:システムプロンプト、ツール定義、取得されたドキュメント、メッセージ履歴、ツール出力、および予備バッファ(合計の5-10%)。予算に対する使用状況を継続的に監視し、いずれかのカテゴリが割り当てを超えた場合、または全体の利用率が70%を超えた場合に最適化をトリガーします。

定期的な最適化ではなく、トリガーベースの最適化を使用します。以下のシグナルを監視します:

  • トークン利用率が80%以上 — 圧縮をトリガー
  • アテンション劣化の兆候(繰り返し、指示の見落とし) — マスキング+圧縮をトリガー
  • 品質スコアがベースラインを下回る — 最適化前にコンテキスト構成を監査

実践的なガイダンス

最適化決定フレームワーク

コンテキストを支配するものに基づいて最適化テクニックを選択します:

コンテキスト構成最初のアクション2番目のアクション
ツール出力が支配的(>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} elided. Key: {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. トークン節約と品質保持のバランスを取る
  7. 本番スケールで最適化をテストする
  8. エッジケースに対してグレースフルデグラデーションを実装する

落とし穴

  1. 空白がKVキャッシュを壊す: プロンプトプレフィックス内の単一の空白文字や改行の変更でさえ、そのポイントより後方のKVキャッシュブロック全体を無効にします。システムプロンプトを不変の文字列として固定します—タイムスタンプ、バージョン番号、セッションIDをそれらに補間しないでください。デプロイメント間でプロンプトテンプレートをバイト単位で比較します。

  2. システムプロンプト内のタイムスタンプがキャッシュヒット率を壊す: システムプロンプトに Current date: {today} または同様の動的コンテンツを含めると、新しい日ごと(または時刻を使用する場合はリクエストごと)に完全なキャッシュミスを強制します。動的メタデータを安定したプレフィックスの後に追加されたユーザーメッセージまたは個別のツール結果に移動します。

  3. 圧力下での圧縮が重要な状態を失う: 圧縮を実行しているモデル自体がコンテキスト圧力下にある場合(利用率>85%)、その要約品質は低下します—タスク目標を省略し、ユーザーの制約を落とし、微妙な状態を平坦化します。90%以上ではなく、70-80%で圧縮をトリガーします。圧縮を遅く実行しなければならない場合は、要約するマテリアルのみを含むクリーンなコンテキストで別のモデル呼び出しを使用します。

  4. エラー出力のマスキングがデバッグループを壊す: 過度に攻撃的なマスキングは、エージェントが後続のターンで問題を診断して修正するために必要なエラーメッセージ、スタックトレース、障害の詳細を隠します。アクティブなデバッグ中(最後の3ターン以内にエラーがある場合)、問題が解決されるまで、エラー関連のすべての観測のマスキングを一時停止します。

  5. 分割のオーバーヘッドが節約を超える可能性がある: 各サブエージェントには独自のシステムプロンプト、ツール定義、調整メッセージが必要です。3つ未満の独立したサブタスクがあるタスクの場合、調整のオーバーヘッドがコンテキストの節約を超えることがよくあります。分割をコミットする前に、総トークン数(コーディネーター+すべてのサブエージェント)を見積もります。

  6. デプロイメント変更後のキャッシュミスコストのスパイク: ツールの再順序付け、システムプロンプトの言い換え、デプロイメント間でのFew-shotの例の変更は、プレフィックスキャッシュ全体を無効にし、新しいキャッシュがウォームアップするまで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.

関連スキル