Anthropic Chat
Anthropic Chat
Spring AI는 공식 Anthropic Java SDK를 통해 Anthropic의 Claude 모델을 지원해요. 이 SDK로 Claude를 Anthropic API를 통해 사용할 수 있어요.
출처: 공식문서
사전 준비
저장소와 BOM 추가
Spring AI 아티팩트는 Maven Central과 Spring Snapshot 저장소에 게시돼요. Artifact Repositories 섹션을 참고해 빌드 시스템에 저장소를 추가해요. 의존성 관리를 위해 Spring AI는 일관된 버전을 보장하는 BOM을 제공해요. Dependency Management 섹션을 참고해 추가해요.
자동 설정 (Auto-configuration)
spring-ai-starter-model-anthropic 스타터를 통해 Spring Boot 자동 설정이 제공돼요.
- Maven
- Gradle
Maven pom.xml에 추가해요.
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
또는 Gradle build.gradle에 추가해요.
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-anthropic'
}
구성 속성
Anthropic 연결과 채팅 옵션을 구성하려면 spring.ai.anthropic.* 속성을 사용해요.
구성 속성
| 속성 | 설명 | 기본값 |
|---|---|---|
| spring.ai.anthropic.api-key | Anthropic API 키 | - |
| spring.ai.anthropic.base-url | API 기본 URL | |
| spring.ai.anthropic.timeout | 시작 시 공유 HTTP 클라이언트에 구워 넣는 기본 타임아웃. AnthropicChatOptions.timeout()으로 ChatClient에 설정하거나 요청별 프롬프트 옵션으로 호출마다 재정의 가능 | 60s |
| spring.ai.anthropic.max-retries | 실패한 요청의 최대 재시도 횟수 | 2 |
| spring.ai.anthropic.custom-headers.* | 모든 Anthropic 클라이언트 요청에 추가할 사용자 정의 HTTP 헤더 | - |
| spring.ai.anthropic.chat.model | 모델 이름 | claude-haiku-4-5 |
| spring.ai.anthropic.chat.max-tokens | 최대 토큰 수 | 4096 |
| spring.ai.anthropic.chat.temperature | 샘플링 온도 | - |
| spring.ai.anthropic.chat.top-p | Top-p 샘플링 | - |
| spring.ai.anthropic.chat.top-k | Top-k 샘플링 | - |
| spring.ai.anthropic.chat.cache-options.strategy | 사용할 캐싱 전략 | NONE |
| spring.ai.anthropic.chat.cache-options.multi-block-system-caching | 각 시스템 메시지에 별도 블록 사용 | false |
| spring.ai.anthropic.chat.http-headers | 개별 API 호출에 전달할 요청별 HTTP 헤더 | - |
| spring.ai.anthropic.chat.inference-geo | 요청이 처리되는 지리적 리전 (us 또는 eu) | - |
| spring.ai.anthropic.chat.web-search-tool.max-uses | 요청당 최대 웹 검색 횟수 | - |
| spring.ai.anthropic.chat.web-search-tool.allowed-domains | 검색 결과를 제한할 도메인의 쉼표 구분 목록 | - |
| spring.ai.anthropic.chat.web-search-tool.blocked-domains | 검색 결과에서 제외할 도메인의 쉼표 구분 목록 | - |
| spring.ai.anthropic.chat.web-search-tool.user-location.city | 검색 결과 지역화용 도시 | - |
| spring.ai.anthropic.chat.web-search-tool.user-location.country | ISO 3166-1 alpha-2 국가 코드 | - |
| spring.ai.anthropic.chat.web-search-tool.user-location.region | 지역 또는 주 | - |
| spring.ai.anthropic.chat.web-search-tool.user-location.timezone | IANA 타임존 식별자 | - |
| spring.ai.anthropic.chat.service-tier | 용량 라우팅: auto(가능하면 priority 사용) 또는 standard_only(항상 standard). Service Tiers 참고 | - |
수동 설정
AnthropicChatModel은 ChatModel 인터페이스를 구현하고, Claude에 연결하기 위해 공식 Anthropic Java SDK를 사용해요.
- Maven
- Gradle
Maven pom.xml에 spring-ai-anthropic 의존성을 추가해요.
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-anthropic</artifactId>
</dependency>
또는 Gradle build.gradle에 추가해요.
dependencies {
implementation 'org.springframework.ai:spring-ai-anthropic'
}
인증
API 키를 프로그래밍 방식으로 또는 환경 변수로 구성해요.
var chatOptions = AnthropicChatOptions.builder()
.model("claude-sonnet-4-20250514")
.maxTokens(1024)
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.build();
var chatModel = AnthropicChatModel.builder()
.options(chatOptions)
.build();
또는 환경 변수를 설정하고 SDK가 자동 감지하게 할 수 있어요.
export ANTHROPIC_API_KEY=<your-api-key>
// API key will be detected from ANTHROPIC_API_KEY environment variable
var chatModel = AnthropicChatModel.builder()
.options(AnthropicChatOptions.builder()
.model("claude-sonnet-4-20250514")
.maxTokens(1024)
.build())
.build();
기본 사용법
ChatResponse response = chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
// Or with streaming responses
Flux<ChatResponse> stream = chatModel.stream(
new Prompt("Generate the names of 5 famous pirates."));
런타임 옵션
시작 시 AnthropicChatModel.builder().defaultOptions(options).build() 생성자로 기본 옵션을 구성해요.
런타임에는 Prompt 호출에 요청별 옵션을 추가해 기본값을 덮어쓸 수 있어요. 특정 요청의 기본 모델과 temperature를 덮어쓰는 예시예요.
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
AnthropicChatOptions.builder()
.model("claude-sonnet-4-20250514")
.temperature(0.4)
.build()
));
채팅 옵션
채팅 옵션
| 옵션 | 설명 | 기본값 |
|---|---|---|
| model | 사용할 Claude 모델 이름. claude-sonnet-4-20250514, claude-opus-4-20250514, claude-3-5-sonnet-20241022, claude-3-5-haiku-20241022 등. Claude Models 참고 | claude-sonnet-4-20250514 |
| maxTokens | 응답에서 생성할 최대 토큰 수 | 4096 |
| temperature | 응답의 무작위성 제어. 높을수록 무작위, 낮을수록 결정적. 범위: 0.0-1.0 | 1.0 |
| topP | Nucleus sampling 파라미터. top_p 확률 질량을 가진 토큰을 고려. Claude Opus 4.6 및 이전 모델에서만 지원. Anthropic이 Claude Opus 4.6 이후 릴리스 모델(예: claude-opus-4-7)에 대해 deprecated. < 0.99 값은 HTTP 400으로 거부, >= 0.99 값은 하위 호환 no-op(실제 필터링 없음)로 수용 | - |
| topK | 각 토큰에 대해 상위 K개 옵션에서만 샘플링. Claude Opus 4.6 및 이전 모델에서만 지원. Claude Opus 4.6 이후 릴리스 모델(예: claude-opus-4-7)에 대해 deprecated. 해당 모델에서는 어떤 값이든 HTTP 400으로 거부 | - |
| stopSequences | 모델이 생성을 중지하게 하는 사용자 정의 시퀀스 | - |
| apiKey | 인증용 API 키. 설정하지 않으면 ANTHROPIC_API_KEY 환경 변수에서 자동 감지 | - |
| baseUrl | Anthropic API 기본 URL | |
| timeout | 호출별 타임아웃 재정의. ChatClient.Builder.defaultOptions()나 요청별 ChatClient.prompt().options(...)로 설정하면 해당 호출만 제한하고 spring.ai.anthropic.timeout 시작 시 기본값을 재정의 | 60 seconds |
| maxRetries | 실패한 요청의 최대 재시도 횟수 | 2 |
| proxy | HTTP 클라이언트용 프록시 설정 | - |
| customHeaders | 모든 요청에 포함할 사용자 정의 HTTP 헤더 (클라이언트 수준) | - |
| httpHeaders | 요청별 HTTP 헤더. MessageCreateParams.putAdditionalHeader()를 통해 개별 API 호출에 추가. 요청 수준 추적, beta API 헤더, 라우팅에 유용 | - |
| cacheOptions | 프롬프트 캐싱 동작 구성. 캐싱 전략, 멀티 블록 캐싱, TTL, 콘텐츠 길이 요구사항 포함 | - |
| thinking | Thinking 구성. 편의 빌더 thinkingEnabled(budgetTokens), thinkingEnabled(budgetTokens, display), thinkingAdaptive(), thinkingAdaptive(display), thinkingDisabled() 또는 raw ThinkingConfigParam 사용. display 파라미터는 thinking 콘텐츠가 응답에 나타나는 방식 제어: SUMMARIZED(요약) 또는 OMITTED(서명만) | - |
| outputConfig | 구조화 출력(JSON 스키마)과 effort 제어용 출력 구성. outputConfig(OutputConfig)로 완전 제어, 또는 편의 메서드 outputSchema(String)·effort(OutputConfig.Effort). claude-sonnet-4-6 이상 필요 | - |
| inferenceGeo | 요청이 처리되는 지리적 리전 제어. 지원 값: us, eu. 데이터 레지던시 규정 준수에 사용. spring.ai.anthropic.chat.inference-geo로 구성 가능 | - |
| serviceTier | 요청의 용량 라우팅 제어. MessageCreateParams.ServiceTier.AUTO로 우선 용량을 기회주의적으로 사용하거나 STANDARD_ONLY로 항상 표준 용량 사용 | - |
도구 호출 옵션
도구 호출 옵션
| 옵션 | 설명 | 기본값 |
|---|---|---|
| toolChoice | 모델이 호출하는 도구(있는 경우) 제어. ToolChoiceAuto, ToolChoiceAny, ToolChoiceTool, ToolChoiceNone 사용 | AUTO |
| toolCallbacks | 모델에 등록할 도구 콜백 목록 | - |
| disableParallelToolUse | true면 응답당 최대 1개 도구만 사용 | false |
Rate Limit 메타데이터
Anthropic API는 모든 응답에 rate limit 헤더를 포함하는데, 현재 요청·토큰 예산과 각 창이 언제 리셋되는지 보고해요. Spring AI는 표준 ChatResponseMetadata#getRateLimit() 접근자를 통해 이 데이터를 노출해요. 이 메서드는 응답 헤더에서 채워진 AnthropicRateLimit을 반환해요.
이식 가능한 RateLimit 인터페이스는 요청·토큰 계열을 노출해요.
ChatResponse response = chatModel.call(prompt);
RateLimit rateLimit = response.getMetadata().getRateLimit();
rateLimit.getRequestsLimit(); // overall request ceiling
rateLimit.getRequestsRemaining(); // requests left in the current window
rateLimit.getRequestsReset(); // time until the request window resets
rateLimit.getTokensLimit(); // overall token ceiling
rateLimit.getTokensRemaining(); // tokens left in the current window
rateLimit.getTokensReset(); // time until the token window resets
Anthropic은 입력 토큰과 출력 토큰에 대해 별도의 버킷도 보고해요. 이는 AnthropicRateLimit 구체 타입으로 노출돼요.
원시 응답 접근
전체 Anthropic SDK Message 객체는 응답 메타데이터의 "anthropic-response" 키 아래에서 사용할 수 있어요. 이로써 Spring AI 추상화가 명시적으로 매핑하지 않은 모든 필드에 접근할 수 있어요.
ChatResponse response = chatModel.call(new Prompt("Hello"));
com.anthropic.models.messages.Message rawMessage =
(com.anthropic.models.messages.Message) response.getMetadata().get("anthropic-response");
// Access native SDK fields
rawMessage.stopReason(); // Optional<StopReason>
rawMessage.content(); // List<ContentBlock>
rawMessage.usage(); // Usage with cache token details
원시 응답은 동기 호출에서만 사용할 수 있어요. 스트리밍 응답에는 포함되지 않아요.
Skills
Anthropic의 Skills API는 Claude의 기능을 문서 생성용 특화·사전 패키징 능력으로 확장해요. Skills를 사용하면 Claude가 그냥 문서가 무엇인지 설명하는 게 아니라 실제 다운로드 가능한 파일(Excel 스프레드시트, PowerPoint 프레젠테이션, Word 문서, PDF)을 만들게 돼요.
지원 모델 — Skills는 Claude Sonnet 4, Claude Sonnet 4.5, Claude Opus 4 및 이후 모델에서 지원돼요. 요구사항 — Skills는 코드 실행 능력이 필요해요(Skills 구성 시 Spring AI가 자동 활성화). 요청당 최대 8개 Skills. 생성된 파일은 Files API를 통해 24시간 동안 다운로드 가능.
사전 구축 Anthropic Skills
Spring AI는 AnthropicSkill enum을 통해 Anthropic의 사전 구축 Skills에 타입 안전 접근을 제공해요.
| Skill | 설명 | 생성 파일 유형 |
|---|---|---|
XLSX |
Excel 스프레드시트 생성·조작 | .xlsx (Microsoft Excel) |
PPTX |
PowerPoint 프레젠테이션 생성 | .pptx (Microsoft PowerPoint) |
DOCX |
Word 문서 생성 | .docx (Microsoft Word) |
PDF |
PDF 문서 생성 | .pdf (Portable Document Format) |
기본 사용법
AnthropicChatOptions에 Skills를 추가해 활성화해요.
ChatResponse response = chatModel.call(
new Prompt(
"Create an Excel spreadsheet with Q1 2025 sales data. " +
"Include columns for Month, Revenue, and Expenses with 3 rows of sample data.",
AnthropicChatOptions.builder()
.model(Model.CLAUDE_SONNET_4_5)
.maxTokens(4096)
.skill(AnthropicSkill.XLSX)
.build()
)
);
// Claude will generate an actual Excel file
String responseText = response.getResult().getOutput().getText();
System.out.println(responseText);