此版本仍在开发中,尚不被认为是稳定的。对于最新的快照版本,请使用 Spring AI 1.0.1spring-doc.cadn.net.cn

人类聊天

Anthropic Claude 是一系列基础 AI 模型,可用于各种应用。 对于开发人员和企业,您可以利用 API 访问并直接在 Anthropic 的 AI 基础设施之上进行构建。spring-doc.cadn.net.cn

Spring AI 支持 Anthropic Messaging API 用于同步和流式文本生成。spring-doc.cadn.net.cn

Anthropic 的 Claude 模型也可通过 Amazon Bedrock Converse 获得。 Spring AI 还提供专用的 Amazon Bedrock Converse Anthropic 客户端实现。

前提条件

您需要在 Anthropic 门户上创建一个 API 密钥。spring-doc.cadn.net.cn

Anthropic API 仪表板上创建一个帐户,并在获取 API 密钥页面上生成 API 密钥。spring-doc.cadn.net.cn

Spring AI 项目定义了一个名为spring.ai.anthropic.api-key您应该将API Key获得于 anthropic.com。spring-doc.cadn.net.cn

您可以在application.properties文件:spring-doc.cadn.net.cn

spring.ai.anthropic.api-key=<your-anthropic-api-key>

为了在处理 API 密钥等敏感信息时增强安全性,您可以使用 Spring Expression Language (SpEL) 来引用自定义环境变量:spring-doc.cadn.net.cn

# In application.yml
spring:
  ai:
    anthropic:
      api-key: ${ANTHROPIC_API_KEY}
# In your environment or .env file
export ANTHROPIC_API_KEY=<your-anthropic-api-key>

您还可以在应用程序代码中以编程方式获取此配置:spring-doc.cadn.net.cn

// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("ANTHROPIC_API_KEY");

添加存储库和 BOM

Spring AI 工件发布在 Maven Central 和 Spring Snapshot 存储库中。 请参阅 Artifact Repositories 部分,将这些存储库添加到您的构建系统中。spring-doc.cadn.net.cn

为了帮助进行依赖管理,Spring AI 提供了 BOM(物料清单),以确保在整个项目中使用一致的 Spring AI 版本。请参阅依赖项管理部分,将 Spring AI BOM 添加到您的构建系统中。spring-doc.cadn.net.cn

自动配置

Spring AI 自动配置、入门模块的工件名称发生了重大变化。 有关更多信息,请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Anthropic Chat 客户端提供 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到项目的 Mavenpom.xml或 Gradlebuild.gradle文件:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-anthropic'
}
请参阅依赖项管理部分,将 Spring AI BOM 添加到构建文件中。

聊天属性

重试属性

前缀spring.ai.retry用作属性前缀,用于配置 Anthropic 聊天模型的重试机制。spring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.retry.max次尝试spring-doc.cadn.net.cn

重试尝试的最大次数。spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

spring.ai.retry.backoff.初始间隔spring-doc.cadn.net.cn

指数退避策略的初始睡眠持续时间。spring-doc.cadn.net.cn

2 秒。spring-doc.cadn.net.cn

spring.ai.retry.backoff.乘数spring-doc.cadn.net.cn

回退间隔乘数。spring-doc.cadn.net.cn

5spring-doc.cadn.net.cn

spring.ai.retry.backoff.max间隔spring-doc.cadn.net.cn

最大回退持续时间。spring-doc.cadn.net.cn

3分钟spring-doc.cadn.net.cn

spring.ai.retry.on-client-错误spring-doc.cadn.net.cn

如果为 false,则引发 NonTransientAiException,并且不要尝试重试4xx客户端错误代码spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.retry.exclude-on-http-codesspring-doc.cadn.net.cn

不应触发重试的 HTTP 状态代码列表(例如,抛出 NonTransientAiException)。spring-doc.cadn.net.cn

emptyspring-doc.cadn.net.cn

spring.ai.retry.on-http-代码spring-doc.cadn.net.cn

应触发重试的 HTTP 状态代码列表(例如,抛出 TransientAiException)。spring-doc.cadn.net.cn

emptyspring-doc.cadn.net.cn

目前,重试策略不适用于流式处理 API。

连接属性

前缀spring.ai.anthropic用作允许您连接到 Anthropic 的属性前缀。spring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.anthropic.base-urlspring-doc.cadn.net.cn

要连接到的 URLspring-doc.cadn.net.cn

api.anthropic.comspring-doc.cadn.net.cn

spring.ai.anthropic.completions-路径spring-doc.cadn.net.cn

要追加到基本 URL 的路径。spring-doc.cadn.net.cn

/v1/chat/completionsspring-doc.cadn.net.cn

spring.ai.anthropic.versionspring-doc.cadn.net.cn

Anthropic API 版本spring-doc.cadn.net.cn

2023-06-01spring-doc.cadn.net.cn

spring.ai.anthropic.api-keyspring-doc.cadn.net.cn

API 密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.beta-versionspring-doc.cadn.net.cn

启用新功能/实验性功能。如果设置为max-tokens-3-5-sonnet-2024-07-15输出Tokens限制从40968192Tokens(仅适用于 Claude-3-5-Sonnet)。spring-doc.cadn.net.cn

tools-2024-04-04spring-doc.cadn.net.cn

配置属性

现在,通过前缀为spring.ai.model.chat.spring-doc.cadn.net.cn

要启用,spring.ai.model.chat=anthropic(默认启用)spring-doc.cadn.net.cn

要禁用,spring.ai.model.chat=none(或任何与 anthropic 不匹配的值)spring-doc.cadn.net.cn

进行此更改是为了允许配置多个模型。spring-doc.cadn.net.cn

前缀spring.ai.anthropic.chat是属性前缀,用于配置 Anthropic 的聊天模型实现。spring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.anthropic.chat.enabled(已删除且不再有效)spring-doc.cadn.net.cn

启用 Anthropic 聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.聊天spring-doc.cadn.net.cn

启用 Anthropic 聊天模型。spring-doc.cadn.net.cn

人类spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.modelspring-doc.cadn.net.cn

这是要使用的 Anthropic Chat 模型。 支持:claude-opus-4-0,claude-sonnet-4-0,claude-3-7-sonnet-latest,claude-3-5-sonnet-latest,claude-3-opus-20240229,claude-3-sonnet-20240229,claude-3-haiku-20240307,claude-3-7-sonnet-latest,claude-sonnet-4-20250514,claude-opus-4-1-20250805spring-doc.cadn.net.cn

claude-opus-4-20250514spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.温度spring-doc.cadn.net.cn

要使用的采样温度,用于控制生成的完成的表观创造力。较高的值将使输出更加随机,而较低的值将使结果更加集中和确定。不建议为相同的完成请求修改温度和top_p,因为这两个设置的交互很难预测。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.maxTokensspring-doc.cadn.net.cn

聊天补全时要生成的最大Tokens数。输入标记和生成标记的总长度受模型上下文长度的限制。spring-doc.cadn.net.cn

500spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.stop-序列spring-doc.cadn.net.cn

将导致模型停止生成的自定义文本序列。我们的模型通常会在自然完成轮次后停止,这将导致响应stop_reason为“end_turn”。如果您希望模型在遇到自定义文本字符串时停止生成,则可以使用stop_sequences参数。如果模型遇到其中一个自定义序列,则响应stop_reason值将为“stop_sequence”,响应stop_sequence值将包含匹配的停止序列。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.top-pspring-doc.cadn.net.cn

使用核心采样。在核心采样中,我们按概率递减顺序计算每个后续标记的所有选项的累积分布,并在达到top_p指定的特定概率时将其切断。您应该改变温度或top_p,但不能同时更改两者。仅推荐用于高级用例。您通常只需要使用温度。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.top-kspring-doc.cadn.net.cn

仅从每个后续标记的前 K 个选项中采样。用于删除“长尾”低概率响应。在此处了解更多技术细节。仅建议用于高级用例。通常只需要使用 temperature。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.tool名称spring-doc.cadn.net.cn

工具列表,由其名称标识,以便在单个提示请求中启用工具调用。具有这些名称的工具必须存在于 toolCallbacks 注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.tool回调spring-doc.cadn.net.cn

工具回调以注册 ChatModel。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为 false,则 Spring AI 不会在内部处理工具调用,而是将它们代理给客户端。然后,客户端负责处理工具调用,将它们分派到适当的函数,并返回结果。如果为 true(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

(deprecated - 替换为toolNames) spring.ai.anthropic.chat.options.functionsspring-doc.cadn.net.cn

函数列表,由其名称标识,以便在单个提示请求中启用函数调用。具有这些名称的函数必须存在于 functionCallbacks 注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

(deprecated - 替换为toolCallbacks) spring.ai.anthropic.chat.options.function回调spring-doc.cadn.net.cn

工具函数回调,用于向 ChatModel 注册。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

(deprecated - 替换为 negatedinternal-tool-execution-enabled) spring.ai.anthropic.chat.options.proxy-tool-callsspring-doc.cadn.net.cn

如果为 true,则 Spring AI 不会在内部处理函数调用,而是将它们代理到客户端。然后,客户端负责处理函数调用,将它们分派到适当的函数,并返回结果。如果为 false(默认值),则 Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.http-headersspring-doc.cadn.net.cn

要添加到聊天补全请求的可选 HTTP 标头。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

有关模型别名的最新列表及其描述,请参阅官方 Anthropic 模型别名文档
所有以spring.ai.anthropic.chat.options可以通过将特定于请求的运行时选项添加到Prompt叫。

运行时选项

AnthropicChatOptions.java提供模型配置,例如要使用的模型、温度、最大Tokens数等。spring-doc.cadn.net.cn

启动时,可以使用AnthropicChatModel(api, options)构造函数或spring.ai.anthropic.chat.options.*性能。spring-doc.cadn.net.cn

在运行时,您可以通过向Prompt叫。 例如,要覆盖特定请求的默认模型和温度,请执行以下作:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        AnthropicChatOptions.builder()
            .model("claude-3-7-sonnet-latest")
            .temperature(0.4)
        .build()
    ));
除了特定于模型的 AnthropicChatOptions 之外,您还可以使用使用 ChatOptions#builder() 创建的可移植 ChatOptions 实例。

思维

人类克劳德模型支持“思考”功能,允许模型在提供最终答案之前显示其推理过程。此功能可以实现更透明和详细的问题解决,特别是对于需要逐步推理的复杂问题。spring-doc.cadn.net.cn

支持的型号spring-doc.cadn.net.cn

以下 Claude 模型支持思维功能:spring-doc.cadn.net.cn

模型能力:spring-doc.cadn.net.cn

  • Claude 3.7 十四行诗:返回完整的思维输出。行为是一致的,但不支持总结或交错思维。spring-doc.cadn.net.cn

  • Claude 4 模型:支持总结思维、交错思维和增强工具集成。spring-doc.cadn.net.cn

所有受支持的模型的 API 请求结构都相同,但输出行为各不相同。spring-doc.cadn.net.cn

思维配置

要启用对任何受支持的 Claude 模型的思考,请在您的请求中包含以下配置:spring-doc.cadn.net.cn

所需配置

  1. 添加thinking对象:spring-doc.cadn.net.cn

  2. Tokens预算规则spring-doc.cadn.net.cn

关键考虑因素

工具集成和交错思维

Claude 4 模型支持与工具使用的交错思维,允许模型在工具调用之间进行推理。spring-doc.cadn.net.cn

当前的 Spring AI 实现分别支持基本思维和工具使用,但尚不支持与工具使用的交错思维(其中思维跨多个工具调用继续)。spring-doc.cadn.net.cn

有关交错思维与工具使用的详细信息,请参阅 Anthropic 文档spring-doc.cadn.net.cn

非流式处理示例

以下是如何使用 ChatClient API 在非流式请求中启用思考:spring-doc.cadn.net.cn

ChatClient chatClient = ChatClient.create(chatModel);

// For Claude 3.7 Sonnet - explicit thinking configuration required
ChatResponse response = chatClient.prompt()
    .options(AnthropicChatOptions.builder()
        .model("claude-3-7-sonnet-latest")
        .temperature(1.0)  // Temperature should be set to 1 when thinking is enabled
        .maxTokens(8192)
        .thinking(AnthropicApi.ThinkingType.ENABLED, 2048)  // Must be ≥1024 && < max_tokens
        .build())
    .user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
    .call()
    .chatResponse();

// For Claude 4 models - thinking is enabled by default
ChatResponse response4 = chatClient.prompt()
    .options(AnthropicChatOptions.builder()
        .model("claude-opus-4-0")
        .maxTokens(8192)
        // No explicit thinking configuration needed
        .build())
    .user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
    .call()
    .chatResponse();

// Process the response which may contain thinking content
for (Generation generation : response.getResults()) {
    AssistantMessage message = generation.getOutput();
    if (message.getText() != null) {
        // Regular text response
        System.out.println("Text response: " + message.getText());
    }
    else if (message.getMetadata().containsKey("signature")) {
        // Thinking content
        System.out.println("Thinking: " + message.getMetadata().get("thinking"));
        System.out.println("Signature: " + message.getMetadata().get("signature"));
    }
}

流式处理示例

您还可以将思维与流式响应一起使用:spring-doc.cadn.net.cn

ChatClient chatClient = ChatClient.create(chatModel);

// For Claude 3.7 Sonnet - explicit thinking configuration
Flux<ChatResponse> responseFlux = chatClient.prompt()
    .options(AnthropicChatOptions.builder()
        .model("claude-3-7-sonnet-latest")
        .temperature(1.0)
        .maxTokens(8192)
        .thinking(AnthropicApi.ThinkingType.ENABLED, 2048)
        .build())
    .user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
    .stream();

// For Claude 4 models - thinking is enabled by default
Flux<ChatResponse> responseFlux4 = chatClient.prompt()
    .options(AnthropicChatOptions.builder()
        .model("claude-opus-4-0")
        .maxTokens(8192)
        // No explicit thinking configuration needed
        .build())
    .user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
    .stream();

// For streaming, you might want to collect just the text responses
String textContent = responseFlux.collectList()
    .block()
    .stream()
    .map(ChatResponse::getResults)
    .flatMap(List::stream)
    .map(Generation::getOutput)
    .map(AssistantMessage::getText)
    .filter(text -> text != null && !text.isBlank())
    .collect(Collectors.joining());

工具使用集成

Claude 4 模型集成了思维和工具使用能力:spring-doc.cadn.net.cn

  • Claude 3.7 Sonnet:支持思维和工具使用,但它们是分开作的,需要更显式的配置spring-doc.cadn.net.cn

  • Claude 4 模型:原生交错思维和工具使用,在工具交互过程中提供更深层次的推理spring-doc.cadn.net.cn

使用思维的好处

思考功能提供了几个好处:spring-doc.cadn.net.cn

  1. 透明度:查看模型的推理过程及其得出结论的方式spring-doc.cadn.net.cn

  2. 调试:确定模型可能在哪里出现逻辑错误spring-doc.cadn.net.cn

  3. 教育:使用分步推理作为教学工具spring-doc.cadn.net.cn

  4. 解决复杂问题:在数学、逻辑和推理任务上取得更好的结果spring-doc.cadn.net.cn

请注意,启用思维需要更高的Tokens预算,因为思维过程本身会消耗您分配中的Tokens。spring-doc.cadn.net.cn

工具/函数调用

您可以使用AnthropicChatModel并让 Anthropic Claude 模型智能地选择输出一个 JSON 对象,其中包含调用一个或多个已注册函数的参数。这是一种将 LLM 功能与外部工具和 API 连接起来的强大技术。阅读有关工具调用的更多信息。spring-doc.cadn.net.cn

模 态

多模态是指模型同时理解和处理来自各种来源的信息的能力,包括文本、pdf、图像、数据格式。spring-doc.cadn.net.cn

图像

目前,Anthropic Claude 3 支持base64源类型imagesimage/jpeg,image/png,image/gifimage/webp媒体类型。查看视觉指南了解更多信息。Anthropic Claude 3.5 Sonnet 还支持pdf源类型application/pdf文件。spring-doc.cadn.net.cn

Spring AI 的Message接口通过引入 Media 类型来支持多模态 AI 模型。此类型包含有关消息中媒体附件的数据和信息,使用 Spring 的org.springframework.util.MimeTypejava.lang.Object用于原始媒体数据。spring-doc.cadn.net.cn

下面是从 AnthropicChatModelIT.java 中提取的简单代码示例,演示了用户文本与图像的组合。spring-doc.cadn.net.cn

var imageData = new ClassPathResource("/multimodal.test.png");

var userMessage = new UserMessage("Explain what do you see on this picture?",
        List.of(new Media(MimeTypeUtils.IMAGE_PNG, this.imageData)));

ChatResponse response = chatModel.call(new Prompt(List.of(this.userMessage)));

logger.info(response.getResult().getOutput().getContent());

它将multimodal.test.png图像:spring-doc.cadn.net.cn

多模态测试图像

以及短信“解释一下你在这张照片上看到了什么?”,并生成一个响应,如下所示:spring-doc.cadn.net.cn

The image shows a close-up view of a wire fruit basket containing several pieces of fruit.
...

PDF格式

从 Sonnet 3.5 开始,提供 PDF 支持(测试版)。 使用application/pdf将 PDF 文件附加到邮件的媒体类型:spring-doc.cadn.net.cn

var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");

var userMessage = new UserMessage(
        "You are a very professional document summarization specialist. Please summarize the given document.",
        List.of(new Media(new MimeType("application", "pdf"), pdfData)));

var response = this.chatModel.call(new Prompt(List.of(userMessage)));

Samples控制器

创建一个新的 Spring Boot 项目,并将spring-ai-starter-model-anthropic到你的 pom(或 gradle)依赖项。spring-doc.cadn.net.cn

添加一个application.properties文件,在src/main/resources目录,以启用和配置 Anthropic 聊天模型:spring-doc.cadn.net.cn

spring.ai.anthropic.api-key=YOUR_API_KEY
spring.ai.anthropic.chat.options.model=claude-3-5-sonnet-latest
spring.ai.anthropic.chat.options.temperature=0.7
spring.ai.anthropic.chat.options.max-tokens=450
api-key使用您的 Anthropic 凭据。

这将创建一个AnthropicChatModel实现,您可以注入到类中。 这是一个简单的示例@Controller使用聊天模型生成文本的类。spring-doc.cadn.net.cn

@RestController
public class ChatController {

    private final AnthropicChatModel chatModel;

    @Autowired
    public ChatController(AnthropicChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
	public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return this.chatModel.stream(prompt);
    }
}

手动配置

AnthropicChatModel 实现了ChatModelStreamingChatModel并使用低级 AnthropicApi 客户端连接到 Anthropic 服务。spring-doc.cadn.net.cn

添加spring-ai-anthropic对项目 Maven 的依赖pom.xml文件:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-anthropic</artifactId>
</dependency>

或 Gradlebuild.gradle构建文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-anthropic'
}
请参阅依赖项管理部分,将 Spring AI BOM 添加到构建文件中。

接下来,创建一个AnthropicChatModel并将其用于文本生成:spring-doc.cadn.net.cn

var anthropicApi = new AnthropicApi(System.getenv("ANTHROPIC_API_KEY"));
var anthropicChatOptions = AnthropicChatOptions.builder()
            .model("claude-3-7-sonnet-20250219")
            .temperature(0.4)
            .maxTokens(200)
        .build()
var chatModel = AnthropicChatModel.builder().anthropicApi(anthropicApi)
                .defaultOptions(anthropicChatOptions).build();

ChatResponse response = this.chatModel.call(
    new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = this.chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

AnthropicChatOptions提供聊天请求的配置信息。 这AnthropicChatOptions.Builder是流畅的选项生成器。spring-doc.cadn.net.cn

低级 AnthropicApi 客户端

AnthropicApiAnthropic Message API 提供的轻量级 Java 客户端。spring-doc.cadn.net.cn

以下类图说明了AnthropicApi聊天界面和构建块:spring-doc.cadn.net.cn

AnthropicApi 聊天 API 图
AnthropicApi 事件模型

以下是如何以编程方式使用 API 的简单片段:spring-doc.cadn.net.cn

AnthropicApi anthropicApi =
    new AnthropicApi(System.getenv("ANTHROPIC_API_KEY"));

AnthropicMessage chatCompletionMessage = new AnthropicMessage(
        List.of(new ContentBlock("Tell me a Joke?")), Role.USER);

// Sync request
ResponseEntity<ChatCompletionResponse> response = this.anthropicApi
    .chatCompletionEntity(new ChatCompletionRequest(AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue(),
            List.of(this.chatCompletionMessage), null, 100, 0.8, false));

// Streaming request
Flux<StreamResponse> response = this.anthropicApi
    .chatCompletionStream(new ChatCompletionRequest(AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue(),
            List.of(this.chatCompletionMessage), null, 100, 0.8, true));

请关注AnthropicApi.java的 JavaDoc 以获取更多信息。spring-doc.cadn.net.cn

低级 API 示例