mcpField
P
prompt-caching

prompt-caching

github.com/thelobbi开发2154 次安装3 天前更新
代码仓库

关于 prompt-caching

这项技能介绍如何在重复使用大型或稳定提示内容的应用中采用 Anthropic 提示缓存。内容涵盖缓存断点位置、TTL 选择、实现模式、使用情况监测、失效规则和成本计算。

主要功能

  1. 01缓存断点位置选择
  2. 025 分钟与 1 小时 TTL
  3. 03单断点及多断点模式
  4. 04缓存使用情况监测
  5. 05缓存失效规则说明
  6. 06成本计算示例

适用场景

  1. 01在 RAG 中复用静态文档
  2. 02缓存长对话中的指令
  3. 03分析包含大量上下文的代码
  4. 04使用共享前缀处理批次任务

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/thelobbi/claude --skill prompt-caching

安装后在 Claude Code 中输入/prompt-caching确认已加载。

详细介绍

提示词缓存技能

利用 Anthropic 的提示词缓存,大幅降低重复提示词的延迟和成本。

何时使用此技能

  • 包含大型静态文档的 RAG 系统
  • 带有长指令的多轮对话
  • 使用大型代码库上下文进行代码分析
  • 使用共享前缀进行批处理
  • 文档分析与摘要

核心概念

缓存控制的位置
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": "You are a helpful assistant with access to a large knowledge base...",
            "cache_control": {"type": "ephemeral"}  # Cache this content
        }
    ],
    messages=[{"role": "user", "content": "What is...?"}]
)
缓存层级

按以下顺序检查缓存断点:

  1. 工具 - 首先缓存工具定义
  2. 系统 - 其次缓存系统提示词
  3. 消息 - 最后缓存对话历史
TTL 选项
TTL写入成本读取成本使用场景
5 分钟(默认)基础费用的 1.25 倍基础费用的 0.1 倍交互式会话
1 小时基础费用的 2.0 倍基础费用的 0.1 倍批处理、稳定的文档
缓存要求
  • **最少令牌数:**1024-4096(因模型而异)
  • **最多断点数:**每个请求 4 个
  • **支持的模型:**所有当前模型(Fable 5、Opus 4.8、Sonnet 5、Haiku 4.5)

实现模式

模式 1:单个断点(推荐)
# Best for: Document analysis, Q&A with static context
system = [
    {
        "type": "text",
        "text": large_document_content,
        "cache_control": {"type": "ephemeral"}  # Single breakpoint at end
    }
]
模式 2:多轮对话
# Cache grows with conversation
messages = [
    {"role": "user", "content": "First question"},
    {"role": "assistant", "content": "First answer"},
    {
        "role": "user",
        "content": "Follow-up question",
        "cache_control": {"type": "ephemeral"}  # Cache entire conversation
    }
]
模式 3:使用多个断点的 RAG
system = [
    {
        "type": "text",
        "text": "Tool definitions and instructions",
        "cache_control": {"type": "ephemeral"}  # Breakpoint 1: Tools
    },
    {
        "type": "text",
        "text": retrieved_documents,
        "cache_control": {"type": "ephemeral"}  # Breakpoint 2: Documents
    }
]
模式 4:使用 1 小时 TTL 的批处理
# Warm the cache before batch
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=100,
    system=[{
        "type": "text",
        "text": shared_context,
        "cache_control": {"type": "ephemeral", "ttl": "1h"}
    }],
    messages=[{"role": "user", "content": "Initialize cache"}]
)

# Now run batch - all requests hit the cache
for item in batch_items:
    response = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=1024,
        system=[{
            "type": "text",
            "text": shared_context,
            "cache_control": {"type": "ephemeral", "ttl": "1h"}
        }],
        messages=[{"role": "user", "content": item}]
    )

性能监控

检查缓存用量
response = client.messages.create(...)

# Monitor these fields
cache_write = response.usage.cache_creation_input_tokens  # New cache written
cache_read = response.usage.cache_read_input_tokens       # Cache hit!
uncached = response.usage.input_tokens                    # After breakpoint

print(f"Cache hit rate: {cache_read / (cache_read + cache_write + uncached) * 100:.1f}%")
成本计算
def calculate_cost(usage, model="claude-sonnet-5"):
    # Example rates (check current pricing)
    base_input_rate = 0.003  # per 1K tokens

    write_cost = (usage.cache_creation_input_tokens / 1000) * base_input_rate * 1.25
    read_cost = (usage.cache_read_input_tokens / 1000) * base_input_rate * 0.1
    uncached_cost = (usage.input_tokens / 1000) * base_input_rate

    return write_cost + read_cost + uncached_cost

缓存失效

以下更改会导致缓存失效:

更改影响
工具定义整个缓存失效
系统提示词系统提示词和消息缓存失效
断点之前的任何内容该断点及之后的内容失效

最佳实践

应该:
  • 将断点放在静态内容的末尾
  • 在不同请求之间保持工具和指令稳定
  • 批处理使用 1 小时 TTL
  • 监控 cache_read_input_tokens 以了解节省情况
不应该:
  • 将断点放在动态内容中间
  • 频繁更改工具定义
  • 期望缓存适用于少于 1024 个令牌的内容
  • 忽视 20 个块的回溯限制

与扩展思考的集成

# Cache + Extended Thinking
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=16000,
    thinking={"type": "adaptive"},
    system=[{
        "type": "text",
        "text": large_context,
        "cache_control": {"type": "ephemeral"}
    }],
    messages=[{"role": "user", "content": "Analyze this..."}]
)

另请参阅

  • [[llm-integration]] - Claude API 基础知识
  • [[extended-thinking]] - 深度推理
  • [[batch-processing]] - 批量处理

评论

支持 Markdown