最新快照版本请使用Spring AI 1.1.0spring-doc.cadn.net.cn

人类对话

Anthropic Claude 是一系列基础性的人工智能模型,可用于多种应用。 对于开发者和企业来说,你可以利用API访问,直接在Anthropic的AI基础设施上构建。spring-doc.cadn.net.cn

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

Anthropic的Claude型号也可以通过亚马逊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 密钥从 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 表达式语言(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");

添加仓库和物料清单

Spring AI 产物发布于 Maven Central 和 Spring Snapshot 仓库中。 请参阅神器仓库部分,将这些仓库添加到你的构建系统中。spring-doc.cadn.net.cn

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

自动配置

春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Anthropic Chat 客户端提供 Spring Boot 自动配置。 要启用它,请在项目的Maven中添加以下依赖pom.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的物料清单添加到你的构建文件中。

聊天属性

重试属性

前缀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.initial-intervalspring-doc.cadn.net.cn

指数式退避政策的初始睡眠时长。spring-doc.cadn.net.cn

两秒钟。spring-doc.cadn.net.cn

spring.ai.retry.backoff.multiplierspring-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-errorsspring-doc.cadn.net.cn

如果为假,抛出非瞬态AiException,且不要尝试重试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-codesspring-doc.cadn.net.cn

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

emptyspring-doc.cadn.net.cn

目前重试策略不适用于流媒体API。

连接性质

前缀春.ai.人类作为属性前缀,允许你连接到Anthropic。spring-doc.cadn.net.cn

属性 描述 默认值

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

连接的URL(链接)spring-doc.cadn.net.cn

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

spring.ai.anthropic.completions-pathspring-doc.cadn.net.cn

附加到基础URL的路径。spring-doc.cadn.net.cn

/v1/聊天/完成spring-doc.cadn.net.cn

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

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

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

spring.ai.anthropic.api-key。spring-doc.cadn.net.cn

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

-spring-doc.cadn.net.cn

spring.ai.anthropic.beta-version(春.ai.人类.beta版)spring-doc.cadn.net.cn

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

工具-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

启用拟人聊天模式。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.chatspring-doc.cadn.net.cn

启用拟人聊天模式。spring-doc.cadn.net.cn

人为spring-doc.cadn.net.cn

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

这就是拟人聊天的模型。支持:克洛德作品-4-0,克洛德十四行诗-4-0,Claude-3-7-Sonnet-latest,Claude-3-5-Sonnet-latest,Claude-3-opus-20240229,克劳德-3-十四行诗-20240229,Claude-3-Haiku-20240307,Claude-3-7-Sonnet-latest,克劳德十四行诗-4-20250514,克劳德作品-4-1-20250805spring-doc.cadn.net.cn

克劳德作品-4-20250514spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.temperature.temperaturespring-doc.cadn.net.cn

采样温度决定了生成完备的显得创造力。值越高,输出越随机,值越低,结果越聚焦且确定性强。不建议对相同的完井请求调整温度和top_p,因为这两种设置的相互作用难以预测。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.max标记spring-doc.cadn.net.cn

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

500spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.stop-sequencespring-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

使用核抽样。在核抽样中,我们计算每个后续Tokens的累积分布,按递减概率顺序计算,并在达到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

每个后续Tokens只从顶部的K个选项中抽样。用于消除“长尾”低概率反应。点击这里了解更多技术细节。仅推荐用于高级应用场景。通常只需要用温度。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.anthropic.chat.options.toolNamesspring-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

工具回调以注册到聊天模型。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

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

如果错误,Spring AI不会内部处理工具调用,而是代理给客户端。然后由客户端负责处理工具调用,将其派遣到相应函数,并返回结果。如果为真(默认),Spring AI会在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

(已弃用——被工具名称) spring.ai.anthropic.chat.options.functionsspring-doc.cadn.net.cn

函数列表,按名称标识,以便实现函数调用,只需一次提示请求。带有这些名称的函数必须存在于函数回调注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

(已弃用——被tool回调) spring.ai.anthropic.chat.options.functionCallbacksspring-doc.cadn.net.cn

工具函数回调以注册到聊天模型。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

(弃用 - 被否定内部工具执行启用) spring.ai.anthropic.chat.options.proxy-tool-callsspring-doc.cadn.net.cn

如果属实,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可以通过在运行时为 在提示叫。

运行时选项

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

启动时,默认选项可以配置为AnthropicChatModel(api,options)构造者或spring.ai.anthropic.chat.options.*性能。spring-doc.cadn.net.cn

运行时,你可以通过添加新的、请求专属的选项来覆盖默认选项,提示叫。 例如,针对特定请求覆盖默认型号和温度: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实例。

思维

拟人Claude模型支持“思考”功能,允许模型展示其推理过程,然后再给出最终答案。这一功能使问题解决更加透明和细致,尤其适用于需要逐步推理的复杂问题。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. 添加思维对象: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

关于交错思维与工具使用的详细信息,请参见人类文献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

工具/函数调用

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

模 态

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

图像

目前,Anthropic Claude 3 支持基地64来源类型图像,以及图片/jpeg,图片/PNG,图片/动图image/webp媒体类型。 更多信息请查看视力指南。 拟人克劳德3.5十四行诗也支持:PDF格式来源类型申请表/PDF文件。spring-doc.cadn.net.cn

春季 AI消息界面通过引入媒体类型支持多模态 AI 模型。 这种类型包含关于消息中媒体附件的数据和信息,使用 Spring 的org.springframework.util.MimeType以及一个java.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 支持(测试版)。 使用该申请表/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)));

采样控制器

创建一个新的 Spring Boot 项目并添加春-AI-入门-模型-拟人对你的POM(或Gradle)依赖。spring-doc.cadn.net.cn

添加一个application.properties文件,在src/主/资源目录,用于启用和配置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密钥凭你的人类身份。

这将产生人类聊天模型你可以把这些实现注入到你的类里。 这里有一个简单的例子@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 实现了聊天模型StreamingChatModel并使用低级 AnthropicApi 客户端连接 Anthropic 服务。spring-doc.cadn.net.cn

添加春艾人类对你项目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的物料清单添加到你的构建文件中。

接下来,创建一个人类聊天模型并用于文本生成: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.Builder是流利期权构建器。spring-doc.cadn.net.cn

低级 AnthropicApi 客户端

AnthropicApi 提供了一个轻量级的 Anthropic 消息 API 客户端。spring-doc.cadn.net.cn

以下类图展示了人类Api聊天界面与构建模块: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示例