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

# Anthropic 集成

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

专为 Anthropic 的 Claude 模型设计的中间件。了解更多关于[中间件](/oss/javascript/langchain/middleware/overview)的信息。

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

## 提示缓存

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

提示缓存适用于以下情况：

* 具有长且静态的系统提示的应用程序，这些提示在请求之间不会发生变化
* 具有许多工具定义的智能体，这些定义在调用之间保持不变
* 早期消息历史在多个轮次中被重用的对话
* 降低 API 成本和延迟至关重要的高流量部署

<Tip>
  对于更简单的用例，您也可以通过在调用时传递 `cache_control` 而不使用中间件，在聊天模型上使用[提示缓存](/oss/javascript/integrations/chat/anthropic#提示缓存)。当您需要显式控制对系统提示和工具定义的缓存断点时，建议使用中间件。
</Tip>

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

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createAgent, anthropicPromptCachingMiddleware } from "langchain";

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

<Accordion title="配置选项">
  <ParamField body="ttl" type="string" default="5m">
    缓存内容的生存时间。有效值：`'5m'` 或 `'1h'`
  </ParamField>
</Accordion>

<Accordion title="完整示例">
  该中间件缓存每个请求中最新消息及之前的内容。在 TTL 窗口（5 分钟或 1 小时）内的后续请求中，之前看到的内容将从缓存中检索，而不是重新处理，从而显著降低成本和延迟。

  **工作原理：**

  1. 第一次请求：系统提示、工具和用户消息 *"Hi, my name is Bob"* 被发送到 API 并被缓存
  2. 第二次请求：缓存的内容（系统提示、工具和第一条消息）从缓存中检索。只有新消息 *"What's my name?"* 需要被处理，加上模型对第一次请求的响应
  3. 这种模式在每个轮次中继续，每个请求都重用缓存的对话历史

  ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  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" })],
  });

  // 第一次调用：使用系统提示、工具和 "Hi, my name is Bob" 创建缓存
  await agent.invoke({
    messages: [new HumanMessage("Hi, my name is Bob")]
  });

  // 第二次调用：重用缓存的系统提示、工具和之前的消息
  // 只处理新消息 "What's my name?" 和之前的 AI 响应
  const result = await agent.invoke({
    messages: [new HumanMessage("What's my name?")]
  });
  ```
</Accordion>

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/middleware/anthropic.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
