Skip to content
Skills Library
AI & agents · Building & coding

context-optimization

/context-optimization

Use when optimizing token usage, KV cache efficiency, or context window management for LLM agents. Keywords: context optimization, KV cache, prompt caching, token budget, semantic pruning, lost-in-the-middle.

Licence
Apache-2.0
Last repository change
24.10.2026

Assessment and security

90/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content25 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 24.10.2026, without references to retired models or APIs.

Licence

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

What it does and when to use it

Use when optimizing token usage, KV cache efficiency, or context window management for LLM agents. Keywords: context optimization, KV cache, prompt caching, token budget, semantic pruning, lost-in-the-middle.

Original author description

Use when optimizing token usage, KV cache efficiency, or context window management for LLM agents. Keywords: context optimization, KV cache, prompt caching, token budget, semantic pruning, lost-in-the-middle.

How it works

  1. 1. Prompt Cache Alignment
  2. 2. Semantic Pruning & AST Compaction
  3. 3. Lost-in-the-Middle Mitigation
  4. 4. Sliding Windows & Recursive Summarization
  5. 5. Token Budget Allocation
  6. 6. Context Freshness Decisions
  7. 7. Measuring Cache Hit Rate
  8. Best Practices Checklist
Original SKILL.md headings · 77 lines, 565 words
SKILL.md preview
---
name: "context-optimization"
description: >-
  Use when optimizing token usage, KV cache efficiency, or context window management for LLM agents. Keywords: context optimization, KV cache, prompt caching, token budget, semantic pruning, lost-in-the-middle.
---

# Context Optimization Skill

This skill provides methodologies and best practices for maximizing context window efficiency, reducing token costs, and improving the performance of LLM-based agentic workflows.

## 1. Prompt Cache Alignment

To maximize Key-Value (KV) cache hits, prioritize stability in the early parts of the prompt.

- **Static Prefixes**: Design system prompts to remain identical across agent turns.
- **Tool Order**: Sort tool definitions alphabetically or by frequency of use. Keep this ordering constant.
- **Prefix Consistency**: Reserve the top 70% of the KV cache for global system instructions and tool definitions.
- **Avoid Dynamic Data**: Move dynamic session-specific data (dates, current file list) to the end of the context window.

## 2. Semantic Pruning & AST Compaction

Reduce unnecessary data before sending it to the model.

- **Removal of Non-Essentials**: Strip comments, debug logs, and unused boilerplate code.
- **AST Compaction**: Convert deep code structures into simplified, representative summaries or pseudocode.
- **Whitespace Stripping**: Use minification for configuration files (JSON, YAML) and standard code.
- **Irrelevant Body Dropping**: Replace large, irrelevant function bodies with docstrings or signatures if the model doesn't need to reason about the implementation details.

## 3. Lost-in-the-Middle Mitigation

LLMs often suffer from recall degradation for information in the center of the context window.

- **Boundary Priority**: Place high-priority constraints, critical instructions, and schema definitions at the very beginning (Head) or the very end (Tail) of the context.
- **Sandwich Strategy**: If critical information must be in the middle, sandwich it between two clear, high-level summary points that repeat its purpose.

## 4. Sliding Windows & Recursive Summarization

Manage long-running conversations without exceeding token thresholds.

- **Sliding Window**: Keep only the N most recent turns for immediate interaction.
- **Recursive Summarization**: Periodically collapse historical turns into a compressed "Session State Summary".
- **State Archiving**: Store older, less relevant interactions in a side-car file (e.g., `archive.md`) that the agent can read only when necessary.

## 5. Token Budget Allocation

Implement a disciplined token distribution:

| Category | Typical % | Goal |
| :--- | :--- | :--- |
| System Prompt | 10-15% | Definition of role & constraints |
| Tool Definitions | 15-20% | Capability exposure |
| Interaction History | 30-40% | Context for current turn |
| Reserved (Drafting) | 25-45% | Headroom for generation |

## 6. Context Freshness Decisions

Determine when to act on history:

- **Summarize**: When history exceeds 50% of the token budget and requires long-term context.
- **Truncate**: When history is irrelevant to the current task or contains repetitive technical noise.
- **Archive**: When information must be preserved (e.g., decisions, ADRs) but is not needed for the immediate turn.

## 7. Measuring Cache Hit Rate

Continuous improvement relies on telemetry.

- **Monitoring**: Track Cache Hit Rate (CHR) metrics provided by the API provider.
- **Iteration**: Analyze sessions with low CHR. Are the system prompts shifting? Is tool definition order inconsistent?
- **Optimization Loop**:
  1. Measure performance per turn.
  2. Identify volatility in the prefix.
  3. Refactor static content to improve cache stability.
  4. Re-measure.

## Best Practices Checklist

- [ ] Does my system prompt remain stable across requests?
- [ ] Are tools sorted consistently?
- [ ] Is critical information pinned to the Head or Tail?
- [ ] Have I pruned unused code/data from the ingestion stream?
- [ ] Is there an automated summarization step for history?

Versions

RepositoryScoreLicence
This page · VoDaiLocz/kilo-kit-mcp90Apache-2.0
atretyak1985/swarmery100Apache-2.0
dhar174/langgraph_system_generator100MIT
athola/claude-night-market100MIT
AbdullahMalik17/Digital-FTE100MIT
seb1n/awesome-ai-agent-skills100MIT
bcastelino/agent-skills-kit100MIT
viktorbezdek/skillstack100MIT

Database snapshot: 13.11.2026 · package version 2a1882fcbec9 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100ai-cost-optimizer
    Optimize LLM inference costs: token budget allocation, model routing, caching strategy, and batching without breaching quality thresholds. Use when working on prompt engineering, AI workflows, agents, context design, or LLM optimization.
  • 90context-window-management
    Strategies for managing LLM context windows including summarization, trimming, routing, and avoiding context rot Use when: context window, token limit, context management, context engineering, long...
  • 100context-report
    Analyze Claude Code context efficiency. Use when evaluating session token usage.
  • 100prompt-optimizer
    Optimize prompts for token efficiency, latency, and output quality while preserving task behavior. Use when working on prompt engineering, AI workflows, agents, context design, or LLM optimization.
  • 100tune-prompt-management
    Tune Prompt Management — optimize token usage, A/B test configuration, few-shot example selection, template compression, prompt caching. Use when: tune, optimize prompts.
  • 90memory-optimization
    Summarizing context, pruning history, and managing token budget efficiency. Use when: memory optimization.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.