[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6F8D9NTHNG4EQV96F930KEG":3,"skill-same:01M6F8D9NTHNG4EQV96F930KEG":78},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":44,"linkOnly":45,"markdownContent":46,"markdownBody":47,"frontMatter":48,"refName":28,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":63,"install":64,"resources":77},"01M6F8D9NTHNG4EQV96F930KEG","llm-caching",null,"Implement multi-layer LLM caching with exact match, semantic similarity, and provider-side prompt caching.","boisenoise\u002Fskills-collections","boisenoise","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F193180?v=4","01M6CDBDQK6BDN55ZMA6B6PKBM","01M6CDBDVSJ3JPTBYN26FZ7TZK",13,"MIT","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-llm-caching\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43],"llm caching","caching","agent-skills","2026","layer","relevant","helper","scripts","critical","platform","main","community","provider","security","only","environment","prompt","access","devops-security","prompt caching","kubectl","ci","runners","license","git","implement","2026-11-10 10:12:30",false,"---\nname: llm-caching\ndescription: Implement multi-layer LLM caching with exact match, semantic similarity,\n  and provider-side prompt caching.\ncategory: devops\nrisk: critical\nsource: https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills\nsource_repo: BagelHole\u002FDevOps-Security-Agent-Skills\nsource_type: community\ndate_added: '2026-09-20'\nlicense: MIT\nlicense_source: https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills\u002Fblob\u002Fmain\u002FLICENSE\ncompatibility: Requires the relevant platform CLIs (kubectl, helm, terraform, git,\n  CI runners) and authorized access to the target environment. Docs-only; helper scripts\n  and templates not bundled.\nmetadata:\n  author: devops-skills\n  version: '1.0'\n---\n\n# LLM Caching\n\nCut LLM costs and latency with exact match, semantic, and provider-side caching layers.\n\n## When to Use This Skill\n\nUse this skill when:\n- The same or similar queries are asked repeatedly (FAQ bots, support tools)\n- LLM API costs are growing and you need immediate savings\n- Serving high request volumes where repeated queries cause bottlenecks\n- Implementing prompt caching for long system prompts (Anthropic\u002FOpenAI)\n- Building offline-capable AI features that need response persistence\n\n## Caching Layers\n\nCache examples are incomplete until authorization\u002Fdata boundaries are included. Partition by tenant\u002Fuser access scope and include model revision, system\u002Fdeveloper prompts, conversation\u002Ftool context, parameters, locale and source\u002Fpolicy version in keys or eligibility filters. Never serve a privileged cached answer across users merely because queries are similar. Hashing prompts is not encryption: restrict\u002Fencrypt stored queries\u002Fresults, honor deletion\u002Fretention and invalidate when permissions\u002Fdata change. Avoid semantic reuse for sensitive or time-dependent answers unless evaluated false-hit risk is acceptable. Similarity thresholds\u002Flatencies\u002Fsavings are examples, not calibrated guarantees. Cache warming is paid generation: bound concurrency, requests and budget before running.\n\n```\nRequest → Exact Cache → Semantic Cache → Provider Cache → LLM API\n             ↓ hit            ↓ hit             ↓ hit\n           instant          ~5ms           50-80% cheaper\n```\n\n## Layer 1: Exact Match Cache (Redis)\n\n```python\nimport hashlib\nimport json\nimport redis\nfrom openai import OpenAI\n\nr = redis.Redis(host=\"localhost\", port=6379, decode_responses=True)\nclient = OpenAI()\n\ndef build_cache_key(model: str, messages: list, temperature: float) -> str:\n    \"\"\"Deterministic key from request parameters.\"\"\"\n    payload = json.dumps({\n        \"model\": model,\n        \"messages\": messages,\n        \"temperature\": temperature,\n    }, sort_keys=True)\n    return f\"llm:exact:{hashlib.sha256(payload.encode()).hexdigest()}\"\n\ndef cached_completion(model: str, messages: list, temperature: float = 0.0,\n                      ttl: int = 3600) -> dict:\n    key = build_cache_key(model, messages, temperature)\n\n    # Check cache\n    if cached := r.get(key):\n        return json.loads(cached)\n\n    # Call API\n    response = client.chat.completions.create(\n        model=model, messages=messages, temperature=temperature\n    )\n    result = response.model_dump()\n\n    # Cache only eligible responses; temperature 0 does not guarantee determinism.\n    if temperature == 0.0:\n        r.setex(key, ttl, json.dumps(result))\n\n    return result\n```\n\n## Layer 2: Semantic Cache (GPTCache)\n\n```python\nfrom gptcache import cache, Config\nfrom gptcache.adapter import openai\nfrom gptcache.embedding import Onnx\nfrom gptcache.manager import CacheBase, VectorBase, get_data_manager\nfrom gptcache.similarity_evaluation.distance import SearchDistanceEvaluation\n\n# Configure GPTCache with Qdrant backend\ndef init_gptcache(cache_obj, llm: str):\n    onnx = Onnx()                              # local embedding model\n    data_manager = get_data_manager(\n        CacheBase(\"redis\"),                    # metadata store\n        VectorBase(\"qdrant\",\n                   host=\"localhost\",\n                   port=6333,\n                   collection_name=f\"llm-cache-{llm}\",\n                   dimension=onnx.dimension),\n    )\n    cache_obj.init(\n        embedding_func=onnx.to_embeddings,\n        data_manager=data_manager,\n        similarity_evaluation=SearchDistanceEvaluation(),\n        config=Config(similarity_threshold=0.80),  # 80% similarity = cache hit\n    )\n\ncache.set_openai_key()\ninit_gptcache(cache, \"gpt-4o-mini\")\n\n# Now openai calls are automatically cached\nresponse = openai.ChatCompletion.create(\n    model=\"gpt-4o-mini\",\n    messages=[{\"role\": \"user\", \"content\": \"What is machine learning?\"}],\n)\n# Second call with similar question (\"Explain machine learning\") → cache hit\n```\n\n## Custom Semantic Cache (Illustrative)\n\n```python\nfrom sentence_transformers import SentenceTransformer\nfrom qdrant_client import QdrantClient\nfrom qdrant_client.models import Distance, VectorParams, PointStruct, Filter, FieldCondition, Range\nimport numpy as np\nimport uuid\nimport time\n\nembed_model = SentenceTransformer(\"BAAI\u002Fbge-small-en-v1.5\")  # fast, 33M params\nqdrant = QdrantClient(\"http:\u002F\u002Flocalhost:6333\")\n\nCACHE_COLLECTION = \"semantic-cache\"\nSIMILARITY_THRESHOLD = 0.88\nCACHE_TTL_SECONDS = 86400  # 24h\n\n# Create collection once\nqdrant.create_collection(\n    collection_name=CACHE_COLLECTION,\n    vectors_config=VectorParams(size=384, distance=Distance.COSINE),\n    on_disk_payload=True,\n)\n\ndef semantic_cache_lookup(query: str, model: str) -> str | None:\n    embedding = embed_model.encode(query).tolist()\n    results = qdrant.query_points(\n        collection_name=CACHE_COLLECTION,\n        query=embedding,\n        query_filter=Filter(must=[\n            FieldCondition(key=\"model\", match={\"value\": model}),\n            FieldCondition(key=\"expires_at\", range=Range(gte=time.time())),\n        ]),\n        limit=1,\n        score_threshold=SIMILARITY_THRESHOLD,\n    )\n    if results.points:\n        return results.points[0].payload[\"response\"]\n    return None\n\ndef semantic_cache_store(query: str, response: str, model: str):\n    embedding = embed_model.encode(query).tolist()\n    qdrant.upsert(\n        collection_name=CACHE_COLLECTION,\n        points=[PointStruct(\n            id=str(uuid.uuid4()),\n            vector=embedding,\n            payload={\n                \"query\": query,\n                \"response\": response,\n                \"model\": model,\n                \"created_at\": time.time(),\n                \"expires_at\": time.time() + CACHE_TTL_SECONDS,\n            },\n        )],\n    )\n\ndef smart_llm_call(query: str, model: str = \"gpt-4o-mini\") -> dict:\n    # 1. Semantic lookup\n    if cached_response := semantic_cache_lookup(query, model):\n        return {\"response\": cached_response, \"source\": \"semantic_cache\", \"cost\": 0}\n\n    # 2. LLM call\n    response = client.chat.completions.create(\n        model=model,\n        messages=[{\"role\": \"user\", \"content\": query}],\n    )\n    text = response.choices[0].message.content\n    cost = litellm.completion_cost(response)\n\n    # 3. Store in cache\n    semantic_cache_store(query, text, model)\n\n    return {\"response\": text, \"source\": \"llm_api\", \"cost\": cost}\n```\n\n## Gateway-Level Semantic Cache\n\nIf LLM traffic already goes through a gateway (see `llm-gateway`), the semantic cache can live there instead of in each application. LiteLLM's `cache: true` setting is one option; Bifrost's `semantic_cache` plugin is another. Bifrost checks an exact-match hash first and runs the vector similarity search only on a miss. It needs a vector store (RediSearch-compatible Redis\u002FValkey, Weaviate, Qdrant or Pinecone) and an embedding model for the semantic path, and it only caches requests that carry a cache key (the `x-bf-cache-key` header, or a configured `default_cache_key`).\n\n```json\n{\n  \"vector_store\": { \"enabled\": true, \"type\": \"redis\", \"config\": { \"addr\": \"redis:6379\" } },\n  \"plugins\": [{\n    \"enabled\": true,\n    \"name\": \"semantic_cache\",\n    \"config\": {\n      \"provider\": \"openai\",\n      \"embedding_model\": \"text-embedding-3-small\",\n      \"dimension\": 1536,\n      \"threshold\": 0.85,\n      \"ttl\": \"1h\"\n    }\n  }]\n}\n```\n\n## Layer 3: Provider-Side Prompt Caching\n\n```python\n# Anthropic — cache long system prompts (saves 90% on cached input tokens)\nimport anthropic\n\nanthropic_client = anthropic.Anthropic()\n\n# Long system prompt — mark for caching\nSYSTEM_PROMPT = open(\"knowledge-base.txt\").read()  # e.g., 50k tokens\n\ndef call_with_prompt_cache(user_question: str) -> str:\n    response = anthropic_client.messages.create(\n        model=\"claude-sonnet-4-6\",\n        max_tokens=1024,\n        system=[\n            {\"type\": \"text\", \"text\": \"You are a helpful assistant.\"},\n            {\n                \"type\": \"text\",\n                \"text\": SYSTEM_PROMPT,\n                \"cache_control\": {\"type\": \"ephemeral\"},  # cache this block\n            }\n        ],\n        messages=[{\"role\": \"user\", \"content\": user_question}],\n    )\n    # Log cache efficiency\n    usage = response.usage\n    cache_savings = usage.cache_read_input_tokens * 0.9  # 90% discount on cached\n    print(f\"Cache hits: {usage.cache_read_input_tokens} tokens \"\n          f\"(saved ~${cache_savings * 3.0 \u002F 1_000_000:.4f})\")\n    return response.content[0].text\n\n# OpenAI — automatic for repeated prefixes (≥1,024 tokens)\n# No code change needed; cached tokens appear in usage.prompt_tokens_details\nresponse = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    messages=[\n        {\"role\": \"system\", \"content\": LONG_SYSTEM_PROMPT},  # auto-cached\n        {\"role\": \"user\", \"content\": user_question},\n    ]\n)\ncached = response.usage.prompt_tokens_details.cached_tokens\nprint(f\"OpenAI cached {cached} tokens\")\n```\n\n## Cache Warming\n\n```python\nasync def warm_cache(common_queries: list[str], model: str):\n    \"\"\"Pre-populate cache with known frequent queries.\"\"\"\n    import asyncio\n    from openai import AsyncOpenAI\n\n    aclient = AsyncOpenAI()\n\n    async def warm_single(query: str):\n        if not semantic_cache_lookup(query, model):\n            response = await aclient.chat.completions.create(\n                model=model,\n                messages=[{\"role\": \"user\", \"content\": query}],\n            )\n            text = response.choices[0].message.content\n            semantic_cache_store(query, text, model)\n            print(f\"Warmed: {query[:50]}...\")\n\n    await asyncio.gather(*[warm_single(q) for q in common_queries])\n\n# Warm on startup\nimport asyncio\nasyncio.run(warm_cache(FREQUENT_QUERIES, \"gpt-4o-mini\"))\n```\n\n## Cache Metrics\n\n```python\nfrom prometheus_client import Counter, Histogram\n\ncache_hits = Counter(\"llm_cache_hits_total\", \"Cache hits\", [\"cache_layer\", \"model\"])\ncache_misses = Counter(\"llm_cache_misses_total\", \"Cache misses\", [\"model\"])\ncache_savings_usd = Counter(\"llm_cache_savings_usd_total\", \"USD saved by cache\", [\"model\"])\n\n# Use in your smart_llm_call function\nif source == \"semantic_cache\":\n    cache_hits.labels(cache_layer=\"semantic\", model=model).inc()\n    cache_savings_usd.labels(model=model).inc(estimated_cost)\nelse:\n    cache_misses.labels(model=model).inc()\n```\n\n## Redis Configuration for LLM Caching\n\nThese entries belong in redis.conf, not a shell. Verify memory limits and whether disabling persistence is appropriate for the actual Redis instance; do not overwrite unrelated workload policy.\n\n```text\n# redis.conf tuning for LLM cache workload\nmaxmemory 8gb\nmaxmemory-policy allkeys-lru    # evict least-recently-used when full\nsave \"\"                          # disable persistence (cache is ephemeral)\nappendonly no\ntcp-keepalive 60\n```\n\n## Common Issues\n\n| Issue | Cause | Fix |\n|-------|-------|-----|\n| Low cache hit rate | Threshold too strict | Lower `SIMILARITY_THRESHOLD` to 0.82–0.85 |\n| Stale cached responses | Long TTL | Use topic-specific TTLs; invalidate on data updates |\n| Cache serving wrong answers | Threshold too loose | Raise threshold or add model-name filtering |\n| Redis OOM | No eviction policy | Set `maxmemory` + `allkeys-lru` |\n| Slow semantic lookup | Large cache collection | Add payload index on `model` + `expires_at` |\n\n## Best Practices\n\n- Start with exact cache — zero cost, instant wins for identical queries.\n- Semantic threshold of 0.88–0.92 balances hit rate vs. accuracy; tune with your data.\n- Set per-model TTLs: longer for stable knowledge (1 week), shorter for news\u002Fevents (1 hour).\n- Always filter by model name in semantic cache — different models give different answers.\n- Log cache hit rate as a KPI; target 30%+ for FAQ-style applications.\n\n## Related Skills\n\n- llm-cost-optimization (`llm-cost-optimization`) - Full cost strategy\n- llm-gateway (`llm-gateway`) - Gateway-level caching\n- vector-database-ops (`vector-database-ops`) - Qdrant setup\n- agent-observability (`agent-observability`) - Cache metrics dashboards\n\n## Limitations\n\n- Guidance executes against real environments: confirm target, blast radius, and rollback plan before applying anything.\n- Never deploy to production without explicit approval. Docs-only import: upstream scripts and templates not bundled.\n\n### Example\n\n```bash\ngit status && git diff --stat\nkubectl diff -f manifest.yaml\n```\n\n> Adapted from [BagelHole\u002FDevOps-Security-Agent-Skills](https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills) (MIT); frontmatter, When to Use\u002FLimitations, and safety boundaries added for upstream compliance. Docs-only import: helper scripts and templates not bundled.\n","# LLM Caching\n\nCut LLM costs and latency with exact match, semantic, and provider-side caching layers.\n\n## When to Use This Skill\n\nUse this skill when:\n- The same or similar queries are asked repeatedly (FAQ bots, support tools)\n- LLM API costs are growing and you need immediate savings\n- Serving high request volumes where repeated queries cause bottlenecks\n- Implementing prompt caching for long system prompts (Anthropic\u002FOpenAI)\n- Building offline-capable AI features that need response persistence\n\n## Caching Layers\n\nCache examples are incomplete until authorization\u002Fdata boundaries are included. Partition by tenant\u002Fuser access scope and include model revision, system\u002Fdeveloper prompts, conversation\u002Ftool context, parameters, locale and source\u002Fpolicy version in keys or eligibility filters. Never serve a privileged cached answer across users merely because queries are similar. Hashing prompts is not encryption: restrict\u002Fencrypt stored queries\u002Fresults, honor deletion\u002Fretention and invalidate when permissions\u002Fdata change. Avoid semantic reuse for sensitive or time-dependent answers unless evaluated false-hit risk is acceptable. Similarity thresholds\u002Flatencies\u002Fsavings are examples, not calibrated guarantees. Cache warming is paid generation: bound concurrency, requests and budget before running.\n\n```\nRequest → Exact Cache → Semantic Cache → Provider Cache → LLM API\n             ↓ hit            ↓ hit             ↓ hit\n           instant          ~5ms           50-80% cheaper\n```\n\n## Layer 1: Exact Match Cache (Redis)\n\n```python\nimport hashlib\nimport json\nimport redis\nfrom openai import OpenAI\n\nr = redis.Redis(host=\"localhost\", port=6379, decode_responses=True)\nclient = OpenAI()\n\ndef build_cache_key(model: str, messages: list, temperature: float) -> str:\n    \"\"\"Deterministic key from request parameters.\"\"\"\n    payload = json.dumps({\n        \"model\": model,\n        \"messages\": messages,\n        \"temperature\": temperature,\n    }, sort_keys=True)\n    return f\"llm:exact:{hashlib.sha256(payload.encode()).hexdigest()}\"\n\ndef cached_completion(model: str, messages: list, temperature: float = 0.0,\n                      ttl: int = 3600) -> dict:\n    key = build_cache_key(model, messages, temperature)\n\n    # Check cache\n    if cached := r.get(key):\n        return json.loads(cached)\n\n    # Call API\n    response = client.chat.completions.create(\n        model=model, messages=messages, temperature=temperature\n    )\n    result = response.model_dump()\n\n    # Cache only eligible responses; temperature 0 does not guarantee determinism.\n    if temperature == 0.0:\n        r.setex(key, ttl, json.dumps(result))\n\n    return result\n```\n\n## Layer 2: Semantic Cache (GPTCache)\n\n```python\nfrom gptcache import cache, Config\nfrom gptcache.adapter import openai\nfrom gptcache.embedding import Onnx\nfrom gptcache.manager import CacheBase, VectorBase, get_data_manager\nfrom gptcache.similarity_evaluation.distance import SearchDistanceEvaluation\n\n# Configure GPTCache with Qdrant backend\ndef init_gptcache(cache_obj, llm: str):\n    onnx = Onnx()                              # local embedding model\n    data_manager = get_data_manager(\n        CacheBase(\"redis\"),                    # metadata store\n        VectorBase(\"qdrant\",\n                   host=\"localhost\",\n                   port=6333,\n                   collection_name=f\"llm-cache-{llm}\",\n                   dimension=onnx.dimension),\n    )\n    cache_obj.init(\n        embedding_func=onnx.to_embeddings,\n        data_manager=data_manager,\n        similarity_evaluation=SearchDistanceEvaluation(),\n        config=Config(similarity_threshold=0.80),  # 80% similarity = cache hit\n    )\n\ncache.set_openai_key()\ninit_gptcache(cache, \"gpt-4o-mini\")\n\n# Now openai calls are automatically cached\nresponse = openai.ChatCompletion.create(\n    model=\"gpt-4o-mini\",\n    messages=[{\"role\": \"user\", \"content\": \"What is machine learning?\"}],\n)\n# Second call with similar question (\"Explain machine learning\") → cache hit\n```\n\n## Custom Semantic Cache (Illustrative)\n\n```python\nfrom sentence_transformers import SentenceTransformer\nfrom qdrant_client import QdrantClient\nfrom qdrant_client.models import Distance, VectorParams, PointStruct, Filter, FieldCondition, Range\nimport numpy as np\nimport uuid\nimport time\n\nembed_model = SentenceTransformer(\"BAAI\u002Fbge-small-en-v1.5\")  # fast, 33M params\nqdrant = QdrantClient(\"http:\u002F\u002Flocalhost:6333\")\n\nCACHE_COLLECTION = \"semantic-cache\"\nSIMILARITY_THRESHOLD = 0.88\nCACHE_TTL_SECONDS = 86400  # 24h\n\n# Create collection once\nqdrant.create_collection(\n    collection_name=CACHE_COLLECTION,\n    vectors_config=VectorParams(size=384, distance=Distance.COSINE),\n    on_disk_payload=True,\n)\n\ndef semantic_cache_lookup(query: str, model: str) -> str | None:\n    embedding = embed_model.encode(query).tolist()\n    results = qdrant.query_points(\n        collection_name=CACHE_COLLECTION,\n        query=embedding,\n        query_filter=Filter(must=[\n            FieldCondition(key=\"model\", match={\"value\": model}),\n            FieldCondition(key=\"expires_at\", range=Range(gte=time.time())),\n        ]),\n        limit=1,\n        score_threshold=SIMILARITY_THRESHOLD,\n    )\n    if results.points:\n        return results.points[0].payload[\"response\"]\n    return None\n\ndef semantic_cache_store(query: str, response: str, model: str):\n    embedding = embed_model.encode(query).tolist()\n    qdrant.upsert(\n        collection_name=CACHE_COLLECTION,\n        points=[PointStruct(\n            id=str(uuid.uuid4()),\n            vector=embedding,\n            payload={\n                \"query\": query,\n                \"response\": response,\n                \"model\": model,\n                \"created_at\": time.time(),\n                \"expires_at\": time.time() + CACHE_TTL_SECONDS,\n            },\n        )],\n    )\n\ndef smart_llm_call(query: str, model: str = \"gpt-4o-mini\") -> dict:\n    # 1. Semantic lookup\n    if cached_response := semantic_cache_lookup(query, model):\n        return {\"response\": cached_response, \"source\": \"semantic_cache\", \"cost\": 0}\n\n    # 2. LLM call\n    response = client.chat.completions.create(\n        model=model,\n        messages=[{\"role\": \"user\", \"content\": query}],\n    )\n    text = response.choices[0].message.content\n    cost = litellm.completion_cost(response)\n\n    # 3. Store in cache\n    semantic_cache_store(query, text, model)\n\n    return {\"response\": text, \"source\": \"llm_api\", \"cost\": cost}\n```\n\n## Gateway-Level Semantic Cache\n\nIf LLM traffic already goes through a gateway (see `llm-gateway`), the semantic cache can live there instead of in each application. LiteLLM's `cache: true` setting is one option; Bifrost's `semantic_cache` plugin is another. Bifrost checks an exact-match hash first and runs the vector similarity search only on a miss. It needs a vector store (RediSearch-compatible Redis\u002FValkey, Weaviate, Qdrant or Pinecone) and an embedding model for the semantic path, and it only caches requests that carry a cache key (the `x-bf-cache-key` header, or a configured `default_cache_key`).\n\n```json\n{\n  \"vector_store\": { \"enabled\": true, \"type\": \"redis\", \"config\": { \"addr\": \"redis:6379\" } },\n  \"plugins\": [{\n    \"enabled\": true,\n    \"name\": \"semantic_cache\",\n    \"config\": {\n      \"provider\": \"openai\",\n      \"embedding_model\": \"text-embedding-3-small\",\n      \"dimension\": 1536,\n      \"threshold\": 0.85,\n      \"ttl\": \"1h\"\n    }\n  }]\n}\n```\n\n## Layer 3: Provider-Side Prompt Caching\n\n```python\n# Anthropic — cache long system prompts (saves 90% on cached input tokens)\nimport anthropic\n\nanthropic_client = anthropic.Anthropic()\n\n# Long system prompt — mark for caching\nSYSTEM_PROMPT = open(\"knowledge-base.txt\").read()  # e.g., 50k tokens\n\ndef call_with_prompt_cache(user_question: str) -> str:\n    response = anthropic_client.messages.create(\n        model=\"claude-sonnet-4-6\",\n        max_tokens=1024,\n        system=[\n            {\"type\": \"text\", \"text\": \"You are a helpful assistant.\"},\n            {\n                \"type\": \"text\",\n                \"text\": SYSTEM_PROMPT,\n                \"cache_control\": {\"type\": \"ephemeral\"},  # cache this block\n            }\n        ],\n        messages=[{\"role\": \"user\", \"content\": user_question}],\n    )\n    # Log cache efficiency\n    usage = response.usage\n    cache_savings = usage.cache_read_input_tokens * 0.9  # 90% discount on cached\n    print(f\"Cache hits: {usage.cache_read_input_tokens} tokens \"\n          f\"(saved ~${cache_savings * 3.0 \u002F 1_000_000:.4f})\")\n    return response.content[0].text\n\n# OpenAI — automatic for repeated prefixes (≥1,024 tokens)\n# No code change needed; cached tokens appear in usage.prompt_tokens_details\nresponse = client.chat.completions.create(\n    model=\"gpt-4o-mini\",\n    messages=[\n        {\"role\": \"system\", \"content\": LONG_SYSTEM_PROMPT},  # auto-cached\n        {\"role\": \"user\", \"content\": user_question},\n    ]\n)\ncached = response.usage.prompt_tokens_details.cached_tokens\nprint(f\"OpenAI cached {cached} tokens\")\n```\n\n## Cache Warming\n\n```python\nasync def warm_cache(common_queries: list[str], model: str):\n    \"\"\"Pre-populate cache with known frequent queries.\"\"\"\n    import asyncio\n    from openai import AsyncOpenAI\n\n    aclient = AsyncOpenAI()\n\n    async def warm_single(query: str):\n        if not semantic_cache_lookup(query, model):\n            response = await aclient.chat.completions.create(\n                model=model,\n                messages=[{\"role\": \"user\", \"content\": query}],\n            )\n            text = response.choices[0].message.content\n            semantic_cache_store(query, text, model)\n            print(f\"Warmed: {query[:50]}...\")\n\n    await asyncio.gather(*[warm_single(q) for q in common_queries])\n\n# Warm on startup\nimport asyncio\nasyncio.run(warm_cache(FREQUENT_QUERIES, \"gpt-4o-mini\"))\n```\n\n## Cache Metrics\n\n```python\nfrom prometheus_client import Counter, Histogram\n\ncache_hits = Counter(\"llm_cache_hits_total\", \"Cache hits\", [\"cache_layer\", \"model\"])\ncache_misses = Counter(\"llm_cache_misses_total\", \"Cache misses\", [\"model\"])\ncache_savings_usd = Counter(\"llm_cache_savings_usd_total\", \"USD saved by cache\", [\"model\"])\n\n# Use in your smart_llm_call function\nif source == \"semantic_cache\":\n    cache_hits.labels(cache_layer=\"semantic\", model=model).inc()\n    cache_savings_usd.labels(model=model).inc(estimated_cost)\nelse:\n    cache_misses.labels(model=model).inc()\n```\n\n## Redis Configuration for LLM Caching\n\nThese entries belong in redis.conf, not a shell. Verify memory limits and whether disabling persistence is appropriate for the actual Redis instance; do not overwrite unrelated workload policy.\n\n```text\n# redis.conf tuning for LLM cache workload\nmaxmemory 8gb\nmaxmemory-policy allkeys-lru    # evict least-recently-used when full\nsave \"\"                          # disable persistence (cache is ephemeral)\nappendonly no\ntcp-keepalive 60\n```\n\n## Common Issues\n\n| Issue | Cause | Fix |\n|-------|-------|-----|\n| Low cache hit rate | Threshold too strict | Lower `SIMILARITY_THRESHOLD` to 0.82–0.85 |\n| Stale cached responses | Long TTL | Use topic-specific TTLs; invalidate on data updates |\n| Cache serving wrong answers | Threshold too loose | Raise threshold or add model-name filtering |\n| Redis OOM | No eviction policy | Set `maxmemory` + `allkeys-lru` |\n| Slow semantic lookup | Large cache collection | Add payload index on `model` + `expires_at` |\n\n## Best Practices\n\n- Start with exact cache — zero cost, instant wins for identical queries.\n- Semantic threshold of 0.88–0.92 balances hit rate vs. accuracy; tune with your data.\n- Set per-model TTLs: longer for stable knowledge (1 week), shorter for news\u002Fevents (1 hour).\n- Always filter by model name in semantic cache — different models give different answers.\n- Log cache hit rate as a KPI; target 30%+ for FAQ-style applications.\n\n## Related Skills\n\n- llm-cost-optimization (`llm-cost-optimization`) - Full cost strategy\n- llm-gateway (`llm-gateway`) - Gateway-level caching\n- vector-database-ops (`vector-database-ops`) - Qdrant setup\n- agent-observability (`agent-observability`) - Cache metrics dashboards\n\n## Limitations\n\n- Guidance executes against real environments: confirm target, blast radius, and rollback plan before applying anything.\n- Never deploy to production without explicit approval. Docs-only import: upstream scripts and templates not bundled.\n\n### Example\n\n```bash\ngit status && git diff --stat\nkubectl diff -f manifest.yaml\n```\n\n> Adapted from [BagelHole\u002FDevOps-Security-Agent-Skills](https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills) (MIT); frontmatter, When to Use\u002FLimitations, and safety boundaries added for upstream compliance. Docs-only import: helper scripts and templates not bundled.\n",{"name":5,"risk":26,"source":49,"license":14,"category":50,"metadata":51,"date_added":54,"description":7,"source_repo":55,"source_type":29,"compatibility":56,"license_source":57},"https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills","devops",{"author":52,"version":53},"devops-skills","1.0","2026-09-20","BagelHole\u002FDevOps-Security-Agent-Skills","Requires the relevant platform CLIs (kubectl, helm, terraform, git, CI runners) and authorized access to the target environment. Docs-only; helper scripts and templates not bundled.","https:\u002F\u002Fgithub.com\u002FBagelHole\u002FDevOps-Security-Agent-Skills\u002Fblob\u002Fmain\u002FLICENSE","7bf2279c8a65758319526a721d5c4b75683aec9c","skills\u002Fantigravity-llm-caching",3,"https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections","https:\u002F\u002Fgithub.com\u002Fboisenoise","2026-11-14 14:18:11",{"source":8,"skillName":5,"commands":65,"prompt":75,"zipAvailable":76},[66,69,72],{"tool":67,"command":68},"npx","npx skills add boisenoise\u002Fskills-collections --skill llm-caching",{"tool":70,"command":71},"bunx","bunx skills add boisenoise\u002Fskills-collections --skill llm-caching",{"tool":73,"command":74},"pnpm","pnpm dlx skills add boisenoise\u002Fskills-collections --skill llm-caching","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-llm-caching\u002FSKILL.md",true,[],[79,88,96,105,113,121],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":83,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":87},"01M7B6HREHB53EHGGVZND7DDXN","scrapely-scrape","Collect web data with ready-made Scrape.ly scrapers: Google Maps places, Amazon products, LinkedIn jobs, reviews, social posts. Use when the user wants structured data from a site.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-scrapely-scrape\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-scrapely-scrape\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":92,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":87},"01M7B6GDNNN4HE662KA6KPF7GW","lumify-odds","Lumify's hosted sports MCP\u002FREST API for sportsbook odds, line-movement history, public betting splits, and player props across MLB, NFL, NBA, NHL, soccer, tennis, NCAAF, NCAAB. Read-only market data.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-lumify-odds\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-lumify-odds\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":100,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":104},"01M743PZMJW2GEKG5J199GPSK7","sync-lipsync","Lip-sync an existing video of a real person to new audio or a typed script with sync. labs through its hosted MCP server, quoting the cost and waiting for approval first.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-sync-lipsync\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-sync-lipsync\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":109,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":104},"01M743MMN3CKTJVNRSZMB684E5","music-for-robots","Optional music-inspired creative exercise for multimodal agents. Ingests an unquantized acoustic MP3 composition by Michael Luchtan (Music For Robots) into a private temporary directory, analyzing microtiming and texture to inspire creative writing, brainstorming, or technical tasks.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-music-for-robots\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-music-for-robots\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":117,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":104},"01M743KC2GN5WE11BSTWSSWD8B","imagera-media","Generate or edit images, video clips, voiceovers and music through the hosted Imagera MCP server, quoting the credit cost and getting approval before each paid call.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-imagera-media\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-imagera-media\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":125,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":104},"01M743HDJNZQA8A4VT68NWGWQJ","deja-history","Search this machine's past AI coding sessions across Claude Code, Codex, Cursor, Gemini CLI and thirty-nine other agents before editing, debugging, or denying something exists.","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-deja-history\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fboisenoise\u002Fskills-collections\u002Fblob\u002Fmain\u002Fskills\u002Fantigravity-deja-history\u002FSKILL.md",[],[]]