AWS 미들웨어 통합

AWS 미들웨어 통합

LangChain JavaScript로 AWS 미들웨어와 통합하는 방법을 알아봅니다.

AWS Bedrock에 호스팅된 모델을 위해 특별히 설계된 미들웨어예요. 미들웨어에 대해 더 알아보세요.

출처: 문서

본문

미들웨어(Middleware) 설명(Description)
프롬프트 캐싱(Prompt caching) 반복되는 프롬프트 접두사를 캐싱해 비용 절감

프롬프트 캐싱(Prompt caching)

자주 재사용되는 프롬프트 접두사를 Amazon Bedrock에 캐싱해 추론 지연 시간과 입력 토큰 비용을 줄입니다. bedrockPromptCachingMiddlewaremodelSettings를 통해 캐싱을 활성화합니다. 그러면 ChatBedrockConverse가 요청 시점에 이를 올바른 AWS 와이어 형식으로 변환합니다. 캐시 체크포인트는 지원되는 경우 시스템 프롬프트, 도구 정의, 그리고 가장 최근 메시지 뒤에 배치되어, 모델이 후속 요청에서 이전에 본 콘텐츠를 다시 계산하지 않아도 됩니다. 캐시 배치는 모델군에 따라 달라집니다. 예를 들어 Nova는 일부 도구 정의와 도구 결과 케이스를 건너뜁니다.

프롬프트 캐싱은 다음과 같은 경우에 유용합니다:

  • 길고 일관된 시스템 프롬프트가 있는 다중 턴 대화
  • 호출 간에 일정하게 유지되는 많은 도구 정의가 있는 에이전트
  • 동일한 업로드 컨텍스트에 대해 여러 질문을 하는 문서 기반 Q&A
  • 반복되는 정적 콘텐츠가 있는 배치 처리 워크로드

지원 모델:

  • Anthropic Claude
  • Amazon Nova

AWS Bedrock 프롬프트 캐싱 전략과 제한 사항에 대해 더 알아보세요. 캐시 체크포인트가 적용되려면 캐시된 콘텐츠가 1,024 토큰을 초과해야 하며, 모델에 따라 더 많을 수도 있습니다. 지원 모델, 리전 및 제한을 참조하세요.

API reference: BedrockPromptCachingMiddleware

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]
});
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]
});

구성 옵션(Configuration options)

enableCaching (boolean, default true): 프롬프트 캐싱을 적용할지 여부.

ttl (string, default 5m): 캐시된 콘텐츠의 유효 기간(Time to live). 유효한 값은 '5m' 또는 '1h'입니다. Amazon Nova 모델은 '5m'만 지원합니다.

minMessagesToCache (number, default 1): 캐싱이 시작되기 전 최소 메시지 수. 시스템 프롬프트가 하나의 메시지로 계산됩니다.

unsupportedModelBehavior (string, default warn): 지원되지 않는 모델을 사용할 때의 동작. 옵션: 'ignore', 'warn', 'raise'.

전체 예제(Full example)

미들웨어는 각 요청의 최신 메시지까지 포함해 콘텐츠를 캐시합니다. TTL 창(5분 또는 1시간) 내의 후속 요청에서는 이전에 본 콘텐츠를 재처리하는 대신 캐시에서 가져오므로 비용과 지연 시간이 줄어듭니다.

작동 방식:

  1. 첫 번째 요청: 시스템 프롬프트, 도구, 사용자 메시지가 API로 전송되어 캐시됨
  2. 두 번째 요청: 캐시된 콘텐츠가 캐시에서 조회됨. 새 메시지만 처리하면 됨
  3. 이 패턴이 각 턴마다 이어지며, 각 요청이 캐시된 대화 기록을 재사용함

프롬프트 캐싱은 토큰을 캐싱해 API 비용을 줄이지만 대화 메모리를 제공하지는 않습니다. 호출 간 대화 기록을 유지하려면 MemorySaver 같은 체크포인터를 사용하세요.

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);

모델별 동작(Model-specific behavior)

미들웨어는 모델군 간 차이를 자동으로 처리합니다:

기능(Feature) ChatBedrockConverse (Anthropic) ChatBedrockConverse (Nova)
시스템 프롬프트 캐싱(System prompt caching)
도구 정의 캐싱(Tool definition caching)
메시지 캐싱(Message caching) ✅ (도구 결과 메시지 제외)
확장 TTL(1h)

더 알아보기 (Learn more)