Context Optimization

Context Optimization

Guides an AI agent in stretching its context window through budgeting, observation masking, cache-friendly prefixes, partitioning and compaction, with measurement before and after.

Skill files3 files

references/

scripts/

SKILL.md224 lines
1
---
2
name: context-optimization
3
description: "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."
4
---
5
6
# Context Optimization Techniques
7
8
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.
9
10
## When to Activate
11
12
Activate this skill when:
13
- Context budgets or token costs constrain task complexity
14
- Observation masking can replace verbose tool outputs with retrievable references
15
- Prefix or KV-cache hit rate needs improvement
16
- Retrieval scoping can reduce irrelevant loaded context
17
- Context partitioning can extend effective capacity across agents
18
- Budget triggers are needed for masking, compaction, or partitioning
19
20
Do not activate this skill for adjacent work owned by other skills:
21
- Explaining why attention or context windows behave this way: `context-fundamentals`.
22
- Diagnosing active lost-in-middle, poisoning, distraction, confusion, or clash: `context-degradation`.
23
- Designing a structured handoff summary for a long conversation: `context-compression`.
24
- Storing large outputs, plans, or logs as files: `filesystem-context`.
25
- Model-initiated rewrites of its own context and their re-prefill cost: `self-managed-context`.
26
- Qualifying a specific model to trigger its own compaction instead of a harness threshold: `compaction-control-profiling`.
27
28
## Core Concepts
29
30
Apply four primary strategies in this priority order:
31
32
1. **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.
33
34
2. **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.
35
36
3. **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.
37
38
4. **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.
39
40
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.
41
42
## Detailed Topics
43
44
### Compaction Strategies
45
46
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.
47
48
Preserve different elements by message type:
49
50
- **Tool outputs**: Extract key findings, metrics, error codes, and conclusions. Strip verbose raw output, stack traces (unless debugging is ongoing), and boilerplate headers.
51
- **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.
52
- **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.
53
54
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.
55
56
### Observation Masking
57
58
Mask observations selectively based on recency and ongoing relevance — not uniformly. Apply these rules:
59
60
- **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 progress.
61
- **Mask after 3+ turns**: Verbose outputs whose key points have already been extracted into the conversation flow. Replace with a compact reference: `[Obs:{ref_id} elided. Key: {summary}. Full content retrievable.]`
62
- **Always mask immediately**: Repeated/duplicate outputs, boilerplate headers and footers, outputs already summarized earlier in the conversation.
63
64
Masking should achieve 60-80% reduction in masked observations with less than 2% quality impact. The key is maintaining retrievability — store the full content externally and keep the reference ID in context so the agent can request the original if needed.
65
66
### KV-Cache Optimization
67
68
Maximize prefix cache hits by structuring prompts so that stable content occupies the prefix and dynamic content appears at the end. KV-cache stores Key and Value tensors computed during inference; when consecutive requests share an identical prefix, the cached tensors are reused, saving both cost and latency.
69
70
Apply this ordering in every prompt:
71
1. System prompt (most stable — never changes within a session)
72
2. Tool definitions (stable across requests)
73
3. Frequently reused templates and few-shot examples
74
4. Conversation history (grows but shares prefix with prior turns)
75
5. Current query and dynamic content (least stable — always last)
76
77
Design prompts for cache stability: remove timestamps, session counters, and request IDs from the system prompt. Move dynamic metadata into a separate user message or tool result where it does not break the prefix. Even a single whitespace change in the prefix invalidates the entire cached block downstream of that change. The same rule prices any compaction or masking edit applied to earlier history: its cost is the text that follows it, so batch such edits and prefer them near the end of the context.
78
79
Target 70%+ cache hit rate for stable workloads. At scale, this translates to 50%+ cost reduction and 40%+ latency reduction on cached tokens.
80
81
### Context Partitioning
82
83
Partition work across sub-agents when a single context cannot hold the full problem without triggering aggressive compaction. Each sub-agent operates in a clean, focused context for its subtask, then returns a structured result to a coordinator agent.
84
85
Plan partitioning when estimated task context exceeds 60% of the window limit. Decompose the task into independent subtasks, assign each to a sub-agent, and aggregate results. Validate that all partitions completed before merging, merge compatible results, and apply summarization if the aggregated output still exceeds budget.
86
87
This approach achieves separation of concerns — detailed search context stays isolated within sub-agents while the coordinator focuses on synthesis. However, coordination has real token cost: the coordinator prompt, result aggregation, and error handling all consume tokens. Only partition when the savings exceed this overhead.
88
89
### Budget Management
90
91
Allocate explicit token budgets across context categories before the session begins: system prompt, tool definitions, retrieved documents, message history, tool outputs, and a reserved buffer (5-10% of total). Monitor usage against budget continuously and trigger optimization when any category exceeds its allocation or total utilization crosses 70%.
92
93
Use trigger-based optimization rather than periodic optimization. Monitor these signals:
94
- Token utilization above 80% — trigger compaction
95
- Attention degradation indicators (repetition, missed instructions) — trigger masking + compaction
96
- Quality score drops below baseline — audit context composition before optimizing
97
98
## Practical Guidance
99
100
### Optimization Decision Framework
101
102
Select the optimization technique based on what dominates the context:
103
104
| Context Composition | First Action | Second Action |
105
|---|---|---|
106
| Tool outputs dominate (>50%) | Observation masking | Compaction of remaining turns |
107
| Retrieved documents dominate | Summarization | Partitioning if docs are independent |
108
| Message history dominates | Compaction with selective preservation | Partitioning for new subtasks |
109
| Multiple components contribute | KV-cache optimization first, then layer masking + compaction |
110
| Near-limit with active debugging | Mask resolved tool outputs only — preserve error details |
111
112
### Performance Targets
113
114
Track these metrics to validate optimization effectiveness:
115
116
- **Compaction**: 50-70% token reduction, <5% quality degradation, <10% latency overhead from the compaction step itself
117
- **Masking**: 60-80% reduction in masked observations, <2% quality impact, near-zero latency overhead
118
- **Cache optimization**: 70%+ hit rate for stable workloads, 50%+ cost reduction, 40%+ latency reduction
119
- **Partitioning**: Net token savings after accounting for coordinator overhead; break-even typically requires 3+ subtasks
120
121
Iterate on strategies based on measured results. If an optimization technique does not measurably improve the target metric, remove it — optimization machinery itself consumes tokens and adds latency.
122
123
## Examples
124
125
**Example 1: Compaction Trigger**
126
```python
127
if context_tokens / context_limit > 0.8:
128
context = compact_context(context)
129
```
130
131
**Example 2: Observation Masking**
132
```python
133
if len(observation) > max_length:
134
ref_id = store_observation(observation)
135
return f"[Obs:{ref_id} elided. Key: {extract_key(observation)}]"
136
```
137
138
**Example 3: Cache-Friendly Ordering**
139
```python
140
# Stable content first
141
context = [system_prompt, tool_definitions] # Cacheable
142
context += [reused_templates] # Reusable
143
context += [unique_content] # Unique
144
```
145
146
**Example 4: Budget-triggered optimization policy**
147
```yaml
148
budgets:
149
tool_outputs: 35%
150
message_history: 30%
151
retrieved_documents: 20%
152
reserved_buffer: 15%
153
triggers:
154
tool_outputs_over_budget: mask resolved observations
155
total_context_over_70_percent: compact message history
156
repeated_irrelevant_retrievals: tighten retrieval scope
157
```
158
159
## Guidelines
160
161
1. Measure before optimizing—know your current state
162
2. Apply masking before compaction — remove low-value bulk first, then summarize what remains
163
3. Design for cache stability with consistent prompts
164
4. Partition before context becomes problematic
165
5. Monitor optimization effectiveness over time
166
6. Balance token savings against quality preservation
167
7. Test optimization at production scale
168
8. Implement graceful degradation for edge cases
169
170
## Gotchas
171
172
1. **Whitespace breaks KV-cache**: Even a single whitespace or newline change in the prompt prefix invalidates the entire KV-cache block downstream of that point. Pin system prompts as immutable strings — do not interpolate timestamps, version numbers, or session IDs into them. Diff prompt templates byte-for-byte between deployments.
173
174
2. **Timestamps in system prompts destroy cache hit rates**: Including `Current date: {today}` or similar dynamic content in the system prompt forces a full cache miss on every new day (or every request, if using time-of-day). Move dynamic metadata into a user message or a separate tool result appended after the stable prefix.
175
176
3. **Compaction under pressure loses critical state**: When the model performing compaction is itself under context pressure (>85% utilization), its summarization quality degrades — it omits task goals, drops user constraints, and flattens nuanced state. Trigger compaction at 70-80%, not 90%+. If compaction must happen late, use a separate model call with a clean context containing only the material to summarize.
177
178
4. **Masking error outputs breaks debugging loops**: Over-aggressive masking hides error messages, stack traces, and failure details that the agent needs in subsequent turns to diagnose and fix issues. During active debugging (error in the last 3 turns), suspend masking for all error-related observations until the issue is resolved.
179
180
5. **Partitioning overhead can exceed savings**: Each sub-agent requires its own system prompt, tool definitions, and coordination messages. For tasks with fewer than 3 independent subtasks, the coordination overhead often exceeds the context savings. Estimate total tokens (coordinator + all sub-agents) before committing to partitioning.
181
182
6. **Cache miss cost spikes after deployment changes**: Reordering tools, rewording the system prompt, or changing few-shot examples between deployments invalidates the entire prefix cache, causing a temporary cost spike of 2-5x until the new cache warms up. Roll out prompt changes gradually and monitor cache hit rate during deployment windows.
183
184
7. **Compaction creates false confidence in stale summaries**: Once context is compacted, the summary looks authoritative but may reflect outdated state. If the task has evolved since compaction (new user requirements, corrected assumptions), the summary silently carries forward stale information. After compaction, re-validate the summary against the current task goal before proceeding.
185
186
## Integration
187
188
This skill owns token-efficiency tactics and budget policy. Adjacent skills own diagnosis, storage, and architecture:
189
190
- `context-fundamentals`: mental models for why context quality and attention placement matter.
191
- `context-degradation`: diagnosis when output quality has already dropped.
192
- `context-compression`: lossy summarization and handoff strategy.
193
- `filesystem-context`: file-backed offloading for full outputs and logs.
194
- `multi-agent-patterns`: partitioning work across isolated agent contexts.
195
- `latent-briefing`: selective KV retention across orchestrator-worker boundaries in compatible runtimes.
196
- `self-managed-context`: the model, not the harness, decides when and what to edit in its live context.
197
- `compaction-control-profiling`: per-model measurement of whether the harness threshold or the model should trigger compaction.
198
- `evaluation`: measuring whether the optimization improved quality, cost, or latency.
199
- `memory-systems`: persistent retrieval layers that feed context just in time.
200
201
## References
202
203
Internal reference:
204
- [Optimization Techniques Reference](./references/optimization_techniques.md) - Read when: implementing a specific optimization technique and needing detailed code patterns, threshold tables, or integration examples beyond what the skill body provides
205
206
Related skills in this collection:
207
- context-fundamentals - Read when: unfamiliar with context window mechanics, token counting, or attention distribution basics
208
- context-degradation - Read when: diagnosing why agent performance has dropped and needing to identify which degradation pattern is occurring before selecting an optimization
209
- evaluation - Read when: setting up metrics and benchmarks to measure whether an optimization technique actually improved outcomes
210
211
External resources:
212
- Research on context window limitations - Read when: evaluating model-specific context behavior (e.g., lost-in-the-middle effects, attention decay curves)
213
- KV-cache optimization techniques - Read when: implementing prefix caching at the inference infrastructure level (vLLM, TGI, or cloud provider APIs)
214
- Production engineering guides - Read when: deploying context optimization in a production pipeline and needing operability patterns (monitoring, alerting, rollback)
215
216
---
217
218
## Skill Metadata
219
220
**Created**: 2025-12-20
221
**Last Updated**: 2026-05-15
222
**Author**: Agent Skills for Context Engineering Contributors
223
**Version**: 2.1.0
224

© Context Engineering Agent Skills Contributors · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…