Automated summary
This skill helps reduce and manage context-window usage for OpenRouter models through token estimation, model selection, document chunking, and prompt caching.
Strengths
- Provides concrete curl/jq queries to read context_length and per-million-token pricing from the OpenRouter API.
- Includes Python functions for token estimation, safety-margin model selection, and chunking long documents.
- Explains Anthropic prompt caching with ephemeral cache_control to lower costs for repeated static blocks.
- Recommends monitoring prompt_tokens to catch context-limit overruns before they become errors.
Limitations
- The roughly 4-characters-per-token estimate is approximate; exact counting requires tiktoken, which is only referenced.
- The fallback chain and quoted context sizes may become stale as OpenRouter models change.
- The skill focuses on OpenRouter and Anthropic caching rather than universal multi-provider context optimization.
Use it when an OpenRouter application is nearing context limits, risks exceeding a token budget, or needs to process long documents or RAG inputs.
Do not use it if you are not calling OpenRouter or if you need provider-independent context-optimization guidance.
Security analysis
SafeThe skill uses network calls via curl to a public OpenRouter API endpoint for model metadata lookup and Python/Node scripts for local processing. It reads the OPENROUTER_API_KEY from environment but does not exfiltrate, log, or transmit it beyond the expected OpenAI SDK client. No destructive commands, obfuscation, or safety bypasses are present.
No concerns found
How this analysis is madeExamples
Query the OpenRouter models API and compare the context_length and per-million-token prompt price for anthropic/claude-3.5-sonnet, openai/gpt-4o, and google/gemini-2.0-flash-001.Estimate the token count of this conversation and choose an OpenRouter model that fits with an 80% safety margin, using the fallback chain described in the skill.Split this 80,000-character document into 8,000-character chunks with 500-character overlap, analyze each chunk at temperature 0 through OpenRouter, then synthesize the results.name: openrouter-context-optimization description: 'Optimize context window usage for OpenRouter models to reduce cost and improve quality. Use when hitting context limits, managing long conversations, or building RAG systems. Triggers: ''openrouter context'', ''context window'', ''openrouter token limit'', ''reduce tokens openrouter''.
' allowed-tools: Read, Write, Edit, Grep, Bash(python3:), Bash(node:), Bash(curl:), Bash(jq:) version: 1.20.0 license: MIT author: Jeremy Longshore jeremy@intentsolutions.io tags:
- saas
- openrouter
- optimization
- context-window compatibility: Designed for Claude Code, also compatible with Codex and OpenClaw
OpenRouter Context Optimization
Overview
OpenRouter models have varying context windows (4K to 1M+ tokens). Since pricing is per-token, stuffing unnecessary context wastes money and can degrade output quality. This skill covers context window lookup, token estimation, conversation trimming, chunking strategies, and Anthropic prompt caching for large contexts.
Prerequisites
- An OpenRouter API key (
sk-or-v1-...) exported asOPENROUTER_API_KEY— see theopenrouter-install-authskill for setup - Python 3.8+ with the OpenAI SDK and
requestsfor model-metadata lookup;tiktokenfor exact token counting per the references curlandjqto query context windows and pricing from/api/v1/models- Node.js 18+ if you use the TypeScript context-budget calculator in the references
Instructions
- Run the Query Context Limits one-liner — it returns
context_lengthand prompt price per 1M tokens for each candidate model, so you know the real budget before writing code. - Estimate input size (~4 characters per token, or exactly with
tiktokenper the references) and pick a model withselect_model_for_context()from Context-Aware Model Selection — it applies an 80% safety margin and falls back through gpt-4o-mini (128K) → Claude 3.5 Sonnet (200K) → Gemini 2.0 Flash (1M). - Keep long conversations inside budget with
trim_conversation()per Conversation Trimming: system prompt plus the last N messages, with a trim-marker note injected where history was dropped. - For documents that exceed any window, use
chunk_and_process()per Chunking for Large Documents — 8,000-char chunks with 500-char overlap, analyzed independently attemperature=0and then synthesized. - Mark large static blocks with
cache_control: {"type": "ephemeral"}per Prompt Caching for Repeated Context to cut repeated input cost by 90% on Anthropic models. - Monitor
prompt_tokenson every response (Enterprise Considerations) to catch context bloat before it becomes a 400context_length_exceeded.
Query Context Limits
# Check context window for specific models
curl -s https://openrouter.ai/api/v1/models | jq '[.data[] | select(
.id == "anthropic/claude-3.5-sonnet" or
.id == "openai/gpt-4o" or
.id == "google/gemini-2.0-flash-001" or
.id == "meta-llama/llama-3.1-70b-instruct"
) | {id, context_length, prompt_per_M: ((.pricing.prompt|tonumber)*1000000)}]'
Context-Aware Model Selection
import os, requests
from openai import OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
)
# Cache model metadata at startup
MODELS = {m["id"]: m for m in requests.get("https://openrouter.ai/api/v1/models").json()["data"]}
def estimate_tokens(text: str) -> int:
"""Rough estimate: 1 token ~ 4 characters for English text."""
return len(text) // 4
def select_model_for_context(messages: list, preferred: str = "anthropic/claude-3.5-sonnet") -> str:
"""Pick a model that fits the context, falling back to larger windows."""
estimated_tokens = sum(len(m.get("content", "")) for m in messages) // 4
FALLBACK_CHAIN = [
("openai/gpt-4o-mini", 128_000),
("anthropic/claude-3.5-sonnet", 200_000),
("google/gemini-2.0-flash-001", 1_000_000),
]
# Try preferred model first
preferred_ctx = MODELS.get(preferred, {}).get("context_length", 0)
if estimated_tokens < preferred_ctx * 0.8: # 80% safety margin
return preferred
for model_id, ctx in FALLBACK_CHAIN:
if estimated_tokens < ctx * 0.8:
return model_id
raise ValueError(f"Content too large ({estimated_tokens} est. tokens)")
Conversation Trimming
def trim_conversation(
messages: list[dict],
max_tokens: int = 100_000,
keep_system: bool = True,
keep_last_n: int = 4,
) -> list[dict]:
"""Trim conversation history to fit context window.
Strategy: Keep system prompt + last N messages.
If still too large, reduce to last 2 messages.
"""
system = [m for m in messages if m["role"] == "system"] if keep_system else []
non_system = [m for m in messages if m["role"] != "system"]
kept = non_system[-keep_last_n:]
trimmed = non_system[:-keep_last_n] if len(non_system) > keep_last_n else []
total_est = sum(estimate_tokens(m.get("content", "")) for m in system + kept)
if total_est > max_tokens and keep_last_n > 2:
kept = non_system[-2:]
result = system + kept
if trimmed:
summary_note = {
"role": "system",
"content": f"[Previous {len(trimmed)} messages trimmed for context limits]",
}
result = system + [summary_note] + kept
return result
Chunking for Large Documents
def chunk_and_process(document: str, question: str, model: str = "openai/gpt-4o-mini",
chunk_size: int = 8000, overlap: int = 500) -> str:
"""Process a large document in overlapping chunks, then synthesize."""
chunks = []
start = 0
while start < len(document):
chunks.append(document[start:start + chunk_size])
start += chunk_size - overlap
results = []
for i, chunk in enumerate(chunks):
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": f"Analyzing chunk {i+1}/{len(chunks)}."},
{"role": "user", "content": f"Document:\n{chunk}\n\nQuestion: {question}"},
],
max_tokens=1024, temperature=0,
)
results.append(response.choices[0].message.content)
# Synthesize
synthesis = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "Synthesize these partial analyses."},
{"role": "user", "content": f"Question: {question}\n\nResults:\n" + "\n---\n".join(results)},
],
max_tokens=2048, temperature=0,
)
return synthesis.choices[0].message.content
Prompt Caching for Repeated Context
# Anthropic models support prompt caching -- mark large static blocks
# Subsequent requests with same cached block cost 90% less for input tokens
response = client.chat.completions.create(
model="anthropic/claude-3.5-sonnet",
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": large_reference_document, # 50K+ tokens
"cache_control": {"type": "ephemeral"},
}
],
},
{"role": "user", "content": "Summarize section 3."},
],
max_tokens=1024,
)
# First request: cache_creation_input_tokens at 1.25x rate
# Subsequent: cache_read_input_tokens at 0.1x rate (90% savings)
Output
- A jq-formatted listing of model IDs with
context_lengthand per-1M prompt pricing from/api/v1/models - A model ID selected to fit the estimated token count within an 80% safety margin, or a
ValueErrorwhen nothing fits - A trimmed message list containing the system prompt, a
[Previous N messages trimmed for context limits]note, and the most recent turns - A single synthesized answer assembled from per-chunk analyses of an oversized document
Examples
Multi-turn chat with the references' prune_conversation() holding a 2,000-token budget — oldest messages drop as the conversation grows:
[Pruned] 9 -> 7 messages (1876 tokens)
Q: What about class-based decorators?...
Tokens: 412
The pruner always keeps the system message and removes the oldest non-system turns first. More worked examples: references/examples.md.
Error Handling
| Error | Cause | Fix |
|-------|-------|-----|
| 400 context_length_exceeded | Input + max_tokens > model limit | Trim messages or use larger-context model |
| 400 max_tokens too large | max_tokens alone exceeds limit | Reduce max_tokens |
| Slow responses | Very large context | Use streaming; consider chunking |
| Degraded quality | Too much irrelevant context | Trim to relevant content only |
Enterprise Considerations
- Query
/api/v1/modelsat startup to cache context limits -- don't hardcode (they change) - Use
max_tokenson every request to prevent runaway completion costs on large contexts - Implement conversation trimming as middleware so all calls respect limits
- Use Anthropic prompt caching for RAG contexts that repeat across requests (90% input savings)
- Route large-context tasks to cost-effective models (Gemini Flash for 1M context at low cost)
- Monitor
prompt_tokensin responses to detect context bloat before it hits limits
References
- Examples | Errors
- Prompt Caching | Models API
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/openrouter-context-optimization-ms47vpoc' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/openrouter-context-optimization-ms47vpoc/download' --output '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md.part' && mv '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md.part' '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
Environment declared by the author: Designed for Claude Code, also compatible with Codex and OpenClaw
Tools declared by the author (check availability in your agent): Read, Write, Edit, Grep, Bash(python3:*), Bash(node:*), Bash(curl:*), Bash(jq:*)
Original excerpt: Prerequisites
- An OpenRouter API key (
sk-or-v1-...) exported asOPENROUTER_API_KEY— see theopenrouter-install-authskill for setup - Python 3.8+ with the OpenAI SDK and
requestsfor model-metadata lookup;tiktokenfor exact token counting per the references curlandjqto query context windows and pricing from/api/v1/models- Node.js 18+ if you use the TypeScript context-budget calculator in the references
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md' && test -s '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/openrouter-context-optimization' && cp -R '.skill-downloads/openrouter-context-optimization-ms47vpoc' '.claude/skills/openrouter-context-optimization'Codex
test -f '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md' && test -s '.skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/openrouter-context-optimization' && cp -R '.skill-downloads/openrouter-context-optimization-ms47vpoc' '.agents/skills/openrouter-context-optimization'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/openrouter-context-optimization-ms47vpoc'openskills read 'openrouter-context-optimization-ms47vpoc'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/openrouter-context-optimization-ms47vpoc/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
Create Interactive Maps with kepler.gl
Data & AI
Create interactive map visualizations and export standalone HTML using the keplergl Python package. Use to plot geospatial data from DataFrames, GeoJSON, or CSV.
Agent-Driven Parameter Optimization
Data & AI
Guide for optimizing configurable systems with a measurable objective, using bounded trials and evidence-based recommendations.
ICP Visitor Outreach
Data & AI
Identify signed-up users matching the ideal customer profile but stalled, and draft personalized outreach to re-engage them.