npx skills add ...
npx skills add sickn33/antigravity-awesome-skills --skill prompt-caching
Caching strategies for LLM prompts including Anthropic prompt
npx skills add sickn33/antigravity-awesome-skills --skill prompt-caching
Caching strategies for LLM prompts including Anthropic prompt caching, response caching, and CAG (Cache Augmented Generation)
upstash-redis)Use Claude's native prompt caching for repeated prefixes
When to use: Using Claude API with stable system prompts or context
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
// Cache the stable parts of your prompt async function queryWithCaching(userQuery: string) { const response = await client.messages.create({ model: "claude-sonnet-4-20250514", max_tokens: 1024, system: [ { type: "text", text: LONG_SYSTEM_PROMPT, // Your detailed instructions cache_control: { type: "ephemeral" } // Cache this! }, { type: "text", text: KNOWLEDGE_BASE, // Large static context cache_control: { type: "ephemeral" } } ], messages: [ { role: "user", content: userQuery } // Dynamic part ] });
}
// Cost savings: 90% reduction on cached tokens // Latency savings: Up to 2x faster
Cache full LLM responses for identical or similar queries
When to use: Same queries asked repeatedly
import { createHash } from 'crypto'; import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL); // Serverless/edge alternative without a persistent connection: // import { Redis } from '@upstash/redis'; const redis = Redis.fromEnv(); // then use redis.set(key, value, { ex: ttl })
class ResponseCache { private ttl = 3600; // 1 hour default
}
Pre-cache documents in prompt instead of RAG retrieval
When to use: Document corpus is stable and fits in context
// CAG: Pre-compute document context, cache in prompt // Better than RAG when: // - Documents are stable // - Total fits in context window // - Latency is critical
class CAGSystem { private cachedContext: string | null = null; private lastUpdate: number = 0;
}
// CAG vs RAG decision matrix: // | Factor | CAG Better | RAG Better | // |------------------|------------|------------| // | Corpus size | < 100K tokens | > 100K tokens | // | Update frequency | Low | High | // | Latency needs | Critical | Flexible | // | Query specificity| General | Specific |
Severity: HIGH
Situation: Slow response when cache miss, slower than no caching
Symptoms:
Why this breaks: Cache check adds latency. Cache write adds more latency. Miss + overhead > no caching.
Recommended fix:
// Optimize for cache misses, not just hits
class OptimizedCache { async queryWithCache(prompt: string): Promise { const cacheKey = this.hash(prompt);
}
// Alternative: Probabilistic caching // Only cache if query matches known high-frequency patterns class SelectiveCache { private patterns: Map<string, number> = new Map();
}
Severity: HIGH
Situation: Users get outdated or wrong information from cache
Symptoms:
Why this breaks: Source data changed. No cache invalidation. Long TTLs for dynamic data.
Recommended fix:
// Implement proper cache invalidation
class InvalidatingCache { // Version-based invalidation private cacheVersion = 1;
}
Severity: MEDIUM
Situation: Cache misses despite similar prompts
Symptoms:
Why this breaks: Anthropic caching requires exact prefix match. Timestamps or dynamic content in prefix. Different message order.
Recommended fix:
// Structure prompts for optimal caching
class CacheOptimizedPrompts {
// WRONG: Dynamic content in cached prefix
buildPromptBad(query: string): SystemMessage[] {
return [
{
type: "text",
text: You are helpful. Current time: ${new Date()}, // BREAKS CACHE!
cache_control: { type: "ephemeral" }
}
];
}
}
Severity: WARNING
Message: Caching with high temperature. Responses are non-deterministic.
Fix action: Only cache responses with temperature <= 0.5
Severity: WARNING
Message: Cache without TTL. May serve stale data indefinitely.
Fix action: Set appropriate TTL based on data freshness requirements
Severity: WARNING
Message: Dynamic content in cached prefix. Will cause cache misses.
Fix action: Move dynamic content outside of cache_control blocks
Severity: INFO
Message: Cache without hit/miss tracking. Can't measure effectiveness.
Fix action: Add cache hit/miss metrics and logging
Skills: prompt-caching, context-window-management, rag-implementation
Workflow:
Works well with: context-window-management, rag-implementation, conversation-memory