专为 Anthropic 的 Claude 模型设计的中间件。了解更多关于 中间件.
| 中间件 | 描述 |
|---|---|
| 提示词缓存 | 通过缓存重复的提示词前缀来降低成本 |
提示词缓存
通过在 Anthropic 服务器上缓存静态或重复的提示词内容(如系统提示词、工具定义和对话历史)来降低成本和延迟。此中间件实现了 **对话缓存策略** ,它在系统消息、工具定义和最新的用户消息上设置明确的缓存断点,允许整个对话历史被缓存并在后续 API 调用中重用。
提示词缓存适用于以下场景:
- - 具有长的静态系统提示词的应用程序,这些提示词在请求之间不会改变
- - 具有许多在调用之间保持不变的工具定义的代理
- - 早期消息历史在多个轮次中重用的对话
- - 在降低 API 成本和延迟至关重要的低延迟部署
const agent = createAgent({
model: "claude-sonnet-4-6",
prompt: "",
middleware: [anthropicPromptCachingMiddleware({ ttl: "5m" })],
});
Configuration options
缓存内容的生存时间。有效值: '5m' or '1h'
Full example
中间件会缓存每个请求中直到并包括最新消息的内容。在 TTL 窗口(5 分钟或 1 小时)内的后续请求中,之前见过的内容从缓存中检索,而不是重新处理,从而显著降低成本和延迟。
工作原理: 1. 第一个请求:系统提示词、工具和用户消息 *"你好,我叫 Bob"* 被发送到 API 并缓存 2. 第二个请求:缓存的内容(系统提示词、工具和第一条消息)从缓存中检索。只需要处理新消息 *"我叫什么名字?"* 加上第一次请求中模型的响应 3. 每个轮次都会继续这种模式,每个请求都重用缓存的对话历史
const LONG_PROMPT = `
Please be a helpful assistant.
`;
const agent = createAgent({
model: "claude-sonnet-4-6",
prompt: LONG_PROMPT,
middleware: [anthropicPromptCachingMiddleware({ ttl: "5m" })],
});
// First invocation: Creates cache with system prompt, tools, and "Hi, my name is Bob"
await agent.invoke({
messages: [new HumanMessage("Hi, my name is Bob")]
});
// Second invocation: Reuses cached system prompt, tools, and previous messages
// Only processes the new message "What's my name?" and the previous AI response
const result = await agent.invoke({
messages: [new HumanMessage("What's my name?")]
});