This skill should be used when the user asks to "optimize context", "reduce token costs", "improve context efficiency", "implement KV-cache optimization", "partition context", or mentions context limits, observation masking, context budgeting, or extending effective context capacity.
Add this skill
npx mdskills install muratcankoylan/context-optimizationComprehensive guide to context optimization with clear strategies and concrete examples
1---2name: context-optimization3description: This skill should be used when the user asks to "optimize context", "reduce token costs", "improve context efficiency", "implement KV-cache optimization", "partition context", or mentions context limits, observation masking, context budgeting, or extending effective context capacity.4---56# Context Optimization Techniques78Context 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.910## When to Activate1112Activate this skill when:13- Context limits constrain task complexity14- Optimizing for cost reduction (fewer tokens = lower costs)15- Reducing latency for long conversations16- Implementing long-running agent systems17- Needing to handle larger documents or conversations18- Building production systems at scale1920## Core Concepts2122Context 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).2324The 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.2526## Detailed Topics2728### Compaction Strategies2930**What is Compaction**31Compaction 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.3233Compaction typically serves as the first lever in context optimization. The art lies in selecting what to keep versus what to discard.3435**Compaction Implementation**36Compaction 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.3738**Summary Generation**39Effective summaries preserve different elements depending on message type:4041Tool outputs: Preserve key findings, metrics, and conclusions. Remove verbose raw output.4243Conversational turns: Preserve key decisions, commitments, and context shifts. Remove filler and back-and-forth.4445Retrieved documents: Preserve key facts and claims. Remove supporting evidence and elaboration.4647### Observation Masking4849**The Observation Problem**50Tool 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.5152Observation masking replaces verbose tool outputs with compact references. The information remains accessible if needed but does not consume context continuously.5354**Masking Strategy Selection**55Not all observations should be masked equally:5657Never mask: Observations critical to current task, observations from the most recent turn, observations used in active reasoning.5859Consider masking: Observations from 3+ turns ago, verbose outputs with key points extractable, observations whose purpose has been served.6061Always mask: Repeated outputs, boilerplate headers/footers, outputs already summarized in conversation.6263### KV-Cache Optimization6465**Understanding KV-Cache**66The 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.6768Prefix 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.6970**Cache Optimization Patterns**71Optimize 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.7273Design prompts to maximize cache stability: avoid dynamic content like timestamps, use consistent formatting, keep structure stable across sessions.7475### Context Partitioning7677**Sub-Agent Partitioning**78The 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.7980This approach achieves separation of concerns—the detailed search context remains isolated within sub-agents while the coordinator focuses on synthesis and analysis.8182**Result Aggregation**83Aggregate results from partitioned subtasks by validating all partitions completed, merging compatible results, and summarizing if still too large.8485### Budget Management8687**Context Budget Allocation**88Design 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.8990**Trigger-Based Optimization**91Monitor signals for optimization triggers: token utilization above 80%, degradation indicators, and performance drops. Apply appropriate optimization techniques based on context composition.9293## Practical Guidance9495### Optimization Decision Framework9697When to optimize:98- Context utilization exceeds 70%99- Response quality degrades as conversations extend100- Costs increase due to long contexts101- Latency increases with conversation length102103What to apply:104- Tool outputs dominate: observation masking105- Retrieved documents dominate: summarization or partitioning106- Message history dominates: compaction with summarization107- Multiple components: combine strategies108109### Performance Considerations110111Compaction 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.112113Monitor and iterate on optimization strategies based on measured effectiveness.114115## Examples116117**Example 1: Compaction Trigger**118```python119if context_tokens / context_limit > 0.8:120 context = compact_context(context)121```122123**Example 2: Observation Masking**124```python125if len(observation) > max_length:126 ref_id = store_observation(observation)127 return f"[Obs:{ref_id} elided. Key: {extract_key(observation)}]"128```129130**Example 3: Cache-Friendly Ordering**131```python132# Stable content first133context = [system_prompt, tool_definitions] # Cacheable134context += [reused_templates] # Reusable135context += [unique_content] # Unique136```137138## Guidelines1391401. Measure before optimizing—know your current state1412. Apply compaction before masking when possible1423. Design for cache stability with consistent prompts1434. Partition before context becomes problematic1445. Monitor optimization effectiveness over time1456. Balance token savings against quality preservation1467. Test optimization at production scale1478. Implement graceful degradation for edge cases148149## Integration150151This skill builds on context-fundamentals and context-degradation. It connects to:152153- multi-agent-patterns - Partitioning as isolation154- evaluation - Measuring optimization effectiveness155- memory-systems - Offloading context to memory156157## References158159Internal reference:160- [Optimization Techniques Reference](./references/optimization_techniques.md) - Detailed technical reference161162Related skills in this collection:163- context-fundamentals - Context basics164- context-degradation - Understanding when to optimize165- evaluation - Measuring optimization166167External resources:168- Research on context window limitations169- KV-cache optimization techniques170- Production engineering guides171172---173174## Skill Metadata175176**Created**: 2025-12-20177**Last Updated**: 2025-12-20178**Author**: Agent Skills for Context Engineering Contributors179**Version**: 1.0.0180
Full transparency — inspect the skill content before installing.