Anthropic 통합

Anthropic 통합

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

Anthropic의 Claude 모델을 위해 특별히 설계된 미들웨어예요. 미들웨어에 대해 더 알아보세요.

출처: 문서

본문

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

프롬프트 캐싱(Prompt caching)

정적이거나 반복적인 프롬프트 내용(시스템 프롬프트, 도구 정의, 대화 기록 등)을 Anthropic 서버에 캐싱해 비용과 지연 시간을 줄입니다. 이 미들웨어는 시스템 메시지, 도구 정의, 그리고 가장 최근 사용자 메시지에 명시적 캐시 중단점(cache breakpoints)을 배치하는 **대화형 캐싱 전략(conversational caching strategy)**을 구현하여, 전체 대화 기록을 캐시해 이후 API 호출에서 재사용할 수 있게 합니다.

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

  • 요청 간에 변하지 않는 길고 정적인 시스템 프롬프트가 있는 애플리케이션
  • 호출 간에 일정하게 유지되는 많은 도구 정의가 있는 에이전트
  • 초기 메시지 기록이 여러 턴에 걸쳐 재사용되는 대화
  • API 비용과 지연 시간 절감이 중요한 대용량 배포

더 단순한 사용 사례라면 미들웨어 없이 호출 시점에 cache_control을 전달해 채팅 모델에서 프롬프트 캐싱을 사용할 수도 있어요. 시스템 프롬프트와 도구 정의의 캐시 중단점을 명시적으로 제어해야 할 때 미들웨어를 권장합니다.

Anthropic 프롬프트 캐싱 전략과 제한 사항에 대해 더 알아보세요.

import { createAgent, anthropicPromptCachingMiddleware } from "langchain";

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

구성 옵션(Configuration options)

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

전체 예제(Full example)

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

작동 방식:

  1. 첫 번째 요청: 시스템 프롬프트, 도구, 사용자 메시지 *"Hi, my name is Bob"*가 API로 전송되어 캐시됨
  2. 두 번째 요청: 캐시된 콘텐츠(시스템 프롬프트, 도구, 첫 번째 메시지)가 캐시에서 조회됨. 새 메시지 *"What's my name?"*와 첫 번째 요청의 모델 응답만 처리하면 됨
  3. 이 패턴이 각 턴마다 이어지며, 각 요청이 캐시된 대화 기록을 재사용함
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?")]
});

더 알아보기 (Learn more)