context-optimization
Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. The goal is not to magically increase context windows but to make better use of available capacity.
About this skill
Context optimization is a meta-skill that allows AI agents to significantly extend their effective processing capacity within limited context windows. Instead of magically increasing token limits, it employs sophisticated techniques like strategic data compression, intelligent masking of irrelevant information, efficient caching of frequently accessed data, and partitioning of large inputs. This enables the AI to make better use of its available context, effectively doubling or tripling its capacity for relevant information without requiring larger models or longer raw contexts. It's crucial for managing complex, data-rich tasks where raw token limits would otherwise be a major constraint.
Best use case
An AI agent needs to process, analyze, or synthesize information from datasets or documents that exceed its direct context window. This skill allows the agent to intelligently manage and prioritize information to complete tasks that require a broader scope of understanding or recall.
Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. The goal is not to magically increase context windows but to make better use of available capacity.
The AI agent successfully handles complex, data-intensive tasks that would typically exceed its context window. This leads to more robust performance, more comprehensive analysis, reduced token usage, and the ability to maintain a consistent understanding across extended interactions.
Practical example
Example input
An AI agent is tasked with summarizing a 100-page research paper, cross-referencing findings with a user's previous 50-page project proposal, and providing a concise executive summary, all while operating under a 100k token context window. The agent internally applies context optimization to manage the voluminous input.
Example output
The AI agent successfully processes both the research paper and the project proposal, intelligently prioritizing and compressing information using context optimization techniques. It delivers an accurate and relevant executive summary, demonstrating an effective context capacity far exceeding the raw token limit for this specific task, without encountering 'context window exceeded' errors.
When to use this skill
- Activate this skill when: - Context limits constrain the AI's ability to process necessary information for a task. - The AI needs to analyze lengthy documents, large codebases, or extensive chat histories. - There's a need to reduce token usage and associated costs for complex, data-intensive operations. - The agent must maintain a broader understanding or recall across multiple interactions or data sources.
When not to use this skill
- Do not activate this skill when: - The task is simple and fits comfortably within the AI's standard context window. - High-fidelity, uncompressed access to every single detail of the input is absolutely critical and cannot be intelligently summarized or masked. - The overhead of applying optimization techniques outweighs the benefits for very short, straightforward interactions.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/context-optimization/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How context-optimization Compares
| Feature / Agent | context-optimization | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. The goal is not to magically increase context windows but to make better use of available capacity.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
Top AI Agents for Productivity
See the top AI agent skills for productivity, workflow automation, operational systems, documentation, and everyday task execution.
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
SKILL.md Source
# Context Optimization Techniques
Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. The goal is not to magically increase context windows but to make better use of available capacity. Effective optimization can double or triple effective context capacity without requiring larger models or longer contexts.
## When to Use
Activate this skill when:
- Context limits constrain task complexity
- Optimizing for cost reduction (fewer tokens = lower costs)
- Reducing latency for long conversations
- Implementing long-running agent systems
- Needing to handle larger documents or conversations
- Building production systems at scale
## Core Concepts
Context optimization extends effective capacity through four primary strategies: compaction (summarizing context near limits), observation masking (replacing verbose outputs with references), KV-cache optimization (reusing cached computations), and context partitioning (splitting work across isolated contexts).
The key insight is that context quality matters more than quantity. Optimization preserves signal while reducing noise. The art lies in selecting what to keep versus what to discard, and when to apply each technique.
## Detailed Topics
### Compaction Strategies
**What is Compaction**
Compaction is the practice of summarizing context contents when approaching limits, then reinitializing a new context window with the summary. This distills the contents of a context window in a high-fidelity manner, enabling the agent to continue with minimal performance degradation.
Compaction typically serves as the first lever in context optimization. The art lies in selecting what to keep versus what to discard.
**Compaction Implementation**
Compaction works by identifying sections that can be compressed, generating summaries that capture essential points, and replacing full content with summaries. Priority for compression goes to tool outputs (replace with summaries), old turns (summarize early conversation), retrieved docs (summarize if recent versions exist), and never compress system prompt.
**Summary Generation**
Effective summaries preserve different elements depending on message type:
Tool outputs: Preserve key findings, metrics, and conclusions. Remove verbose raw output.
Conversational turns: Preserve key decisions, commitments, and context shifts. Remove filler and back-and-forth.
Retrieved documents: Preserve key facts and claims. Remove supporting evidence and elaboration.
### Observation Masking
**The Observation Problem**
Tool outputs can comprise 80%+ of token usage in agent trajectories. Much of this is verbose output that has already served its purpose. Once an agent has used a tool output to make a decision, keeping the full output provides diminishing value while consuming significant context.
Observation masking replaces verbose tool outputs with compact references. The information remains accessible if needed but does not consume context continuously.
**Masking Strategy Selection**
Not all observations should be masked equally:
Never mask: Observations critical to current task, observations from the most recent turn, observations used in active reasoning.
Consider masking: Observations from 3+ turns ago, verbose outputs with key points extractable, observations whose purpose has been served.
Always mask: Repeated outputs, boilerplate headers/footers, outputs already summarized in conversation.
### KV-Cache Optimization
**Understanding KV-Cache**
The KV-cache stores Key and Value tensors computed during inference, growing linearly with sequence length. Caching the KV-cache across requests sharing identical prefixes avoids recomputation.
Prefix caching reuses KV blocks across requests with identical prefixes using hash-based block matching. This dramatically reduces cost and latency for requests with common prefixes like system prompts.
**Cache Optimization Patterns**
Optimize for caching by reordering context elements to maximize cache hits. Place stable elements first (system prompt, tool definitions), then frequently reused elements, then unique elements last.
Design prompts to maximize cache stability: avoid dynamic content like timestamps, use consistent formatting, keep structure stable across sessions.
### Context Partitioning
**Sub-Agent Partitioning**
The most aggressive form of context optimization is partitioning work across sub-agents with isolated contexts. Each sub-agent operates in a clean context focused on its subtask without carrying accumulated context from other subtasks.
This approach achieves separation of concerns—the detailed search context remains isolated within sub-agents while the coordinator focuses on synthesis and analysis.
**Result Aggregation**
Aggregate results from partitioned subtasks by validating all partitions completed, merging compatible results, and summarizing if still too large.
### Budget Management
**Context Budget Allocation**
Design explicit context budgets. Allocate tokens to categories: system prompt, tool definitions, retrieved docs, message history, and reserved buffer. Monitor usage against budget and trigger optimization when approaching limits.
**Trigger-Based Optimization**
Monitor signals for optimization triggers: token utilization above 80%, degradation indicators, and performance drops. Apply appropriate optimization techniques based on context composition.
## Practical Guidance
### Optimization Decision Framework
When to optimize:
- Context utilization exceeds 70%
- Response quality degrades as conversations extend
- Costs increase due to long contexts
- Latency increases with conversation length
What to apply:
- Tool outputs dominate: observation masking
- Retrieved documents dominate: summarization or partitioning
- Message history dominates: compaction with summarization
- Multiple components: combine strategies
### Performance Considerations
Compaction should achieve 50-70% token reduction with less than 5% quality degradation. Masking should achieve 60-80% reduction in masked observations. Cache optimization should achieve 70%+ hit rate for stable workloads.
Monitor and iterate on optimization strategies based on measured effectiveness.
## Examples
**Example 1: Compaction Trigger**
```python
if context_tokens / context_limit > 0.8:
context = compact_context(context)
```
**Example 2: Observation Masking**
```python
if len(observation) > max_length:
ref_id = store_observation(observation)
return f"[Obs:{ref_id} elided. Key: {extract_key(observation)}]"
```
**Example 3: Cache-Friendly Ordering**
```python
# Stable content first
context = [system_prompt, tool_definitions] # Cacheable
context += [reused_templates] # Reusable
context += [unique_content] # Unique
```
## Guidelines
1. Measure before optimizing—know your current state
2. Apply compaction before masking when possible
3. Design for cache stability with consistent prompts
4. Partition before context becomes problematic
5. Monitor optimization effectiveness over time
6. Balance token savings against quality preservation
7. Test optimization at production scale
8. Implement graceful degradation for edge cases
## Integration
This skill builds on context-fundamentals and context-degradation. It connects to:
- multi-agent-patterns - Partitioning as isolation
- evaluation - Measuring optimization effectiveness
- memory-systems - Offloading context to memory
## References
Internal reference:
- Optimization Techniques Reference - Detailed technical reference
Related skills in this collection:
- context-fundamentals - Context basics
- context-degradation - Understanding when to optimize
- evaluation - Measuring optimization
External resources:
- Research on context window limitations
- KV-cache optimization techniques
- Production engineering guides
---
## Skill Metadata
**Created**: 2025-12-20
**Last Updated**: 2025-12-20
**Author**: Agent Skills for Context Engineering Contributors
**Version**: 1.0.0Related Skills
hig-project-context
Create or update a shared Apple design context document that other HIG skills use to tailor guidance.
filesystem-context
Use for file-based context management, dynamic context discovery, and reducing context window bloat. Offload context to files for just-in-time loading.
ddd-context-mapping
Map relationships between bounded contexts and define integration contracts using DDD context mapping patterns.
database-cloud-optimization-cost-optimize
You are a cloud cost optimization expert specializing in reducing infrastructure expenses while maintaining performance and reliability. Analyze cloud spending, identify savings opportunities, and implement cost-effective architectures across AWS, Azure, and GCP.
cost-optimization
Strategies and patterns for optimizing cloud costs across AWS, Azure, and GCP.
context7-auto-research
Automatically fetch latest library/framework documentation for Claude Code via Context7 API. Use when you need up-to-date documentation for libraries and frameworks or asking about React, Next.js, Prisma, or any other popular library.
context-management-context-save
Use when working with context management context save
context-management-context-restore
Use when working with context management context restore
context-guardian
Guardiao de contexto que preserva dados criticos antes da compactacao automatica. Snapshots, verificacao de integridade e zero perda de informacao.
context-driven-development
Guide for implementing and maintaining context as a managed artifact alongside code, enabling consistent AI interactions and team alignment through structured project documentation.
context-compression
When agent sessions generate millions of tokens of conversation history, compression becomes mandatory. The naive approach is aggressive compression to minimize tokens per request.
context-agent
Agente de contexto para continuidade entre sessoes. Salva resumos, decisoes, tarefas pendentes e carrega briefing automatico na sessao seguinte.