Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Prompt Caching

ASecurity

Optimize LLM cost and latency with prompt caching: cacheable prefixes, cache-control headers, context layout, and cache-aware prompting. Use for high-volume apps.

2 stars
0 votes
0 copies
0 views
Added 9/29/2026
ai-agentspythongobash

Works with

cli

Security Analysis

A96/100
mediumInstalls packages at runtime which could introduce malicious dependencies

Pro scans all 2 files and shows the line behind each finding

Scanned 9/29/2026

$npx -y skills add ssrjkk/claude-skills --skill prompt-caching --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Prompt Caching?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Prompt Caching
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/ssrjkk-prompt-caching/badge)](https://www.skillsdirectory.com/skills/ssrjkk-prompt-caching)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: prompt-caching
description: "Optimize LLM cost and latency with prompt caching: cacheable prefixes, cache-control headers, context layout, and cache-aware prompting. Use for high-volume apps."
category: ai
tags: [prompt-caching, caching, llm, cost, latency, context, optimization]
models: [sonnet, opus, gpt-5, gemini-2.5, glm-4.6]
version: 1.0.0
created: 2026-09-25
updated: 2026-09-28
author: ssrjkk
---
# Prompt Caching

> Cutting LLM cost and latency by caching repeated prompt prefixes.

## Quick Start
```python
# Put stable content first, mark it as cacheable
resp = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "system", "content": LONG_SYSTEM_PROMPT},
        {"role": "user", "content": dynamic_question},
    ],
    extra_headers={"Cache-Control": "ttl=3600, min_tokens=1024"},
)
```

## When to Use
- Chat with long system prompts or tool definitions
- Agents with large context that repeats across turns
- RAG apps where system instructions are stable
- High-volume endpoints where cost matters

## Best Practices

### Layout
- Put stable content first: system prompt, tools, static context
- Put dynamic content last: user turns, retrieved chunks
- Keep a stable prefix across all requests
- Minimum cacheable size varies by provider (e.g., 1024+ tokens)

### Cache-Control
- Mark cacheable segments with cache-control headers
- Set a TTL that matches your access pattern
- Don't cache secrets or per-user data
- Verify cache hits via usage metadata (`cached_tokens`)

### Design for Caching
- Keep the system prompt identical across calls
- Separate static tool definitions from dynamic input
- Reuse the same prefix for the whole conversation
- Batch ephemeral data at the end of the context

### Measurement
- Track cached vs uncached tokens in usage
- Measure latency improvement per request
- Monitor cache hit rate over time
- Compare cost before and after optimization

## Dependencies
```bash
pip install openai anthropic
```

## Examples
```python
import openai

client = openai.OpenAI()

# Stable prefix: system prompt + tools, marked cacheable
STATIC = [
    {"role": "system", "content": "You are a senior support agent."},
    {"role": "user", "content": "Available tools: search, refund, escalate."},
]

def ask(question: str) -> str:
    resp = client.chat.completions.create(
        model="gpt-5",
        messages=STATIC + [{"role": "user", "content": question}],
        extra_headers={"Cache-Control": "ttl=3600, min_tokens=1024"},
    )
    usage = resp.usage
    print("cached:", getattr(usage, "prompt_tokens_details", None))
    return resp.choices[0].message.content
```
```python
# Anthropic-style cache control
import anthropic

client = anthropic.Anthropic()

def ask(question: str) -> str:
    resp = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        system=[
            {"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}},
        ],
        messages=[{"role": "user", "content": question}],
    )
    print("cache:", resp.usage.cache_creation_input_tokens, resp.usage.cache_read_input_tokens)
    return resp.content[0].text
```
```python
# Session-style caching: stable system across a conversation
def chat_session():
    messages = list(STATIC)
    while True:
        q = input("> ")
        resp = client.chat.completions.create(
            model="gpt-5", messages=messages + [{"role": "user", "content": q}],
            extra_headers={"Cache-Control": "ttl=3600, min_tokens=1024"},
        )
        answer = resp.choices[0].message.content
        messages.append({"role": "user", "content": q})
        messages.append({"role": "assistant", "content": answer})
        print(answer)
```
```python
# Verify cache hits from usage metadata
def report_cache(usage) -> dict:
    details = getattr(usage, "prompt_tokens_details", None) or {}
    cached = getattr(details, "cached_tokens", 0)
    total = usage.prompt_tokens
    return {"cached": cached, "total": total, "rate": cached / total if total else 0}
```

## Step-by-Step
1. Identify the stable prefix in your prompts (system, tools, static).
2. Move dynamic content to the end of the context.
3. Mark the prefix cacheable with the provider's mechanism.
4. Verify cache hits in usage metadata.
5. Measure latency and cost before/after.
6. Tune TTL and minimum tokens to your traffic.
7. Avoid caching per-user or secret data.
8. Monitor hit rate and keep the prefix byte-identical.

## Validation
1. Usage shows cached tokens on repeat requests
2. Latency drops for the cached portion
3. Cost per request decreases measurably
4. Responses stay correct after cache hits
5. Secrets are not in the cacheable prefix

## Troubleshooting
- No cache hits: prefix differs between calls — keep it byte-identical.
- Short prompts: raise the prefix above the provider minimum.
- Cache invalidation: changing the prefix invalidates; redesign for stability.

Attribution

ssrjkkssrjkk
View sourceSee grades on GitHubMore from ssrjkk →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Terse caveman voice: answer first, fluff gone, every technical fact kept. Use for /caveman, "caveman mode", "talk like caveman", "be brief", "less tokens". Stays on until "stop caveman" or "normal mode".

1100021 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

698461 votes

Writing Skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dep...

3931 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3421 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Amp, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Grok Build, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

741 votes
View all in ai-agents →