> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Anthropic 集成

> 使用 LangChain JavaScript 集成 Anthropic 中间件。

专为 Anthropic 的 Claude 模型设计的中间件。了解更多关于 [中间件](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/middleware/overview.md) 的信息。

| 中间件 | 描述 |
| - | - |
| [提示词缓存](#提示词缓存) | 通过缓存重复的提示词前缀来降低成本 |

## 提示词缓存

通过在 Anthropic 的服务器上缓存静态或重复的提示词内容（如系统提示词、工具定义和对话历史）来降低成本和延迟。此中间件实现了一种 **对话缓存策略**，在系统消息、工具定义和最新用户消息上设置明确的缓存断点，允许整个对话历史被缓存并在后续 API 调用中重用。

提示词缓存适用于以下场景：

* 具有长且静态的系统提示词的应用，这些提示词在请求之间不会改变
* 具有许多在调用之间保持不变的工具定义的智能体
* 对话中早期消息历史在多个回合中被重复使用
* 高容量部署，其中降低 API 成本和延迟至关重要

> [!TIP]
>
> 对于简单的用例，您也可以通过在调用时传递 `cache_control` 而不使用中间件来在对话模型上使用 [提示词缓存](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/chat/anthropic.md#提示词缓存)。当您需要显式控制系统提示词和工具定义上的缓存断点时，建议使用中间件。

> [!NOTE]
>
> 了解更多关于 [Anthropic 提示词缓存](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-limitations) 策略和限制的信息。

```typescript theme={null}
import { createAgent, anthropicPromptCachingMiddleware } from "langchain";

const agent = createAgent({
  model: "claude-sonnet-4-6",
  prompt: "<Your long system prompt here>",
  middleware: [anthropicPromptCachingMiddleware({ ttl: "5m" })],
});
```

> [accordion] Configuration options
>
> **ttl** `string` (default: 5m)
>
> 缓存内容的生存时间。有效值：`'5m'` 或 `'1h'`

> [accordion] Full example
>
> 中间件缓存每个请求中包括最新消息的内容。在 TTL 窗口（5 分钟或 1 小时）内的后续请求中，先前看到的内容将从缓存中检索而不是重新处理，从而显著降低成本和延迟。
>
> **工作原理：**
>
> 1. 第一个请求：系统提示词、工具和用户消息 *"Hi, my name is Bob"* 被发送到 API 并被缓存
> 2. 第二个请求：从缓存中检索缓存的 内容（系统提示词、工具和第一条消息）。只需要处理新消息 *"What's my name?"*，以及模型对第一个请求的响应
> 3. 此模式继续应用于每个回合，每个请求重用缓存的对话历史
>
> ```typescript theme={null}
> import { createAgent, HumanMessage, anthropicPromptCachingMiddleware } from "langchain";
>
> const LONG_PROMPT = `
> Please be a helpful assistant.
>
> <Lots more context ...>
> `;
>
> 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?")]
> });
> ```

***

> 官方原文：[src/oss/javascript/integrations/middleware/anthropic.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/middleware/anthropic.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.