如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

Bedrock Converse API

Amazon Bedrock Converse API 提供了一个统一的接口,用于对话式AI模型,并包含增强功能,如函数/工具调用、多模态输入和流式响应。spring-doc.cadn.net.cn

The Bedrock Converse API 有以下高级特性:spring-doc.cadn.net.cn

The Bedrock Converse API 提供了一个跨多个模型提供商的统一接口,同时处理 AWS 特定的身份验证和基础设施问题。 目前,Converse API 支持的模型 包括: Amazon Titan, Amazon Nova, AI21 Labs, Anthropic Claude, Cohere Command, Meta Llama, Mistral AI

根据 Bedrock 推荐,Spring AI 正在转向使用 Amazon Bedrock 的 Converse API 来实现所有 Spring AI 的聊天对话功能。 虽然现有的 InvokeModel API 支持对话应用,但我们强烈建议采用 Converse API 用于所有的聊天对话模型。spring-doc.cadn.net.cn

The Converse API 不支持嵌入操作,因此这些功能将保持在当前 API 中,并且现有 InvokeModel API 中的嵌入模型功能也将维持不变spring-doc.cadn.net.cn

前置条件

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

将以下依赖添加到项目中的Mavenpom.xml或Gradlebuild.gradle构建文件中: spring-doc.cadn.net.cn

  1. Maven构建文件:spring-ai-starter-model-bedrock-converse
  2. Gradle构建文件:spring-ai-starter-model-bedrock-converse

spring-doc.cadn.net.cn

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

聊天属性

spring.ai.bedrock.aws 前缀是配置连接到 AWS Bedrock 的属性前缀。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.bedrock.aws.regionspring-doc.cadn.net.cn

要使用的 AWS 区域。spring-doc.cadn.net.cn

us-east-1spring-doc.cadn.net.cn

spring.ai.bedrock.aws.timeoutspring-doc.cadn.net.cn

要使用的 AWS 超时时间。spring-doc.cadn.net.cn

5mspring-doc.cadn.net.cn

spring.ai.bedrock.aws.access-keyspring-doc.cadn.net.cn

AWS 访问密钥。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.secret-keyspring-doc.cadn.net.cn

AWS 密钥。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.bedrock.aws.session-tokenspring-doc.cadn.net.cn

用于临时凭证的 AWS 会话Tokens。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

现在通过带有前缀spring.ai.model.chat的顶级属性来配置聊天自动配置的启用和禁用。spring-doc.cadn.net.cn

要启用,请设置:spring.ai.model.chat=bedrock-converse(默认已启用)spring-doc.cadn.net.cn

要禁用,请设置 spring.ai.model.chat=none (或任何不匹配 bedrock-converse 的值)spring-doc.cadn.net.cn

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

spring.ai.bedrock.converse.chat 前缀是用于配置 Converse API 会话模型实现的属性前缀。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.bedrock.converse.chat.enabled (已移除且不再有效)spring-doc.cadn.net.cn

启用Bedrock Converse 会话模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

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

启用Bedrock Converse 会话模型。spring-doc.cadn.net.cn

bedrock-conversespring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.modelspring-doc.cadn.net.cn

使用要使用的模型ID。您可以查阅支持的模型和模型功能spring-doc.cadn.net.cn

请选择您的modelId,从AWS Bedrock控制台。spring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.temperaturespring-doc.cadn.net.cn

控制输出的随机性。值可以在 [0.0,1.0] 范围内。spring-doc.cadn.net.cn

0.8spring-doc.cadn.net.cn

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

考虑采样时要考虑的Tokens累计概率的最大值。spring-doc.cadn.net.cn

AWS Bedrock默认设置spring-doc.cadn.net.cn

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

生成下一个-token-时的选择Tokens数量。spring-doc.cadn.net.cn

AWS Bedrock默认设置spring-doc.cadn.net.cn

spring.ai.bedrock.converse.chat.options.max-tokensspring-doc.cadn.net.cn

生成响应中的最大Tokens数。spring-doc.cadn.net.cn

500spring-doc.cadn.net.cn

运行时选项

使用便携式ChatOptionsToolCallingChatOptions构建器来创建模型配置,例如温度、最大词汇数、顶级P值等。spring-doc.cadn.net.cn

启动时,可以使用BedrockConverseProxyChatModel(api, options)构造函数或spring.ai.bedrock.converse.chat.options.*属性来配置默认选项。spring-doc.cadn.net.cn

运行时,您可以通过向Prompt调用添加新的、针对请求的选项来覆盖默认选项:spring-doc.cadn.net.cn

var options = ToolCallingChatOptions.builder()
        .model("anthropic.claude-3-5-sonnet-20240620-v1:0")
        .temperature(0.6)
        .maxTokens(300)
        .toolCallbacks(List.of(FunctionToolCallback.builder("getCurrentWeather", new WeatherService())
            .description("Get the weather in location. Return temperature in 36°F or 36°C format. Use multi-turn if needed.")
            .inputType(WeatherService.Request.class)
            .build()))
        .build();

String response = ChatClient.create(this.chatModel)
    .prompt("What is current weather in Amsterdam?")
    .options(options)
    .call()
    .content();

工具调用

The Bedrock Converse API 支持工具调用能力,允许模型在对话中使用工具。 以下是定义和使用基于 @Tool 的工具的示例:spring-doc.cadn.net.cn

public class WeatherService {

    @Tool(description = "Get the weather in location")
    public String weatherByLocation(@ToolParam(description= "City or state name") String location) {
        ...
    }
}

String response = ChatClient.create(this.chatModel)
        .prompt("What's the weather like in Boston?")
        .tools(new WeatherService())
        .call()
        .content();

您可以将 Java.util.function 工具作为 Beans 使用:spring-doc.cadn.net.cn

@Bean
@Description("Get the weather in location. Return temperature in 36°F or 36°C format.")
public Function<Request, Response> weatherFunction() {
    return new MockWeatherService();
}

String response = ChatClient.create(this.chatModel)
        .prompt("What's the weather like in Boston?")
        .toolNames("weatherFunction")
        .inputType(Request.class)
        .call()
        .content();

工具文档中查找更多内容。spring-doc.cadn.net.cn

多模态

多模态指的是模型同时理解和处理来自各种来源的信息的能力,包括文本、图像、视频、PDF、DOC、HTML、MD以及其他数据格式。spring-doc.cadn.net.cn

The Bedrock Converse API 支持多模态输入,包括文本和图像输入,并可以根据结合输入生成文本响应。spring-doc.cadn.net.cn

您需要一个支持多模态输入的模型,例如Anthropic Claude或Amazon Nova模型。spring-doc.cadn.net.cn

图片

对于支持视觉多模态的模型,例如Amazon Nova、Anthropic Claude、Llama 3.2以及Bedrock Converse API Amazon允许您在负载中包含多个图像。这些模型可以分析传递过来的图像,并回答问题、对图像进行分类,以及根据提供的说明总结图像。spring-doc.cadn.net.cn

当前,Bedrock Converse 支持的 base64 编码图片的 MIME 类型包括 image/jpegimage/pngimage/gifimage/webpspring-doc.cadn.net.cn

Spring AI的Message接口通过引入Media类型支持多模态AI模型。 它包含了消息中媒体附件的数据和信息,使用了Spring的org.springframework.util.MimeType和一个java.lang.Object来处理原始媒体数据。spring-doc.cadn.net.cn

以下是一个简单的代码示例,演示了用户文本与图片的结合。spring-doc.cadn.net.cn

String response = ChatClient.create(chatModel)
    .prompt()
    .user(u -> u.text("Explain what do you see on this picture?")
        .media(Media.Format.IMAGE_PNG, new ClassPathResource("/test.png")))
    .call()
    .content();

logger.info(response);

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

Multimodal Test Image

<p>along with the text message &quot;Explain what do you see on this picture?&quot;, 和生成类似下面的响应:</p>spring-doc.cadn.net.cn

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

视频

The Amazon Nova模型 允许您在负载中包含单个视频,该视频可以以base64格式提供或通过Amazon S3 URI提供。spring-doc.cadn.net.cn

当前,Bedrock Nova 支持的视频类型包括 video/x-matroskavideo/quicktimevideo/mp4video/webmvideo/x-flvvideo/mpegvideo/x-ms-wmvvideo/3gppspring-doc.cadn.net.cn

Spring AI的Message接口通过引入Media类型支持多模态AI模型。 它包含了消息中媒体附件的数据和信息,使用了Spring的org.springframework.util.MimeType和一个java.lang.Object来处理原始媒体数据。spring-doc.cadn.net.cn

以下是简单的代码示例,演示了用户文本与视频的结合。spring-doc.cadn.net.cn

String response = ChatClient.create(chatModel)
    .prompt()
    .user(u -> u.text("Explain what do you see in this video?")
        .media(Media.Format.VIDEO_MP4, new ClassPathResource("/test.video.mp4")))
    .call()
    .content();

logger.info(response);

它将输入test.video.mp4图像:spring-doc.cadn.net.cn

Multimodal Test Video

<p>与文本消息“请解释你在视频中看到了什么?”一同出现,并生成类似于以下内容的响应:</p>spring-doc.cadn.net.cn

The video shows a group of baby chickens, also known as chicks, huddled together on a surface
...

_documents_

对于某些模型,Bedrock 允许您通过 Converse API 文档支持在负载中包含文档,这些文档可以以字节形式提供。 文档支持有两种不同的变体,如下所述:spring-doc.cadn.net.cn

  • 文本文档类型(txt、csv、html、md等),强调对文本的理解。这些用例包括基于文档中的文本元素进行回答。spring-doc.cadn.net.cn

  • 媒体文档类型(pdf、docx、xlsx),其中重点是基于视觉的理解来回答问题。这些用例包括根据图表、图形等回答问题。spring-doc.cadn.net.cn

当前,Anthropic 的 PDF 支持(Beta 版本) 和 Amazon Bedrock Nova 模型支持文档的多媒体特性。spring-doc.cadn.net.cn

以下是一个简单的代码示例,演示了用户文本与媒体文档的结合。spring-doc.cadn.net.cn

String response = ChatClient.create(chatModel)
    .prompt()
    .user(u -> u.text(
            "You are a very professional document summarization specialist. Please summarize the given document.")
        .media(Media.Format.DOC_PDF, new ClassPathResource("/spring-ai-reference-overview.pdf")))
    .call()
    .content();

logger.info(response);

它接受一个输入参数 spring-ai-reference-overview.pdf 的文档:spring-doc.cadn.net.cn

Multimodal Test PNG

<p>您是一位非常专业的文档摘要专家,请总结给定的文档。</p>spring-doc.cadn.net.cn

**Introduction:**
- Spring AI is designed to simplify the development of applications with artificial intelligence (AI) capabilities, aiming to avoid unnecessary complexity.
...

样本控制器

创建一个新的Spring Boot项目,并在依赖中添加spring-ai-starter-model-bedrock-conversespring-doc.cadn.net.cn

src/main/resources下添加一个application.properties文件:spring-doc.cadn.net.cn

spring.ai.bedrock.aws.region=eu-central-1
spring.ai.bedrock.aws.timeout=10m
spring.ai.bedrock.aws.access-key=${AWS_ACCESS_KEY_ID}
spring.ai.bedrock.aws.secret-key=${AWS_SECRET_ACCESS_KEY}
# session token is only required for temporary credentials
spring.ai.bedrock.aws.session-token=${AWS_SESSION_TOKEN}

spring.ai.bedrock.converse.chat.options.temperature=0.8
spring.ai.bedrock.converse.chat.options.top-k=15

这里是一个使用聊天模型的控制器示例:spring-doc.cadn.net.cn

@RestController
public class ChatController {

    private final ChatClient chatClient;

    @Autowired
    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

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

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