Skip to content
Automation
Skill

/context-window-management

Strategies for managing LLM context windows including

From plugin
lihongwei-cn
5200 skills1 agent
Install
$ npx -y skills add LiHongwei-cn/lihongwei-cn --skill context-window-management --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/context-window-management

Context preview

The summary Claude sees to decide when to auto-load this skill.

Strategies for managing LLM context windows including

SKILL.md

context-window-management.SKILL.md
name: context-window-management
description: Strategies for managing LLM context windows including
  summarization, trimming, routing, and avoiding context rot
risk: unknown
source: vibeship-spawner-skills (Apache 2.0)
date_added: 2026-02-27

Context Window Management

Strategies for managing LLM context windows including summarization, trimming, routing, and avoiding context rot

Capabilities

  • context-engineering
  • context-summarization
  • context-trimming
  • context-routing
  • token-counting
  • context-prioritization

Prerequisites

  • Knowledge: LLM fundamentals, Tokenization basics, Prompt engineering
  • Skills_recommended: prompt-engineering

Scope

  • Does_not_cover: RAG implementation details, Model fine-tuning, Embedding models
  • Boundaries: Focus is context optimization, Covers strategies not specific implementations

Ecosystem

Primary_tools

  • tiktoken - OpenAI's tokenizer for counting tokens
  • LangChain - Framework with context management utilities
  • Claude API - 200K+ context with caching support

Patterns

Tiered Context Strategy

Different strategies based on context size

**When to use**: Building any multi-turn conversation system

interface ContextTier { maxTokens: number; strategy: 'full' | 'summarize' | 'rag'; model: string; }

const TIERS: ContextTier[] = [ { maxTokens: 8000, strategy: 'full', model: 'claude-3-haiku' }, { maxTokens: 32000, strategy: 'full', model: 'claude-3-5-sonnet' }, { maxTokens: 100000, strategy: 'summarize', model: 'claude-3-5-sonnet' }, { maxTokens: Infinity, strategy: 'rag', model: 'claude-3-5-sonnet' } ];

async function selectStrategy(messages: Message[]): ContextTier { const tokens = await countTokens(messages);

for (const tier of TIERS) { if (tokens <= tier.maxTokens) { return tier; } } return TIERS[TIERS.length - 1]; }

async function prepareContext(messages: Message[]): PreparedContext { const tier = await selectStrategy(messages);

switch (tier.strategy) { case 'full': return { messages, model: tier.model };

case 'summarize': const summary = await summarizeOldMessages(messages); return { messages: [summary, ...recentMessages(messages)], model: tier.model };

case 'rag': const relevant = await retrieveRelevant(messages); return { messages: [...relevant, ...recentMessages(messages)], model: tier.model }; } }

Serial Position Optimization

Place important content at start and end

**When to use**: Constructing prompts with significant context

// LLMs weight beginning and end more heavily // Structure prompts to leverage this

function buildOptimalPrompt(components: { systemPrompt: string; criticalContext: string; conversationHistory: Message[]; currentQuery: string; }): string { // START: System instructions (always first) const parts = [components.systemPrompt];

// CRITICAL CONTEXT: Right after system (high primacy) if (components.criticalContext) { parts.push(`## Key Context\n${components.criticalContext}`); }

// MIDDLE: Conversation history (lower weight) // Summarize if long, keep recent messages full const history = components.conversationHistory; if (history.length > 10) { const oldSummary = summarize(history.slice(0, -5)); const recent = history.slice(-5); parts.push(`## Earlier Conversation (Summary)\n${oldSummary}`); parts.push(`## Recent Messages\n${formatMessages(recent)}`); } else { parts.push(`## Conversation\n${formatMessages(history)}`); }

// END: Current query (high recency) // Restate critical requirements here parts.push(`## Current Request\n${components.currentQuery}`);

// FINAL: Reminder of key constraints parts.push(`Remember: ${extractKeyConstraints(components.systemPrompt)}`);

return parts.join('\n\n'); }

Intelligent Summarization

Summarize by importance, not just recency

**When to use**: Context exceeds optimal size

interface MessageWithMetadata extends Message { importance: number; // 0-1 score hasCriticalInfo: boolean; // User preferences, decisions referenced: boolean; // Was this referenced later? }

async function smartSummarize( messages: MessageWithMetadata[], targetTokens: number ): Message[] { // Sort by importance, preserve order for tied scores const sorted = [...messages].sort((a, b) => (b.importance + (b.hasCriticalInfo ? 0.5 : 0) + (b.referenced ? 0.3 : 0)) - (a.importance + (a.hasCriticalInfo ? 0.5 : 0) + (a.referenced ? 0.3 : 0)) );

const keep: Message[] = []; const summarizePool: Message[] = []; let currentTokens = 0;

for (const msg of sorted) { const msgTokens = await countTokens([msg]); if (currentTokens + msgTokens < targetTokens * 0.7) { keep.push(msg); currentTokens += msgTokens; } else { summarizePool.push(msg); } }

// Summarize the low-importance messages if (summarizePool.length > 0) { const summary = await llm.complete(` Summarize these messages, preserving:

  • Any user preferences or decisions
  • Key facts that might be referenced later
  • The overall flow of conversation

Messages: ${formatMessages(summarizePool)} `);

keep.unshift({ role: 'system', content: `[Earlier context: ${summary}]` }); }

// Restore original order return keep.sort((a, b) => a.timestamp - b.timestamp); }

Token Budget Allocation

Allocate token budget across context components

**When to use**: Need predictable context management

interface TokenBudget { system: number; // System prompt criticalContext: number; // User prefs, key info history: number; // Conversation history query: number;

Read more
Ships withlihongwei-cn

MUNDO - THE EMPEROR. Complete AI orchestration system with 1208 skills, 25 capability modules, self-evolving, collective consciousness. GitHub Actions 24/7 automation.

Get the whole plugin
Stats
5
Stars
1
Forks
Maintained
Maintenance
Python
Language
MIT
License
1mo ago
Last commit
4mo ago
Created

Repo: LiHongwei-cn/lihongwei-cn

Other skills on lihongwei-cn.

cheat-on-content
Skill

cheat-on-content

给所有想把"感觉"变成可校准预测的内容创作者。**方法论通用**——打分 → 盲预测 → T+3d 复盘 → 进化 rubric 的循环适用任何能被量化(播放 / 阅读 / 收听 / 点击)的内容。**rubric 是循环的内容,不是循环本身**——当前内置一份观点视频 rubric(参考博主 25+…

cheat-bump
Skill

cheat-bump

提议并执行 rubric 或 bucket 升级。两种模式:**完整 rubric bump**(最高风险动作,5 步强制 + 跨模型审核)和 **--bucket-only 轻量重校**(只换 bucket 边界,不动 rubric 公式)。**Phase 2 强制走 cheat-score-blind…

cheat-init
Skill

cheat-init

cheat-on-content 的首次 onboarding 与脚手架创建器。统一流程——所有用户都走相同 5 阶段闭环,唯一区别是"发过视频的人"会在 init 时多一步:抓取已有视频建立历史 context(用于后续 cheat-seed 给更贴合的选题、更准的…

cheat-migrate
Skill

cheat-migrate

把老用户的 .cheat-state.json 升级到当前 schema_version。读 migrations/registry.md 算迁移链,按顺序应用每一步迁移文件。幂等:跑两次结果一样。失败停在中间版本不前进。触发词:"迁移"/"升级 state"/"migrate"/"我的 state…

cheat-persona
Skill

cheat-persona

从复盘评论数据派生 / 刷新账号的受众画像,写入 audience.md。这是和 rubric 平行的第二个派生物——rubric 答"怎么打分",persona 答"谁在看"。cheat-seed 选题 / 写稿时读它。**audience.md 含实绩信号,cheat-score-blind…