Caching Architecture
majiayu000/litellm-rs
LiteLLM-RS response caching architecture. An agent skill from majiayu000/litellm-rs.
Agent skill
by jeremylongshore in jeremylongshore/tons-of-skills-marketplace
Implement caching for OpenRouter API responses to reduce cost and latency.
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-caching-strategy --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/openrouter-caching-strategy .claude/skills/openrouter-caching-strategy && rm -rf skills-srcUse ~/.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/
Install the "openrouter-caching-strategy" agent skill from https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategy into .claude/skills/openrouter-caching-strategy/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "openrouter-caching-strategy", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategyType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-caching-strategy --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .agents/skills && cp -r skills-src/skills/.curated/openrouter-caching-strategy .agents/skills/openrouter-caching-strategy && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "openrouter-caching-strategy" agent skill from https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategy into .agents/skills/openrouter-caching-strategy/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "openrouter-caching-strategy", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-caching-strategy --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/skills/.curated/openrouter-caching-strategy .cursor/skills/openrouter-caching-strategy && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "openrouter-caching-strategy" agent skill from https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategy into .cursor/skills/openrouter-caching-strategy/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "openrouter-caching-strategy", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/jeremylongshore/tons-of-skills-marketplace.git --path skills/.curated/openrouter-caching-strategy--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-caching-strategy --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/skills/.curated/openrouter-caching-strategy .gemini/skills/openrouter-caching-strategy && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "openrouter-caching-strategy" agent skill from https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategy into .gemini/skills/openrouter-caching-strategy/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "openrouter-caching-strategy", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-caching-strategyInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .github/skills && cp -r skills-src/skills/.curated/openrouter-caching-strategy .github/skills/openrouter-caching-strategy && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "openrouter-caching-strategy" agent skill from https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategy into .github/skills/openrouter-caching-strategy/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "openrouter-caching-strategy", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-caching-strategy --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/skills/.curated/openrouter-caching-strategy .opencode/skills/openrouter-caching-strategy && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "openrouter-caching-strategy" agent skill from https://github.com/jeremylongshore/tons-of-skills-marketplace/tree/main/skills/.curated/openrouter-caching-strategy into .opencode/skills/openrouter-caching-strategy/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "openrouter-caching-strategy", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
openrouter-caching-strategyImplement caching for OpenRouter API responses to reduce cost and latency.
Openrouter Caching Strategy is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement caching for OpenRouter API responses to reduce cost and latency. Use when optimizing repeat queries, building RAG systems, or reducing API spend. Triggers: 'openrouter cache', 'cache llm responses', 'openrouter caching', 'reduce openrouter cost'.
Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 9 other files, including reference files (for example `references/cache-invalidation.md`, `references/caching-strategies.md` and `references/cost-savings-analysis.md`). Compatibility notes: Designed for Claude Code
It sits in AI & LLM Engineering, covering Model routing and gateways and Caching. It works with OpenRouter and Redis. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.
6 steps, taken from the first numbered list in SKILL.md.
Read from SKILL.md and the folder at commit cfae287. It shows what the files ask for, not the result of running them.
Pre-approves these tools, so the agent can use them without asking each time:
ReadWriteEditGrepBash(python3:*)Bash(node:*)From allowed-tools in the SKILL.md frontmatter.
No scripts in the folder and no shell commands in SKILL.md (its code samples are python).
From the folder's file list and the shell code blocks in SKILL.md.
Hosts in commands or code, which the agent is likely to contact:
openrouter.aiFrom URLs in SKILL.md, links to its own repository left out.
Names these keys or tokens, usually read from environment variables:
OPENROUTER_API_KEYFrom names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Designed for Claude Code
From compatibility in the SKILL.md frontmatter.
Openrouter Caching Strategy loads about 2.4k tokens when it runs, and up to ~6.4k if it reads all its reference files. Until then it costs about 71 tokens; SKILL.md has 580 words of instructions outside code blocks.
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.
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.
The full file from jeremylongshore/tons-of-skills-marketplace at commit cfae287, republished under its MIT licence (© jeremylongshore). 580 words, ~2,385 tokens.
.claude/skills/openrouter-caching-strategy/SKILL.md (or your agent's skills folder). This skill also uses 8 other files; get the full folder from GitHub.OpenRouter charges per token, so caching identical or similar requests can dramatically cut costs. Deterministic requests (temperature=0) with the same model and messages produce identical outputs -- these are safe to cache. This skill covers in-memory caching, persistent caching with TTL, and Anthropic prompt caching via OpenRouter.
sk-or-v1-...) exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setupredis client package for the persistent cache; Node.js 18+ with the OpenAI SDK for the TypeScript variant in the referenceslocalhost:6379 for Persistent Cache with Redis (the in-memory LLMCache needs no infrastructure)temperature=0temperature=0); non-zero temperatures produce different outputs each call and must never be cached.LLMCache plus cached_completion() gives you TTL expiry and hit/miss counters in a single process.redis_cached_completion() stores results under or:<sha256> keys with r.setex TTL expiry and falls through to a direct API call on a miss.:floor), messages, temperature, max_tokens, and top_p; exclude stream and the HTTP-Referer/X-Title headers.cache_control: {"type": "ephemeral"} per Anthropic Prompt Caching via OpenRouter — cache reads bill at 0.1x the input rate.import os, hashlib, json, time
from typing import Optional
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"},
)
class LLMCache:
def __init__(self, ttl_seconds: int = 3600):
self._cache: dict[str, tuple[dict, float]] = {}
self._ttl = ttl_seconds
self.hits = 0
self.misses = 0
def _key(self, model: str, messages: list, **kwargs) -> str:
blob = json.dumps({"model": model, "messages": messages, **kwargs}, sort_keys=True)
return hashlib.sha256(blob.encode()).hexdigest()
def get(self, model: str, messages: list, **kwargs) -> Optional[dict]:
k = self._key(model, messages, **kwargs)
if k in self._cache:
data, ts = self._cache[k]
if time.time() - ts < self._ttl:
self.hits += 1
return data
del self._cache[k]
self.misses += 1
return None
def set(self, model: str, messages: list, response: dict, **kwargs):
k = self._key(model, messages, **kwargs)
self._cache[k] = (response, time.time())
cache = LLMCache(ttl_seconds=1800)
def cached_completion(messages, model="anthropic/claude-3.5-sonnet", **kwargs):
"""Only cache deterministic requests (temperature=0)."""
kwargs.setdefault("temperature", 0)
kwargs.setdefault("max_tokens", 1024)
cached = cache.get(model, messages, **kwargs)
if cached:
return cached
response = client.chat.completions.create(model=model, messages=messages, **kwargs)
result = {
"content": response.choices[0].message.content,
"model": response.model,
"usage": {"prompt": response.usage.prompt_tokens, "completion": response.usage.completion_tokens},
}
cache.set(model, messages, result, **kwargs)
return resultimport redis, json, hashlib
r = redis.Redis(host="localhost", port=6379, db=0)
def redis_cached_completion(messages, model="openai/gpt-4o-mini", ttl=3600, **kwargs):
"""Cache in Redis with automatic TTL expiry."""
kwargs["temperature"] = 0 # Must be deterministic
key = f"or:{hashlib.sha256(json.dumps({'m': model, 'msgs': messages, **kwargs}, sort_keys=True).encode()).hexdigest()}"
cached = r.get(key)
if cached:
return json.loads(cached)
response = client.chat.completions.create(model=model, messages=messages, **kwargs)
result = {
"content": response.choices[0].message.content,
"model": response.model,
"tokens": response.usage.prompt_tokens + response.usage.completion_tokens,
}
r.setex(key, ttl, json.dumps(result))
return resultAnthropic models on OpenRouter support prompt caching -- large system prompts are cached server-side, reducing input cost by 90% on cache hits.
# Mark large static content blocks with cache_control
response = client.chat.completions.create(
model="anthropic/claude-3.5-sonnet",
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": "You are an expert. Here is the full source:\n" + large_context,
"cache_control": {"type": "ephemeral"}, # Cache this block
}
],
},
{"role": "user", "content": "What does the main() function do?"},
],
max_tokens=1024,
)
# First call: cache_creation_input_tokens charged at 1.25x
# Subsequent: cache_read_input_tokens charged at 0.1x (90% savings)def cache_key(model: str, messages: list, **params) -> str:
"""Deterministic cache key. Include everything that affects output.
Include: model ID (with variant like :floor), messages, temperature,
max_tokens, top_p, transforms, provider routing.
Exclude: stream (doesn't affect content), HTTP-Referer, X-Title.
"""
canonical = json.dumps({
"model": model, "messages": messages,
"temperature": params.get("temperature", 0),
"max_tokens": params.get("max_tokens"),
"top_p": params.get("top_p"),
}, sort_keys=True)
return hashlib.sha256(canonical.encode()).hexdigest()| Trigger | Action | Why |
|---|---|---|
| Model version update | Flush keys for that model | New version may give different outputs |
| System prompt change | Flush all keys | Output semantics changed |
| TTL expiry | Automatic eviction | Prevents stale data |
| Manual purge | r.delete(key) or clear by prefix | Debugging or policy change |
{"content", "model", "usage"} from the in-memory cache or {"content", "model", "tokens"} from Redisor:<sha256-of-canonical-request> that expire automatically via TTLhit_rate figure you can use to justify the caching infrastructurecache_creation_input_tokens billed at 1.25x on the first call and cache_read_input_tokens at 0.1x (90% savings) on subsequent hitsTwo identical deterministic calls through the ResponseCache from the references — the second returns instantly from cache:
result1 = cached_completion("What is Python?") # [Cache MISS] key=3f8a92c1... (stored)
result2 = cached_completion("What is Python?") # [Cache HIT] key=3f8a92c1...
print(f"Hit rate: {cache.hit_rate:.0%}") # Hit rate: 50%More worked examples, including a TypeScript Redis-style cache: references/examples.md.
| Error | Cause | Fix |
|---|---|---|
| Stale cache response | TTL too long | Reduce TTL or version cache keys |
| Cache miss storm | Cold start or invalidation | Warm cache with common queries at deploy |
| Redis connection error | Redis down | Fall through to direct API call |
| Non-deterministic cache | temperature > 0 cached | Only cache when temperature=0 |
temperature=0) -- non-zero temperatures produce different outputs each time© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
SKILL.md and 8 other files (references) in skills/.curated/openrouter-caching-strategy of jeremylongshore/tons-of-skills-marketplace.
Open the folder on GitHubat commit cfae287
Openrouter Caching Strategy 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.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Openrouter Caching Strategy this skilljeremylongshore/tons-of-skills-marketplace | 2.8k | — | ~2.4k | Automated safety check: Pass | MIT | |
| Caching Architecturemajiayu000/litellm-rs | 118 | — | ~2k | Automated safety check: Pass | MIT | |
| Embeddings via 9Routerdecolua/9router | 31k | — | ~604 | Automated safety check: Pass | MIT | |
| FreeRide Free Model ManagerShaivpidadi/FreeRide | 238 | 2 repos | ~1.1k | Automated safety check: Pass | None | |
| Using Ccproxy APIstarbaser/ccproxy | 350 | — | ~4k | Automated safety check: Pass | Custom licence | |
| LLM GatewayBagelHole/DevOps-Security-Agent-Skills | 1.2k | — | ~2k | Automated safety check: Pass | MIT |
majiayu000/litellm-rs
LiteLLM-RS response caching architecture. An agent skill from majiayu000/litellm-rs.
decolua/9router
Generates vector embeddings through the 9Router /v1/embeddings endpoint, using models from providers such as OpenAI, Gemini, Mistral and Voyage for RAG and semantic search.
Shaivpidadi/FreeRide
Configures OpenClaw to use free OpenRouter models, setting the best one as primary and adding ranked fallbacks so rate limits do not interrupt work.
starbaser/ccproxy
Guides users through ccproxy as an OpenAI-compatible and Anthropic-compatible LLM API server with SDK integration, OAuth authentication, sentinel key substitution, model routing, and troubleshooting.
BagelHole/DevOps-Security-Agent-Skills
Deploy an API gateway for LLM traffic with load balancing, rate limiting, key management, semantic caching, fallback routing, and cost tracking.
starbaser/ccproxy
Operates the ccproxy inspector MITM system for intercepting, inspecting, and transforming LLM API traffic.
jeremylongshore/tons-of-skills-marketplace
Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.
jeremylongshore/tons-of-skills-marketplace
Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.
jeremylongshore/tons-of-skills-marketplace
Execute proactive auto-loading: automatically detects and loads agents.md files.
jeremylongshore/tons-of-skills-marketplace
Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.
jeremylongshore/tons-of-skills-marketplace
Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.
jeremylongshore/tons-of-skills-marketplace
Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.
Works with
Categories
Implement caching for OpenRouter API responses to reduce cost and latency. Openrouter Caching Strategy is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement caching for OpenRouter API responses to reduce cost and latency.
Openrouter Caching Strategy fits situations like: optimizing repeat queries; building RAG systems; reducing API spend.
Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a claude-code`. Or copy the skill folder (skills/.curated/openrouter-caching-strategy in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/openrouter-caching-strategy in your project. Claude Code loads it when a task matches its description.
Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a codex`. Or copy the skill folder (skills/.curated/openrouter-caching-strategy in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/openrouter-caching-strategy in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-caching-strategy -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/openrouter-caching-strategy, .gemini/skills/openrouter-caching-strategy, .github/skills/openrouter-caching-strategy and .opencode/skills/openrouter-caching-strategy in your project.
Going by SKILL.md and its folder, Openrouter Caching Strategy needs credentials named OPENROUTER_API_KEY. Our summary lists: Python 3; Node.js; A credential in OPENROUTER_API_KEY. Its frontmatter pre-approves these tools: Read, Write, Edit, Grep, Bash(python3:*), Bash(node:*). Compatibility (from SKILL.md): Designed for Claude Code.
SKILL.md names 1 domain. In commands or code: openrouter.ai; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.
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.
Openrouter Caching Strategy is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.
About 2.4k tokens (SKILL.md is roughly 9.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 4k tokens, read only when the agent opens those files.
Skills that share tags, products or a category with Openrouter Caching Strategy: Caching Architecture (majiayu000/litellm-rs, 118 stars), Embeddings via 9Router (decolua/9router, 31k stars), FreeRide Free Model Manager (Shaivpidadi/FreeRide, 238 stars) and Using Ccproxy API (starbaser/ccproxy, 350 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,827 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 10, 2026.
Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.