> ## 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.

# AWS 中间件集成

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

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

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

## 提示词缓存

通过在 Amazon Bedrock 上缓存频繁重用的提示词前缀来减少推理延迟和输入 Token 成本。`bedrockPromptCachingMiddleware` 通过 `modelSettings` 实现缓存功能。`ChatBedrockConverse` 然后在请求时将其转换为正确的 AWS 线路格式。缓存检查点会放置在系统提示词、工具定义和最新消息之后（如果支持），以便模型可以在后续请求中跳过重新计算之前见过的内容。缓存位置因模型系列而异：例如，Nova 会跳过某些工具定义和工具结果的情况。

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

* 具有长且一致的系统提示词的多轮对话
* 具有许多在调用之间保持不变的工具定义的智能体
* 基于文档的问答，用户在相同的上传上下文中提出多个问题
* 具有重复静态内容的批处理工作负载

支持的模型：

* **Anthropic Claude**
* **Amazon Nova**

> [!NOTE]
>
> 了解更多关于 [AWS Bedrock 提示词缓存](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html) 策略和限制的信息。缓存的內容必须超过 1,024 个 Token 才能生效，具体可能更多取决于模型。参见 [支持的模型、区域和限制](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html#prompt-caching-models)。

**API 参考:** @\[`BedrockPromptCachingMiddleware`]

```typescript Model string theme={null}
import { createAgent, bedrockPromptCachingMiddleware } from "langchain";

const agent = createAgent({
  model: "bedrock:us.anthropic.claude-sonnet-4-5-20250929-v1:0",
  systemPrompt: "<Your long system prompt here>",
  middleware: [bedrockPromptCachingMiddleware({ ttl: "1h" })], // [!code highlight]
});
```

```typescript ChatBedrockConverse instance theme={null}
import { createAgent, bedrockPromptCachingMiddleware } from "langchain";
import { ChatBedrockConverse } from "@langchain/aws";

const agent = createAgent({
  model: new ChatBedrockConverse({ model: "us.anthropic.claude-sonnet-4-5-20250929-v1:0" }),
  systemPrompt: "<Your long system prompt here>",
  middleware: [bedrockPromptCachingMiddleware({ ttl: "5m" })], // [!code highlight]
});
```

> [accordion] Configuration options
>
> **enableCaching** `boolean` (default: true)
>
> 是否应用提示词缓存。
>
> **ttl** `string` (default: 5m)
>
> 缓存内容的生存时间。有效值：`'5m'` 或 `'1h'`。注意 Amazon Nova 模型仅支持 `'5m'`。
>
> **minMessagesToCache** `number` (default: 1)
>
> 缓存开始前的最小消息数。系统提示词计为一个消息。
>
> **unsupportedModelBehavior** `string` (default: warn)
>
> 使用不支持的模型时的行为。选项：`'ignore'`、`'warn'` 或 `'raise'`。

> [accordion] Full example
>
> 中间件会缓存每个请求中包括最新消息的内容。在 TTL 窗口（5 分钟或 1 小时）内的后续请求中，之前见过的內容会从缓存中检索，而不是重新处理，从而降低成本和延迟。
>
> **工作原理：**
>
> 1. 第一次请求：系统提示词、工具和用户消息被发送到 API 并进行缓存
>
> 2. 第二次请求：从缓存中检索缓存內容。只需要处理新消息
>
> 3. 此模式会持续应用于每一轮，每个请求都会重用缓存的对话历史
>
> > [!NOTE]
> >
> > 提示词缓存通过缓存 Token 来降低 API 成本，但**不**提供对话记忆。要在调用之间持久化对话历史，请使用 [检查点](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/persistence.md#checkpointer-libraries)，例如 `MemorySaver`。
>
> ```typescript theme={null}
> import { createAgent, bedrockPromptCachingMiddleware, AIMessage, HumanMessage, tool } from "langchain";
> import { ChatBedrockConverse } from "@langchain/aws";
> import { z } from "zod";
>
> const getWeather = tool(
>   async ({ city }) => `The weather in ${city} is sunny and 72F.`,
>   {
>     name: "get_weather",
>     description: "Get the current weather for a city.",
>     schema: z.object({ city: z.string() }),
>   }
> );
>
> // System prompt must exceed 1,024 tokens for caching to take effect
> const LONG_PROMPT =
>   "You are a helpful weather assistant with deep expertise in meteorology, " +
>   "climate science, and atmospheric phenomena. When answering questions about " +
>   "weather, provide accurate and up-to-date information. " +
>   "You should always strive to give the most helpful response possible. ".repeat(85);
>
> const agent = createAgent({
>   model: new ChatBedrockConverse({ model: "us.anthropic.claude-sonnet-4-5-20250929-v1:0" }),
>   systemPrompt: LONG_PROMPT,
>   tools: [getWeather],
>   middleware: [bedrockPromptCachingMiddleware({ ttl: "5m" })], // [!code highlight]
> });
>
> // First invocation: writes the cache (system prompt, tool definitions, and message)
> let response = await agent.invoke({
>   messages: [new HumanMessage("What is the weather in Miami?")],
> });
> const last = response.messages.at(-1);
> console.log(last?.content);
>
> // Check cache token usage
> if (AIMessage.isInstance(last)) {
>   const details = last.usage_metadata?.input_token_details;
>   if (details) {
>     console.log(`Cache read: ${details.cache_read ?? 0}, Cache write: ${details.cache_creation ?? 0}`);
>   }
> }
>
> // Second invocation within the TTL: reuses the cached system prompt and tool definitions
> response = await agent.invoke({
>   messages: [new HumanMessage("How about Seattle?")],
> });
> console.log(response.messages.at(-1)?.content);
> ```

### 模型特定行为

中间件会自动处理不同模型系列之间的差异：

| 功能 | ChatBedrockConverse (Anthropic) | ChatBedrockConverse (Nova) |
| - | :-: | :-: |
| 系统提示词缓存 | ✅ | ✅ |
| 工具定义缓存 | ✅ | ❌ |
| 消息缓存 | ✅ | ✅ (不包括工具结果消息) |
| 扩展 TTL (`1h`) | ✅ | ❌ |

***

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


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