Anthropic Claude Chat
Spring AI 2.1 的 AnthropicChatModel 使用 Anthropic Java SDK 3.x。它支持同步和流式聊天、工具调用、提示词缓存,以及适配型号上的扩展思考和结构化输出。
安装与首次调用
在 Spring AI BOM 下添加 starter。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
设置 ANTHROPIC_API_KEY,再配置模型与输出上限。
spring:
ai:
model:
chat: anthropic
anthropic:
api-key: ${ANTHROPIC_API_KEY}
timeout: 60s
chat:
model: claude-haiku-4-5
max-tokens: 2048
从容器注入 ChatClient.Builder 后构造客户端。options(...) 接收 Builder,并覆盖当前请求的选项。切换到自有 Anthropic 兼容端点时,配置 spring.ai.anthropic.base-url 及该服务的 Key 和模型 ID。
var chatClient = chatClientBuilder.build();
ChatResponse response = chatClient.prompt()
.user("将这条工单归纳为一个标题")
.options(AnthropicChatOptions.builder().maxTokens(256))
.call()
.chatResponse();
Flux<String> text = chatClient.prompt().user("列出三个排障步骤").stream().content();
需要工具、结束状态和用量时,使用 chatResponse() 或 stream().chatResponse()。spring.ai.anthropic.timeout 是共享 SDK 客户端的默认超时,也可在请求中用 AnthropicChatOptions.Builder.timeout(Duration) 覆盖。Spring AI Anthropic Chat 参考
提示词缓存
可通过 spring.ai.anthropic.chat.cache-options.strategy=SYSTEM_ONLY 配置默认策略,或在 Java 中构建 AnthropicCacheOptions。根据需要稳定复用的前缀选取策略。缓存断点数受 Anthropic 的单请求上限约束。
AnthropicCacheStrategy | 适用的稳定内容 |
|---|---|
NONE | 默认不加显式断点 |
SYSTEM_ONLY | 系统消息及引用文档 |
TOOLS_ONLY | 工具定义 |
SYSTEM_AND_TOOLS | 系统消息、引用文档与工具定义 |
CONVERSATION_HISTORY | 到当前问题之前为止的对话前缀 |
import org.springframework.ai.anthropic.AnthropicCacheOptions;
import org.springframework.ai.anthropic.AnthropicCacheStrategy;
import org.springframework.ai.anthropic.AnthropicCacheTtl;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.chat.messages.MessageType;
var cacheOptions = AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.messageTypeTtl(MessageType.SYSTEM, AnthropicCacheTtl.ONE_HOUR)
.build();
ChatResponse response = chatClient.prompt()
.system(stableInstructions)
.user("从这些规则中找出审批条件")
.options(AnthropicChatOptions.builder().cacheOptions(cacheOptions))
.call()
.chatResponse();
var usage = response.getMetadata().getUsage();
Long readTokens = usage.getCacheReadInputTokens();
Long writeTokens = usage.getCacheWriteInputTokens();
stableInstructions 是每次请求都相同并满足模型缓存长度要求的指令。通过缓存读写量验证是否命中。构建器也支持 5 分钟 TTL、按消息类型设置最短内容长度,以及通过 multiBlockSystemCaching(true) 把多条系统消息分块。Anthropic Prompt Caching