Agent skill

Context Optimization

by seb1n in seb1n/awesome-ai-agent-skills

Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget.

MITAuto-check passedAgent Workflows

Install Context Optimization

skills CLI
$ npx skills add seb1n/awesome-ai-agent-skills --skill context-optimization -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install seb1n/awesome-ai-agent-skills context-optimization --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/context-engineering/context-optimization .claude/skills/context-optimization && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
context-optimization
GitHub stars
206
Token cost
~2.9k tokens
SKILL.md length
1,549 words
Files
1
Skills in repo
91
Repo updated
First seen
Licence
MIT

At a glance

Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget.

  • Works in 6 steps: Audit the Raw Context: Inventory every… → Deduplicate Overlapping Content: Scan… → Score Relevance and Information Density:… → …
  • Assembled material is noisy
  • SKILL.md covers Workflow, Techniques, Usage and Examples, plus 2 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Context Optimization is an agent skill from seb1n/awesome-ai-agent-skills. Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget. Use when retrieved or assembled material is noisy or exceeds the useful context budget; use context-ranking for scoring chunks and context-compression for shrinking selected content.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Agent Workflows, covering Context engineering and LLM cost and token optimization. The repository describes itself as: 103 ready-to-use AI agent skills for Claude Code, OpenAI Codex, Gemini CLI, Cursor, GitHub Copilot, Windsurf, and other Agent Skills-compatible tools. Complete SKILL.md… The licence is MIT.

When your agent uses it

  • Assembled material is noisy
  • Exceeds the useful context budget
  • Use context-ranking for scoring chunks and context-compression for shrinking selected content

Example prompts

  • “/context-optimization”

Workflow steps

6 steps, taken from the first numbered list in SKILL.md.

  1. Audit the Raw Context: Inventory every piece of context that has been gathered -- retrieved documents, conversation history, tool outputs…
  2. Deduplicate Overlapping Content: Scan the context for near-duplicate passages that convey the same information. This is common in RAG…
  3. Score Relevance and Information Density: Assign each context chunk two scores: a relevance score (how closely it relates to the current…
  4. Filter Low-Value Content: Remove chunks whose composite utility score falls below a threshold. A good starting point is to keep the top…
  5. Reorder by Priority: Arrange the remaining chunks to maximize the model's attention. Place the highest-utility chunks first (models attend…
  6. Validate Coverage: After filtering and reordering, verify that the optimized context still covers all aspects of the query. If the query…

What it can do on your machine

Read from SKILL.md and the folder at commit 75865a5. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Context Optimization loads about 2.9k tokens when it runs. Until then it costs about 80 tokens; SKILL.md has 1,549 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~80
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from seb1n/awesome-ai-agent-skills at commit 75865a5, republished under its MIT licence (© seb1n). 1,549 words, ~2,891 tokens.

Download SKILL.mdSave it as .claude/skills/context-optimization/SKILL.md (or your agent's skills folder).
name
context-optimization
description
Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget. Use when retrieved or assembled material is noisy or exceeds the useful context budget; use context-ranking for scoring chunks and context-compression for shrinking selected content.
license
MIT
metadata.author
awesome-ai-agent-skills
metadata.version
1.0.0

Context Optimization

Context optimization is the process of refining the raw context assembled for an AI model so that every token contributes meaningfully to the task. In a typical RAG or agent pipeline, the retrieved context often contains redundant passages, marginally relevant chunks, and poorly ordered information. Optimization transforms this raw material into a lean, high-signal context block that improves answer quality, reduces inference cost, and makes the most of the model's attention budget.

Workflow

  1. Audit the Raw Context: Inventory every piece of context that has been gathered -- retrieved documents, conversation history, tool outputs, and metadata. Measure the total token count and compare it against the available context budget. Identify the compression ratio needed if the raw context exceeds the budget.

  2. Deduplicate Overlapping Content: Scan the context for near-duplicate passages that convey the same information. This is common in RAG pipelines where chunking with overlap produces multiple chunks covering the same paragraph, or when multiple source documents repeat the same facts. Use semantic similarity (cosine distance > 0.92) or exact n-gram overlap detection to identify duplicates, then keep only the most complete version of each piece of information.

  3. Score Relevance and Information Density: Assign each context chunk two scores: a relevance score (how closely it relates to the current query) and an information density score (how many useful facts it conveys per token). Relevance can be measured via the retrieval score or a lightweight cross-encoder pass. Density can be estimated by counting named entities, code identifiers, numerical data, and key terms relative to chunk length. Multiply the two scores to produce a composite utility score.

  4. Filter Low-Value Content: Remove chunks whose composite utility score falls below a threshold. A good starting point is to keep the top 60-70% of chunks by utility score. Also remove boilerplate text (copyright notices, navigation menus, repeated headers) that contributes zero information. Be conservative -- it is better to include a marginally relevant chunk than to lose a critical fact.

  5. Reorder by Priority: Arrange the remaining chunks to maximize the model's attention. Place the highest-utility chunks first (models attend most to the beginning of the context) and the second-highest near the end (models also attend to recency). Avoid burying critical information in the middle of a long context block -- this is the "lost in the middle" zone where model attention is weakest.

  6. Validate Coverage: After filtering and reordering, verify that the optimized context still covers all aspects of the query. If the query has multiple sub-questions, ensure at least one chunk addresses each. If coverage gaps appear, selectively re-add previously filtered chunks that fill the gap, even if their utility score was below the threshold.

Techniques

  • Deduplication: Identifies and removes redundant passages using semantic similarity thresholds or n-gram overlap detection. Critical in RAG pipelines where overlapping chunks often repeat the same sentences. Keeps the most complete or highest-scoring version.
  • Relevance Filtering: Removes chunks that fall below a relevance threshold. Uses the original retrieval score, a reranker score, or keyword overlap with the query as the signal. Aggressiveness should be tuned -- filtering too hard causes coverage gaps.
  • Information Density Scoring: Estimates how much useful information a chunk contains per token. Dense chunks (packed with facts, code, or data) are preferred over verbose, low-density prose. Useful for deciding which chunks to keep when two have similar relevance scores.
  • Priority-Based Ordering: Arranges chunks so the model sees the most important information first and last, avoiding the "lost in the middle" effect. This is especially impactful for long context windows (32K+ tokens) where attention degradation is more pronounced.
  • Context Window Strategies: Different model context windows require different optimization approaches. For small windows (4K tokens), aggressive filtering and compression are essential. For medium windows (32K), focus on deduplication and ordering. For large windows (128K+), ordering and density scoring matter most, since there is room for more material but the lost-in-the-middle effect is amplified.

Usage

Provide the raw context (a list of text chunks with optional metadata and scores), the user query, and the target token budget. The skill returns an optimized context block -- deduplicated, filtered, scored, and reordered -- ready for prompt assembly. Optionally provide a coverage checklist (key topics the context must address) to prevent important information from being filtered out.

Examples

Example 1: Optimizing Context for a Multi-File Code Edit Task

Task: "Refactor the authentication module to use async/await instead of callbacks."

Raw Context (7 chunks, ~4,200 tokens):

#SourceRelevanceDensityContent Summary
1src/auth/login.js:1-450.93HighLogin function using callback-based db.findUser()
2src/auth/login.js:20-550.90HighOverlapping chunk -- duplicates lines 20-45 of chunk 1, adds token refresh logic
3src/auth/middleware.js:1-300.88HighAuth middleware with callback-based token verification
4README.md:100-1300.45LowProject setup instructions -- no code, no auth details
5src/auth/register.js:1-400.82HighRegistration function using callbacks
6package.json:1-250.35LowDependency list -- no auth-related logic
7src/auth/login.js:40-700.91HighToken generation and session creation with callbacks

Optimization Steps:

  1. Deduplicate: Chunks 1 and 2 overlap on lines 20-45. Merge into a single chunk covering lines 1-55 of login.js.
  2. Filter: Remove chunk 4 (README setup instructions, relevance 0.45) and chunk 6 (package.json, relevance 0.35) -- below the 0.50 threshold.
  3. Reorder: Place merged login.js chunk first (highest relevance), then the token generation chunk, then middleware.js, then register.js.

Optimized Context (~2,800 tokens, 33% reduction):

  1. src/auth/login.js:1-55 (merged) -- Login function with callback-based DB lookup and token refresh
  2. src/auth/login.js:40-70 -- Token generation and session creation
  3. src/auth/middleware.js:1-30 -- Auth middleware with callback token verification
  4. src/auth/register.js:1-40 -- Registration function using callbacks
Show full SKILL.md (637 more words)Show less
Example 2: Optimizing RAG-Retrieved Context to Eliminate Redundancy

Query: "What is the company's return policy for electronics?"

Raw Retrieved Chunks (6 chunks, ~3,000 tokens):

  1. returns-policy.md (score 0.95) -- "Electronics purchased from our store may be returned within 30 days of purchase. Items must be in original packaging with all accessories. A 15% restocking fee applies to opened items."
  2. faq.md (score 0.88) -- "Q: Can I return electronics? A: Yes, within 30 days. Items must be in original packaging. A 15% restocking fee applies to opened items. See our returns policy for full details."
  3. holiday-policy.md (score 0.72) -- "During the holiday season (Nov 15 - Jan 15), the return window for all products, including electronics, is extended to 60 days. All other conditions apply."
  4. shipping-info.md (score 0.40) -- "We ship electronics via insured ground shipping. Delivery takes 3-7 business days."
  5. returns-policy.md (score 0.85) -- "Refunds are processed to the original payment method within 5-10 business days. Defective items are exempt from the restocking fee and may be returned within 90 days."
  6. store-locator.md (score 0.30) -- "Visit any of our 200 retail locations nationwide."

Optimization Steps:

  1. Deduplicate: Chunks 1 and 2 convey nearly identical information (30-day window, original packaging, 15% fee). Keep chunk 1 (higher score, more authoritative source).
  2. Filter: Remove chunk 4 (shipping info, not about returns, score 0.40) and chunk 6 (store locator, irrelevant, score 0.30).
  3. Reorder: Chunk 1 (core policy) then chunk 5 (refund processing) then chunk 3 (holiday extension).

Optimized Context (~900 tokens, 70% reduction):

  1. Core policy: 30-day return window, original packaging required, 15% restocking fee for opened items.
  2. Refund details: processed to original payment method in 5-10 business days; defective items exempt from restocking fee, 90-day window.
  3. Holiday extension: Nov 15 - Jan 15, return window extended to 60 days.

Best Practices

  • Deduplicate before filtering -- removing redundant passages first gives you a clearer picture of the unique information available, leading to better filtering decisions.
  • Tune thresholds on your domain -- relevance and density score thresholds vary by use case. A code-generation task may need stricter relevance filtering than a general Q&A task. Calibrate on a labeled evaluation set.
  • Preserve diversity of sources -- when multiple chunks have similar scores, prefer keeping chunks from different source documents to increase coverage and reduce bias toward a single source.
  • Account for the lost-in-the-middle effect -- for context windows above 8K tokens, place the most critical chunks at the beginning and end of the context block. Test with your specific model, as the effect varies across architectures.
  • Log what you filter -- record which chunks were removed and why. This makes it possible to debug cases where the model gives an incomplete answer because a needed chunk was filtered out.
  • Re-optimize when the query changes -- context that was optimal for one query may be suboptimal for a follow-up. In multi-turn conversations, re-run optimization when the user's intent shifts.

Edge Cases

  • All chunks are highly relevant: When every chunk scores above the threshold, skip filtering and focus on deduplication and ordering. Do not force removal of good content just to hit an arbitrary reduction target.
  • Query covers multiple distinct topics: A complex query like "Compare the return policy and warranty terms" requires context covering both topics. Ensure the coverage validation step checks for both and does not filter all chunks about one topic.
  • Very small context windows (4K tokens): With tight budgets, aggressive compression after optimization may still be needed. Optimize first to remove waste, then compress the remainder if it still exceeds the budget.
  • Rapidly changing source data: In live systems where documents are updated frequently, cached optimization results may become stale. Invalidate and re-optimize when source documents change.
  • Context with mixed content types: When context includes prose, code, tables, and JSON, apply type-specific density scoring -- a 10-line code snippet is typically denser than a 10-line prose paragraph.

© seb1n, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in context-engineering/context-optimization of seb1n/awesome-ai-agent-skills.

Open the folder on GitHubat commit 75865a5

Compare with similar skills

Context Optimization next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Context Optimization compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Context Optimization this skillseb1n/awesome-ai-agent-skills206—~2.9kAutomated safety check: PassMIT
Context DoctorjzOcb/context-doctor119—~642Automated safety check: PassMIT
Caveman Learn Token FixesJuliusBrussee/caveman110k—~2.8kAutomated safety check: PassApache-2.0
OmniRoute Context CLIdiegosouzapw/OmniRoute74k—~1.2kAutomated safety check: PassMIT
Subagent Brief DisciplineLichAmnesia/lich-skills234—~1.6kAutomated safety check: PassMIT
Compact Guidejh941213/my-cc-harness126—~621Automated safety check: PassNone

Similar skills

  • Context Doctor

    jzOcb/context-doctor

    Visualize and diagnose OpenClaw context window usage. An agent skill from jzOcb/context-doctor.

    119 GitHub stars~642 tokensUpdated 6 mo ago
    Agent WorkflowsAuto-check passed
  • Caveman Learn Token Fixes

    JuliusBrussee/caveman

    Acts on a Caveman learn report: reviews ranked token sinks, applies cost-lowering edits one at a time with your consent, and reports what each fix returned.

    110k GitHub stars~2.8k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • OmniRoute Context CLI

    diegosouzapw/OmniRoute

    Manage context engineering configurations, RTK filter sets, and conversation sessions from the CLI. Apply context-relay settings and inspect active context…

    74k GitHub stars~1.2k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Subagent Brief Discipline

    LichAmnesia/lich-skills

    Checks every subagent prompt before spawning, swapping pasted files and context for paths and short summaries and trimming the brief, to avoid multiplied token cost.

    234 GitHub stars~1.6k tokensUpdated 4 mo ago
    Agent WorkflowsAuto-check passed
  • Compact Guide

    jh941213/my-cc-harness

    Context window management and token optimization guide. An agent skill from jh941213/my-cc-harness.

    126 GitHub stars~621 tokensUpdated 2 mo ago
    Agent WorkflowsAuto-check passed
  • Omh Context Budget Review

    rlaope/oh-my-hermes

    [omh] Context window or token budget at risk: plan compact context, token/cost budgets, summarization checkpoints, and overflow recovery before long agent work.

    3.2k GitHub stars~2k tokensUpdated today
    Agent WorkflowsAuto-check passed

More from seb1n/awesome-ai-agent-skills

All 91 skills in this repo
  • Agent Red Teaming

    seb1n/awesome-ai-agent-skills

    Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings.

    206 GitHub stars~2.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Eu AI Act Readiness

    seb1n/awesome-ai-agent-skills

    Build a preliminary, evidence-based EU AI Act readiness assessment across AI-system inventory, territorial scope, operator roles, prohibited-practice screening, risk classification, transparency…

    206 GitHub stars~3.3k tokensUpdated 1 mo ago
    Auto-check passed
  • Human In The Loop

    seb1n/awesome-ai-agent-skills

    Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows.

    206 GitHub stars~2.5k tokensUpdated 1 mo ago
    Auto-check passed
  • MCP Server Building

    seb1n/awesome-ai-agent-skills

    Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests.

    206 GitHub stars~2.5k tokensUpdated 1 mo ago
    Auto-check passed
  • Skill Supply Chain Audit

    seb1n/awesome-ai-agent-skills

    Audit agent skills, plugins, prompts, manifests, scripts, dependencies, and bundled assets for provenance, prompt-injection, permission, execution, exfiltration, persistence, and update risk.

    206 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Spreadsheet Analysis

    seb1n/awesome-ai-agent-skills

    Inspect, profile, clean, reconcile, analyze, visualize, and verify spreadsheet data while preserving formulas, formatting, types, and source files.

    206 GitHub stars~2.5k tokensUpdated 1 mo ago
    Auto-check passed

Questions about Context Optimization

What does Context Optimization do?

Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget. Context Optimization is an agent skill from seb1n/awesome-ai-agent-skills. Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget.

When should I use Context Optimization?

Context Optimization fits situations like: assembled material is noisy; exceeds the useful context budget; use context-ranking for scoring chunks and context-compression for shrinking selected content.

How do I install Context Optimization in Claude Code?

Run `npx skills add seb1n/awesome-ai-agent-skills --skill context-optimization -a claude-code`. Or copy the skill folder (context-engineering/context-optimization in seb1n/awesome-ai-agent-skills) into .claude/skills/context-optimization in your project. Claude Code loads it when a task matches its description.

How do I install Context Optimization in Codex?

Run `npx skills add seb1n/awesome-ai-agent-skills --skill context-optimization -a codex`. Or copy the skill folder (context-engineering/context-optimization in seb1n/awesome-ai-agent-skills) into .agents/skills/context-optimization in your project. Codex loads it when a task matches its description.

Can I use Context Optimization in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add seb1n/awesome-ai-agent-skills --skill context-optimization -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/context-optimization, .gemini/skills/context-optimization, .github/skills/context-optimization and .opencode/skills/context-optimization in your project.

What does Context Optimization need to run?

SKILL.md names no scripts, command-line tools or credentials: Context Optimization is instructions for the agent only.

Does Context Optimization access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Context Optimization safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Context Optimization use?

Context Optimization is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Context Optimization use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Context Optimization?

Skills that share tags, products or a category with Context Optimization: Context Doctor (jzOcb/context-doctor, 119 stars), Caveman Learn Token Fixes (JuliusBrussee/caveman, 110k stars), OmniRoute Context CLI (diegosouzapw/OmniRoute, 74k stars) and Subagent Brief Discipline (LichAmnesia/lich-skills, 234 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Context Optimization?

seb1n (a GitHub user) maintains it in seb1n/awesome-ai-agent-skills, which has 206 GitHub stars. The repository holds 91 skills in this directory. The repository was last updated on August 9, 2026.

Source: seb1n/awesome-ai-agent-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.