context-optimization
Что он делает
Этот скилл показывает, как вместить больше полезной работы в ограниченное контекстное окно: например, скрывать громоздкий вывод инструментов, переиспользовать кешируемые начала промптов и делить работу между агентами. Он нужен командам, которые хотят снизить расходы на ИИ или выполнять более крупные задачи.
Когда использовать
- ✓Когда задача выходит за пределы контекста или стоит слишком много токенов.
- ✓Когда длинный вывод инструментов заполняет контекст деталями, которые агенту почти не нужны.
- ✓Когда вы хотите переиспользовать кешированные части промпта, чтобы сократить повторные расходы.
Ссылка на скилл
https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/blob/main/skills/context-optimization/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Мои агенты выводят слишком много данных инструментов, и контекст быстро заполняется. Покажи, как держать разговор компактным без потери качества.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Скилл ранжирует приёмы по эффекту и риску, например маскировка выводов, кеширование начала промптов и разделение работы, и советует измерять каждое изменение.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Context Optimization Techniques
Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. Effective optimization increases useful capacity without requiring larger models or longer windows — but only when applied with measurement discipline. The techniques below are ordered by impact and risk.
When to Activate
Activate this skill when:
- Context budgets or token costs constrain task complexity
- Observation masking can replace verbose tool outputs with retrievable references
- Prefix or KV-cache hit rate needs improvement
- Retrieval scoping can reduce irrelevant loaded context
- Context partitioning can extend effective capacity across agents
- Budget triggers are needed for masking, compaction, or partitioning
Do not activate this skill for adjacent work owned by other skills:
- Explaining why attention or context windows behave this way:
context-fundamentals. - Diagnosing active lost-in-middle, poisoning, distraction, confusion, or clash:
context-degradation. - Designing a structured handoff summary for a long conversation:
context-compression. - Storing large outputs, plans, or logs as files:
filesystem-context. - Model-initiated rewrites of its own context and their re-prefill cost:
self-managed-context.
Core Concepts
Apply four primary strategies in this priority order:
KV-cache optimization — Reorder and stabilize prompt structure so the inference engine reuses cached Key/Value tensors. This is the cheapest optimization when the runtime supports prefix caching: low quality risk, immediate cost and latency savings. Apply it first when stable prefixes exist.
Observation masking — Replace verbose tool outputs with compact references once their purpose has been served. Tool outputs can dominate agent trajectories (claim-context-optimization-tool-output-dominance), so masking often yields the largest capacity gains. The original content remains retrievable if needed downstream.
Compaction — Summarize accumulated context when utilization exceeds 70%, then reinitialize with the summary. This distills the window's contents while preserving task-critical state. Compaction is lossy — apply it after masking has already removed the low-value bulk.
Context partitioning — Split work across sub-agents with isolated contexts when a single window cannot hold the full problem. Each sub-agent operates in a clean context focused on its subtask. Reserve this for tasks where estimated context exceeds 60% of the window limit, because coordination overhead is real.
The governing principle: context quality matters more than quantity. Every optimization preserves signal while reducing noise. Measure before optimizing, then measure the optimization's effect.
Detailed Topics
Compaction Strategies
Trigger compaction when context utilization exceeds 70%: summarize the current context, then reinitialize with the summary. This distills the window's contents in a high-fidelity manner, enabling continuation with minimal performance degradation. Prioritize compressing tool outputs first (they consume 80%+ of tokens), then old conversation turns, then retrieved documents. Never compress the system prompt — it anchors model behavior and its removal causes unpredictable degradation.
Preserve different elements by message type:
- Tool outputs: Extract key findings, metrics, error codes, and conclusions. Strip verbose raw output, stack traces (unless debugging is ongoing), and boilerplate headers.
- Conversational turns: Retain decisions, commitments, user preferences, and context shifts. Remove filler, pleasantries, and exploratory back-and-forth that led to a conclusion already captured.
- Retrieved documents: Keep claims, facts, and data points relevant to the active task. Remove supporting evidence and elaboration that served a one-time reasoning purpose.
Target 50-70% token reduction with less than 5% quality degradation. If compaction exceeds 70% reduction, audit the summary for critical information loss — over-aggressive compaction is the most common failure mode.
Observation Masking
Mask observations selectively based on recency and ongoing relevance — not uniformly. Apply these rules:
- Never mask: Observations critical to the current task, observations from the most recent turn, observations used in active reasoning chains, and error outputs when debugging is in
Частые вопросы
Что такое маскировка наблюдений?
Она заменяет длинные выводы инструментов короткими ссылками, по которым агент при необходимости может снова открыть полный текст.
Что такое префиксное кеширование?
Оно переиспользует неизменяемое начало промпта, чтобы модель не обрабатывала его заново каждый раз.
Снижает ли это качество ответов?
Скилл советует измерять каждое изменение, и приём сохраняется, только если ответы остаются хорошими.
Подробности
Оригинальное описание автора
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.
Популярность
- Звёзды на GitHub
- 18k
- Место в рейтинге
- #10640
- Лицензия
- MIT
- Обновлён
- 11.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
context-engineering-collection
18kПомогает агенту управлять тем, что попадает в контекстное окно ИИ-модели: от памяти и инструментов до систем из нескольких агентов и оценки.
advanced-evaluation
18kУчит агента оценивать ответы ИИ с помощью другого ИИ: с баллами, попарным сравнением и проверкой на смещение.
bdi-mental-states
18kУчит агента моделировать убеждения, цели и планы по подходу BDI, чтобы его решения можно было проследить и объяснить.
context-compression
18kПомогает агенту сокращать длинные ИИ-сессии до сводок, которые сохраняют решения, файлы, риски и следующие шаги.
Похожие скиллы
add-model-provider
394kПомогает агенту подключить нового провайдера ИИ-моделей к OpenClaw безопасными командами, хранить ключи API не в открытом виде и провести живой тест.
acp-router
394kПомогает агенту передать задачу инструменту для программирования, например Claude Code или Cursor, через OpenClaw, чтобы работа шла в этом инструменте.
browser-automation
394kУчит агента пошагово управлять веб-страницами: входить в аккаунты, работать с вкладками и восстанавливаться, если страница перестала отвечать.