跳到主要内容

Bedrock Converse API

DeepSeek V3 中英对照 Amazon Bedrock Converse Bedrock Converse API

Amazon Bedrock Converse API 为对话式 AI 模型提供了一个统一的接口,具备增强的功能,包括函数/工具调用、多模态输入和流式响应。

Bedrock Converse API 具有以下高级功能:

  • 工具/函数调用:支持在对话过程中定义函数和使用工具

  • 多模态输入:能够在对话中处理文本和图像输入

  • 流式支持:实时流式传输模型响应

  • 系统消息:支持系统级指令和上下文设置

提示

Bedrock Converse API 提供了一个跨多个模型提供者的统一接口,同时处理 AWS 特定的身份验证和基础设施问题。目前,Converse API 支持的模型 包括:Amazon TitanAmazon NovaAI21 LabsAnthropic ClaudeCohere CommandMeta LlamaMistral AI

备注

根据 Bedrock 的推荐,Spring AI 正在过渡到使用 Amazon Bedrock 的 Converse API 来实现 Spring AI 中的所有聊天对话功能。虽然现有的 InvokeModel API 支持对话应用,但我们强烈建议在所有 Char 对话模型中使用 Converse API。

Converse API 不支持嵌入操作,因此这些操作将保留在当前 API 中,并且现有 InvokeModel API 中的嵌入模型功能将继续保留。

前提条件

请参考 Amazon Bedrock 入门指南 来设置 API 访问权限。

  • 获取 AWS 凭证:如果你还没有 AWS 账户并且没有配置 AWS CLI,这个视频指南可以帮助你完成配置:AWS CLI & SDK 设置不到 4 分钟!。你应该能够获取你的访问密钥和安全密钥。

  • 启用要使用的模型:前往 Amazon Bedrock,然后从左侧的 Model Access 菜单中,配置你要使用的模型的访问权限。

自动配置

spring-ai-bedrock-converse-spring-boot-starter 依赖添加到你的项目的 Maven pom.xml 或 Gradle build.gradle 构建文件中:

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bedrock-converse-spring-boot-starter</artifactId>
</dependency>
xml
提示

请参考依赖管理部分,将 Spring AI BOM 添加到你的构建文件中。

聊天属性

前缀 spring.ai.bedrock.aws 是用于配置连接到 AWS Bedrock 的属性前缀。

属性描述默认值
spring.ai.bedrock.aws.region使用的 AWS 区域。us-east-1
spring.ai.bedrock.aws.timeout使用的 AWS 超时时间。5m
spring.ai.bedrock.aws.access-keyAWS 访问密钥。-
spring.ai.bedrock.aws.secret-keyAWS 密钥。-
spring.ai.bedrock.aws.session-token用于临时凭证的 AWS 会话令牌。-

前缀 spring.ai.bedrock.converse.chat 是用于配置 Converse API 的聊天模型实现的属性前缀。

属性描述默认值
spring.ai.bedrock.converse.chat.enabled启用 Bedrock Converse 聊天模型。true
spring.ai.bedrock.converse.chat.options.model使用的模型 ID。你可以使用 支持的模型和模型功能无。从 AWS Bedrock 控制台 中选择你的模型 ID。
spring.ai.bedrock.converse.chat.options.temperature控制输出的随机性。取值范围为 [0.0,1.0]。0.8
spring.ai.bedrock.converse.chat.options.top-p采样时考虑的最大累积概率。AWS Bedrock 默认值
spring.ai.bedrock.converse.chat.options.top-k生成下一个 token 时的 token 选择数量。AWS Bedrock 默认值
spring.ai.bedrock.converse.chat.options.max-tokens生成响应中的最大 token 数量。500

运行时选项

使用可移植的 ChatOptionsToolCallingChatOptions 可移植构建器来创建模型配置,例如 temperature(温度)、maxToken(最大令牌数)、topP(顶部概率)等。

在启动时,默认选项可以通过 BedrockConverseProxyChatModel(api, options) 构造函数或 spring.ai.bedrock.converse.chat.options.* 属性进行配置。

在运行时,你可以通过在 Prompt 调用中添加新的、特定于请求的选项来覆盖默认选项:

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();
java

工具调用

Bedrock Converse API 支持工具调用功能,允许模型在对话过程中使用工具。以下是如何定义和使用基于 @Tool 的工具的示例:

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

你也可以将 java.util.function 包中的 beans 用作工具:

@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?")
.tools("weatherFunction")
.inputType(Request.class)
.call()
.content();
java

更多内容请参见 工具 文档。

多模态

多模态指的是模型能够同时理解和处理来自多种来源的信息,包括文本、图像、视频、PDF、DOC、HTML、MD 以及更多数据格式。

Bedrock Converse API 支持多模态输入,包括文本和图像输入,并能够根据组合输入生成文本响应。

你需要一个支持多模态输入的模型,例如 Anthropic Claude 或 Amazon Nova 模型。

图片

对于支持视觉多模态的模型,例如 Amazon Nova、Anthropic Claude、Llama 3.2,Bedrock Converse API 允许你在 payload 中包含多张图片。这些模型能够分析传递的图片并回答问题、对图片进行分类,以及根据提供的指令对图片进行总结。

目前,Bedrock Converse 支持 image/jpegimage/pngimage/gifimage/webp MIME 类型的 base64 编码图像。

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

以下是一个简单的代码示例,演示了如何将用户文本与图像结合。

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);
java

它以 test.png 图像作为输入:

多模态测试图片

伴随着文本消息“解释一下你在这张图片上看到了什么?”,并生成类似以下的响应:

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

视频

Amazon Nova 模型 允许你在有效载荷中包含单个视频,该视频可以以 base64 格式或通过 Amazon S3 URI 提供。

目前,Bedrock Nova 支持以下 MIME 类型的视频和图像文件:video/x-matrosvideo/quicktimevideo/mp4video/webmvideo/x-flvvideo/mpegvideo/x-ms-wmv 以及 image/3gpp

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

以下是一个简单的代码示例,展示了如何将用户文本与视频结合。

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);
java

它以 test.video.mp4 图像作为输入:

多模态测试视频

伴随着文本消息“解释一下你在这个视频中看到了什么?”,并生成类似如下的响应:

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

文档

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

  • 文本文档类型(txt、csv、html、md 等),重点是文本理解。这些用例包括基于文档的文本元素进行回答。

  • 媒体文档类型(pdf、docx、xlsx),重点是基于视觉的理解来回答问题。这些用例包括基于图表、图形等回答问题。

  • Code document types (ipynb, py, java, and so on), where the emphasis is on understanding code and code blocks. These use cases include answering questions based on code, code blocks, and so on.

目前,Anthropic 的 PDF 支持(测试版) 和 Amazon Bedrock Nova 模型支持文档多模态功能。

下面是一个简单的代码示例,展示了如何将用户文本与媒体文档结合。

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);
java

它接受 spring-ai-reference-overview.pdf 文档作为输入:

多模态测试 PNG

同时附带文本消息“你是一位非常专业的文档摘要专家。请对给定的文档进行摘要。”,并生成类似以下的响应:

**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-bedrock-converse-spring-boot-starter 添加到你的依赖中。

src/main/resources 目录下添加一个 application.properties 文件:

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
properties

以下是一个使用聊天模型的控制器示例:

@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();
}
}
java