Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions models/spring-ai-bedrock-converse/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@
<developerConnection>[email protected]:spring-projects/spring-ai.git</developerConnection>
</scm>

<properties>
<aws.sdk.version>2.29.3</aws.sdk.version>
</properties>

<dependencies>

<!-- production dependencies -->
Expand All @@ -59,7 +55,7 @@
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrockruntime</artifactId>
<version>${aws.sdk.version}</version>
<version>${awssdk.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
Expand All @@ -71,13 +67,13 @@
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sts</artifactId>
<version>${aws.sdk.version}</version>
<version>${awssdk.version}</version>
</dependency>

<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>netty-nio-client</artifactId>
<version>${aws.sdk.version}</version>
<version>${awssdk.version}</version>
</dependency>

<!-- test dependencies -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -51,10 +53,13 @@
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamOutput;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamRequest;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.DocumentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.DocumentSource;
import software.amazon.awssdk.services.bedrockruntime.model.ImageBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ImageSource;
import software.amazon.awssdk.services.bedrockruntime.model.InferenceConfiguration;
import software.amazon.awssdk.services.bedrockruntime.model.Message;
import software.amazon.awssdk.services.bedrockruntime.model.S3Location;
import software.amazon.awssdk.services.bedrockruntime.model.StopReason;
import software.amazon.awssdk.services.bedrockruntime.model.SystemContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.Tool;
Expand All @@ -64,7 +69,11 @@
import software.amazon.awssdk.services.bedrockruntime.model.ToolResultContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ToolSpecification;
import software.amazon.awssdk.services.bedrockruntime.model.ToolUseBlock;
import software.amazon.awssdk.services.bedrockruntime.model.VideoBlock;
import software.amazon.awssdk.services.bedrockruntime.model.VideoFormat;
import software.amazon.awssdk.services.bedrockruntime.model.VideoSource;

import org.springframework.ai.bedrock.converse.api.BedrockMediaFormat;
import org.springframework.ai.bedrock.converse.api.ConverseApiUtils;
import org.springframework.ai.bedrock.converse.api.URLValidator;
import org.springframework.ai.chat.messages.AssistantMessage;
Expand All @@ -86,6 +95,7 @@
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.ChatOptionsBuilder;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.Media;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.model.function.FunctionCallbackResolver;
Expand Down Expand Up @@ -252,14 +262,10 @@ ConverseRequest createRequest(Prompt prompt) {
contents.add(ContentBlock.fromText(userMessage.getContent()));

if (!CollectionUtils.isEmpty(userMessage.getMedia())) {
List<ContentBlock> mediaContent = userMessage.getMedia().stream().map(media -> {
ContentBlock cb = ContentBlock.fromImage(ImageBlock.builder()
.format(media.getMimeType().getSubtype())
.source(ImageSource
.fromBytes(SdkBytes.fromByteArray(getContentMediaData(media.getData()))))
.build());
return cb;
}).toList();
List<ContentBlock> mediaContent = userMessage.getMedia()
.stream()
.map(this::mapMediaToContentBlock)
.toList();
contents.addAll(mediaContent);
}
}
Expand Down Expand Up @@ -341,6 +347,7 @@ else if (prompt.getOptions() instanceof ChatOptions) {
? updatedRuntimeOptions.getTemperature().floatValue() : null)
.topP(updatedRuntimeOptions.getTopP() != null ? updatedRuntimeOptions.getTopP().floatValue() : null)
.build();

Document additionalModelRequestFields = ConverseApiUtils
.getChatOptionsAdditionalModelRequestFields(this.defaultOptions, prompt.getOptions());

Expand All @@ -354,6 +361,91 @@ else if (prompt.getOptions() instanceof ChatOptions) {
.build();
}

private ContentBlock mapMediaToContentBlock(Media media) {

var mimeType = media.getMimeType();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should look to break up this multi-screen function into if/else structure with additional helper methods.


if (BedrockMediaFormat.isSupportedVideoFormat(mimeType)) { // Video
VideoFormat videoFormat = BedrockMediaFormat.getVideoFormat(mimeType);
VideoSource videoSource = null;
if (media.getData() instanceof byte[] bytes) {
videoSource = VideoSource.builder().bytes(SdkBytes.fromByteArrayUnsafe(bytes)).build();
}
else if (media.getData() instanceof String uriText) {
// if (URLValidator.isValidURLBasic(uriText)) {
videoSource = VideoSource.builder().s3Location(S3Location.builder().uri(uriText).build()).build();
// }
}
else if (media.getData() instanceof URL url) {
try {
videoSource = VideoSource.builder()
.s3Location(S3Location.builder().uri(url.toURI().toString()).build())
.build();
}
catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
else {
throw new IllegalArgumentException("Invalid video content type: " + media.getData().getClass());
}

return ContentBlock.fromVideo(VideoBlock.builder().source(videoSource).format(videoFormat).build());
}
else if (BedrockMediaFormat.isSupportedImageFormat(mimeType)) { // Image
ImageSource.Builder sourceBuilder = ImageSource.builder();
if (media.getData() instanceof byte[] bytes) {
sourceBuilder.bytes(SdkBytes.fromByteArrayUnsafe(bytes)).build();
}
else if (media.getData() instanceof String text) {

if (URLValidator.isValidURLBasic(text)) {
try {
URL url = new URL(text);
URLConnection connection = url.openConnection();
try (InputStream is = connection.getInputStream()) {
sourceBuilder.bytes(SdkBytes.fromByteArrayUnsafe(StreamUtils.copyToByteArray(is))).build();
}
}
catch (IOException e) {
throw new RuntimeException("Failed to read media data from URL: " + text, e);
}
}
else {
sourceBuilder.bytes(SdkBytes.fromByteArray(Base64.getDecoder().decode(text)));
}
}
else if (media.getData() instanceof URL url) {

try (InputStream is = url.openConnection().getInputStream()) {
byte[] imageBytes = StreamUtils.copyToByteArray(is);
sourceBuilder.bytes(SdkBytes.fromByteArrayUnsafe(imageBytes)).build();
}
catch (IOException e) {
throw new IllegalArgumentException("Failed to read media data from URL: " + url, e);
}
}
else {
throw new IllegalArgumentException("Invalid Image content type: " + media.getData().getClass());
}

return ContentBlock.fromImage(ImageBlock.builder()
.source(sourceBuilder.build())
.format(BedrockMediaFormat.getImageFormat(mimeType))
.build());
}
else if (BedrockMediaFormat.isSupportedDocumentFormat(mimeType)) { // Document

return ContentBlock.fromDocument(DocumentBlock.builder()
.name(media.getName())
.format(BedrockMediaFormat.getDocumentFormat(mimeType))
.source(DocumentSource.builder().bytes(SdkBytes.fromByteArray(media.getDataAsByteArray())).build())
.build());
}

throw new IllegalArgumentException("Unsupported media format: " + mimeType);
}

private List<Tool> getFunctionTools(Set<String> functionNames) {
return this.resolveFunctionCallbacks(functionNames).stream().map(functionCallback -> {
var description = functionCallback.getDescription();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright 2024 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.bedrock.converse.api;

import java.util.Map;

import software.amazon.awssdk.services.bedrockruntime.model.DocumentFormat;
import software.amazon.awssdk.services.bedrockruntime.model.ImageFormat;
import software.amazon.awssdk.services.bedrockruntime.model.VideoFormat;

import org.springframework.ai.model.Media;
import org.springframework.util.MimeType;

/**
* The BedrockMediaFormat class provides mappings between MIME types and their
* corresponding Bedrock media formats for documents, images, and videos. It supports
* conversion of MIME types to specific formats used by the Bedrock runtime.
*
* <p>
* Supported document formats include PDF, CSV, DOC, DOCX, XLS, XLSX, HTML, TXT, and MD.
* Supported image formats include JPEG, PNG, GIF, and WEBP. Supported video formats
* include MKV, MOV, MP4, WEBM, FLV, MPEG, MPG, WMV, and 3GP.
* </p>
*
* <p>
* Usage example:
* </p>
* <pre>
* String format = BedrockMediaFormat.getFormatAsString(Media.Format.DOC_PDF);
* </pre>
*
* <p>
* Throws IllegalArgumentException if the MIME type is unsupported.
* </p>
*
* @author Christian Tzolov
* @since 1.0.0
*/
public class BedrockMediaFormat {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make abstract


// @formatter:off
public static final Map<MimeType, DocumentFormat> DOCUMENT_MAP = Map.of(
Media.Format.DOC_PDF, DocumentFormat.PDF,
Media.Format.DOC_CSV, DocumentFormat.CSV,
Media.Format.DOC_DOC, DocumentFormat.DOC,
Media.Format.DOC_DOCX, DocumentFormat.DOCX,
Media.Format.DOC_XLS, DocumentFormat.XLS,
Media.Format.DOC_XLSX, DocumentFormat.XLSX,
Media.Format.DOC_HTML, DocumentFormat.HTML,
Media.Format.DOC_TXT, DocumentFormat.TXT,
Media.Format.DOC_MD, DocumentFormat.MD);
// @formatter:on

// @formatter:off
public static final Map<MimeType, ImageFormat> IMAGE_MAP = Map.of(
Media.Format.IMAGE_JPEG, ImageFormat.JPEG,
Media.Format.IMAGE_PNG, ImageFormat.PNG,
Media.Format.IMAGE_GIF, ImageFormat.GIF,
Media.Format.IMAGE_WEBP, ImageFormat.WEBP);
// @formatter:on

// @formatter:off
public static final Map<MimeType, VideoFormat> VIDEO_MAP = Map.of(
Media.Format.VIDEO_MKV, VideoFormat.MKV,
Media.Format.VIDEO_MOV, VideoFormat.MOV,
Media.Format.VIDEO_MP4, VideoFormat.MP4,
Media.Format.VIDEO_WEBM, VideoFormat.WEBM,
Media.Format.VIDEO_FLV, VideoFormat.FLV,
Media.Format.VIDEO_MPEG, VideoFormat.MPEG,
Media.Format.VIDEO_WMV, VideoFormat.WMV,
Media.Format.VIDEO_THREE_GP, VideoFormat.THREE_GP);
// @formatter:on

public static String getFormatAsString(MimeType mimeType) {
if (isSupportedDocumentFormat(mimeType)) {
return DOCUMENT_MAP.get(mimeType).toString();
}
else if (isSupportedImageFormat(mimeType)) {
return IMAGE_MAP.get(mimeType).toString();
}
else if (isSupportedVideoFormat(mimeType)) {
return VIDEO_MAP.get(mimeType).toString();
}
throw new IllegalArgumentException("Unsupported media format: " + mimeType);
}

public static Boolean isSupportedDocumentFormat(MimeType mimeType) {
return DOCUMENT_MAP.containsKey(mimeType);
}

public static DocumentFormat getDocumentFormat(MimeType mimeType) {
if (!isSupportedDocumentFormat(mimeType)) {
throw new IllegalArgumentException("Unsupported document format: " + mimeType);
}
return DOCUMENT_MAP.get(mimeType);
}

public static Boolean isSupportedImageFormat(MimeType mimeType) {
return IMAGE_MAP.containsKey(mimeType);
}

public static ImageFormat getImageFormat(MimeType mimeType) {
if (!isSupportedImageFormat(mimeType)) {
throw new IllegalArgumentException("Unsupported image format: " + mimeType);
}
return IMAGE_MAP.get(mimeType);
}

public static Boolean isSupportedVideoFormat(MimeType mimeType) {
return VIDEO_MAP.containsKey(mimeType);
}

public static VideoFormat getVideoFormat(MimeType mimeType) {
if (!isSupportedVideoFormat(mimeType)) {
throw new IllegalArgumentException("Unsupported video format: " + mimeType);
}
return VIDEO_MAP.get(mimeType);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(classes = BedrockConverseTestConfiguration.class, properties = "spring.ai.retry.on-http-codes=429")
@SpringBootTest(classes = BedrockConverseTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockProxyChatModelIT {
Expand Down
Loading
Loading