Java 2.x용 SDK를 사용하는 Amazon Bedrock 런타임 예제 - AWS SDK for Java 2.x

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Java 2.x용 SDK를 사용하는 Amazon Bedrock 런타임 예제

다음 코드 예제는 Amazon Bedrock Runtime과 AWS SDK for Java 2.x 함께 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 호출하는 방법을 보여 주며 관련 시나리오와 교차 서비스 예시에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예시입니다.

각 예제에는 GitHub 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 링크가 포함되어 있습니다.

AI21 랩 쥬라기-2

다음 코드 예제는 베드락의 컨버스 API를 사용하여 AI21 Labs Jurassic-2에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

GitHub더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 AI21 Labs Jurassic-2에 문자 메시지를 보내세요.

// Use the Converse API to send a text message to AI21 Labs Jurassic-2. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse; import software.amazon.awssdk.services.bedrockruntime.model.Message; public class Converse { public static String converse() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Jurassic-2 Mid. var modelId = "ai21.j2-mid-v1"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); try { // Send the message with a basic inference configuration. ConverseResponse response = client.converse(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F))); // Retrieve the generated text from Bedrock's response object. var responseText = response.output().message().content().get(0).text(); System.out.println(responseText); return responseText; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converse(); } }

비동기 자바 클라이언트와 함께 베드락의 컨버스 API를 사용하여 AI21 Labs Jurassic-2에 문자 메시지를 보내십시오.

// Use the Converse API to send a text message to AI21 Labs Jurassic-2 // with the async Java client. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ConverseAsync { public static String converseAsync() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Jurassic-2 Mid. var modelId = "ai21.j2-mid-v1"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Send the message with a basic inference configuration. var request = client.converse(params -> params .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F)) ); // Prepare a future object to handle the asynchronous response. CompletableFuture<String> future = new CompletableFuture<>(); // Handle the response or error using the future object. request.whenComplete((response, error) -> { if (error == null) { // Extract the generated text from Bedrock's response object. String responseText = response.output().message().content().get(0).text(); future.complete(responseText); } else { future.completeExceptionally(error); } }); try { // Wait for the future object to complete and retrieve the generated text. String responseText = future.get(); System.out.println(responseText); return responseText; } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converseAsync(); } }

다음 코드 예제는 호출 모델 API를 사용하여 AI21 Labs Jurassic-2에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to AI21 Labs Jurassic-2. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Jurassic-2 Mid. var modelId = "ai21.j2-mid-v1"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html var nativeRequestTemplate = "{ \"prompt\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/completions/0/data/text").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

Amazon Titan Image Generator

다음 코드 예제는 Amazon Bedrock에서 Amazon Titan Image를 호출하여 이미지를 생성하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Amazon Titan 이미지 생성기로 이미지를 생성하십시오.

// Create an image with the Amazon Titan Image Generator. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import java.math.BigInteger; import java.security.SecureRandom; import static com.example.bedrockruntime.libs.ImageTools.displayImage; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Image G1. var modelId = "amazon.titan-image-generator-v1"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html var nativeRequestTemplate = """ { "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "{{prompt}}" }, "imageGenerationConfig": { "seed": {{seed}} } }"""; // Define the prompt for the image generation. var prompt = "A stylized picture of a cute old steampunk robot"; // Get a random 31-bit seed for the image generation (max. 2,147,483,647). var seed = new BigInteger(31, new SecureRandom()); // Embed the prompt and seed in the model's native request payload. var nativeRequest = nativeRequestTemplate .replace("{{prompt}}", prompt) .replace("{{seed}}", seed.toString()); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated image data from the model's response. var base64ImageData = new JSONPointer("/images/0").queryFrom(responseBody).toString(); return base64ImageData; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { System.out.println("Generating image. This may take a few seconds..."); String base64ImageData = invokeModel(); displayImage(base64ImageData); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

아마존 타이탄 텍스트

다음 코드 예제는 Bedrock의 컨버스 API를 사용하여 Amazon Titan Text에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 아마존 타이탄 텍스트로 문자 메시지를 보내십시오.

// Use the Converse API to send a text message to Amazon Titan Text. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse; import software.amazon.awssdk.services.bedrockruntime.model.Message; public class Converse { public static String converse() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); try { // Send the message with a basic inference configuration. ConverseResponse response = client.converse(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F))); // Retrieve the generated text from Bedrock's response object. var responseText = response.output().message().content().get(0).text(); System.out.println(responseText); return responseText; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converse(); } }

비동기 Java 클라이언트와 함께 Bedrock의 컨버스 API를 사용하여 Amazon Titan Text에 문자 메시지를 보냅니다.

// Use the Converse API to send a text message to Amazon Titan Text // with the async Java client. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ConverseAsync { public static String converseAsync() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Send the message with a basic inference configuration. var request = client.converse(params -> params .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F)) ); // Prepare a future object to handle the asynchronous response. CompletableFuture<String> future = new CompletableFuture<>(); // Handle the response or error using the future object. request.whenComplete((response, error) -> { if (error == null) { // Extract the generated text from Bedrock's response object. String responseText = response.output().message().content().get(0).text(); future.complete(responseText); } else { future.completeExceptionally(error); } }); try { // Wait for the future object to complete and retrieve the generated text. String responseText = future.get(); System.out.println(responseText); return responseText; } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converseAsync(); } }

다음 코드 예제는 Bedrock의 Converse API를 사용하여 Amazon Titan Text에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드록의 컨버스 API를 사용하여 Amazon Titan Text에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리합니다.

// Use the Converse API to send a text message to Amazon Titan Text // and print the response stream. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.ExecutionException; public class ConverseStream { public static void main(String[] args) { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Create a handler to extract and print the response text in real-time. var responseStreamHandler = ConverseStreamResponseHandler.builder() .subscriber(ConverseStreamResponseHandler.Visitor.builder() .onContentBlockDelta(chunk -> { String responseText = chunk.delta().text(); System.out.print(responseText); }).build() ).onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()) ).build(); try { // Send the message with a basic inference configuration and attach the handler. client.converseStream(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F) ), responseStreamHandler).get(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); } } }
  • API 세부 정보는 API 참조를 참조하십시오 ConverseStream.AWS SDK for Java 2.x

다음 코드 예제는 모델 호출 API를 사용하여 Amazon Titan Text에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Amazon Titan Text. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-text.html var nativeRequestTemplate = "{ \"inputText\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/results/0/outputText").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 Invoke Model API를 사용하여 Amazon Titan Text 모델에 문자 메시지를 보내고 응답 스트림을 인쇄하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Amazon Titan Text // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-text.html var nativeRequestTemplate = "{ \"inputText\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { // Extract and print the text from the model's native response. var response = new JSONObject(chunk.bytes().asUtf8String()); var text = new JSONPointer("/outputText").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }

Amazon Titan Text Embeddings

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 첫 임베딩 생성을 시작하세요.

  • 차원 수와 정규화를 구성하는 임베딩을 생성하세요 (V2만 해당).

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

타이탄 텍스트 임베딩 V2로 첫 임베딩을 만들어 보세요.

// Generate and print an embedding with Amazon Titan Text Embeddings. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Titan Text Embeddings V2. var modelId = "amazon.titan-embed-text-v2:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-embed-text.html var nativeRequestTemplate = "{ \"inputText\": \"{{inputText}}\" }"; // The text to convert into an embedding. var inputText = "Please recommend books with a theme similar to the movie 'Inception'."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{inputText}}", inputText); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/embedding").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }

타이탄 텍스트 임베딩 V2를 호출하여 차원 수와 정규화를 구성하십시오.

/** * Invoke Amazon Titan Text Embeddings V2 with additional inference parameters. * * @param inputText - The text to convert to an embedding. * @param dimensions - The number of dimensions the output embeddings should have. * Values accepted by the model: 256, 512, 1024. * @param normalize - A flag indicating whether or not to normalize the output embeddings. * @return The {@link JSONObject} representing the model's response. */ public static JSONObject invokeModel(String inputText, int dimensions, boolean normalize) { // Create a Bedrock Runtime client in the AWS Region of your choice. var client = BedrockRuntimeClient.builder() .region(Region.US_WEST_2) .build(); // Set the model ID, e.g., Titan Embed Text v2.0. var modelId = "amazon.titan-embed-text-v2:0"; // Create the request for the model. var nativeRequest = """ { "inputText": "%s", "dimensions": %d, "normalize": %b } """.formatted(inputText, dimensions, normalize); // Encode and send the request. var response = client.invokeModel(request -> { request.body(SdkBytes.fromUtf8String(nativeRequest)); request.modelId(modelId); }); // Decode the model's response. var modelResponse = new JSONObject(response.body().asUtf8String()); // Extract and print the generated embedding and the input text token count. var embedding = modelResponse.getJSONArray("embedding"); var inputTokenCount = modelResponse.getBigInteger("inputTextTokenCount"); System.out.println("Embedding: " + embedding); System.out.println("\nInput token count: " + inputTokenCount); // Return the model's native response. return modelResponse; }
  • API에 대한 자세한 내용은 API 레퍼런스를 참조하십시오 InvokeModel.AWS SDK for Java 2.x

Anthropic Claude

다음 코드 예제는 베드락의 컨버스 API를 사용하여 Anthropic Claude에게 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

GitHub더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 앤트로픽 클로드에게 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Anthropic Claude. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse; import software.amazon.awssdk.services.bedrockruntime.model.Message; public class Converse { public static String converse() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); try { // Send the message with a basic inference configuration. ConverseResponse response = client.converse(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F))); // Retrieve the generated text from Bedrock's response object. var responseText = response.output().message().content().get(0).text(); System.out.println(responseText); return responseText; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converse(); } }

비동기 자바 클라이언트와 함께 베드록의 컨버스 API를 사용하여 앤트로픽 클로드에게 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Anthropic Claude // with the async Java client. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ConverseAsync { public static String converseAsync() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Send the message with a basic inference configuration. var request = client.converse(params -> params .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F)) ); // Prepare a future object to handle the asynchronous response. CompletableFuture<String> future = new CompletableFuture<>(); // Handle the response or error using the future object. request.whenComplete((response, error) -> { if (error == null) { // Extract the generated text from Bedrock's response object. String responseText = response.output().message().content().get(0).text(); future.complete(responseText); } else { future.completeExceptionally(error); } }); try { // Wait for the future object to complete and retrieve the generated text. String responseText = future.get(); System.out.println(responseText); return responseText; } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converseAsync(); } }

다음 코드 예제는 베드록의 컨버스 API를 사용하여 Anthropic Claude에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 앤트로픽 클로드에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하세요.

// Use the Converse API to send a text message to Anthropic Claude // and print the response stream. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.ExecutionException; public class ConverseStream { public static void main(String[] args) { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Create a handler to extract and print the response text in real-time. var responseStreamHandler = ConverseStreamResponseHandler.builder() .subscriber(ConverseStreamResponseHandler.Visitor.builder() .onContentBlockDelta(chunk -> { String responseText = chunk.delta().text(); System.out.print(responseText); }).build() ).onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()) ).build(); try { // Send the message with a basic inference configuration and attach the handler. client.converseStream(request -> request.modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F) ), responseStreamHandler).get(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); } } }
  • API 세부 정보는 API 레퍼런스를 참조하십시오. ConverseStreamAWS SDK for Java 2.x

다음 코드 예제는 Invoke Model API를 사용하여 Anthropic Claude에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Anthropic Claude. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html var nativeRequestTemplate = """ { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 512, "temperature": 0.5, "messages": [{ "role": "user", "content": "{{prompt}}" }] }"""; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/content/0/text").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 Invoke Model API를 사용하여 Anthropic Claude 모델에 문자 메시지를 보내고 응답 스트림을 인쇄하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Anthropic Claude // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.Objects; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html var nativeRequestTemplate = """ { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 512, "temperature": 0.5, "messages": [{ "role": "user", "content": "{{prompt}}" }] }"""; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { var response = new JSONObject(chunk.bytes().asUtf8String()); // Extract and print the text from the content blocks. if (Objects.equals(response.getString("type"), "content_block_delta")) { var text = new JSONPointer("/delta/text").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); } }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }

Cohere Command

다음 코드 예제는 베드락의 컨버스 API를 사용하여 Cohere Command에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 코히어 커맨드에 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Cohere Command. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse; import software.amazon.awssdk.services.bedrockruntime.model.Message; public class Converse { public static String converse() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); try { // Send the message with a basic inference configuration. ConverseResponse response = client.converse(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F))); // Retrieve the generated text from Bedrock's response object. var responseText = response.output().message().content().get(0).text(); System.out.println(responseText); return responseText; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converse(); } }

비동기 자바 클라이언트와 함께 베드락의 컨버스 API를 사용하여 코히어 커맨드에 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Cohere Command // with the async Java client. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ConverseAsync { public static String converseAsync() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Send the message with a basic inference configuration. var request = client.converse(params -> params .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F)) ); // Prepare a future object to handle the asynchronous response. CompletableFuture<String> future = new CompletableFuture<>(); // Handle the response or error using the future object. request.whenComplete((response, error) -> { if (error == null) { // Extract the generated text from Bedrock's response object. String responseText = response.output().message().content().get(0).text(); future.complete(responseText); } else { future.completeExceptionally(error); } }); try { // Wait for the future object to complete and retrieve the generated text. String responseText = future.get(); System.out.println(responseText); return responseText; } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converseAsync(); } }

다음 코드 예제는 베드록의 컨버스 API를 사용하여 Cohere Command에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드록의 컨버스 API를 사용하여 Cohere Command에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하세요.

// Use the Converse API to send a text message to Cohere Command // and print the response stream. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.ExecutionException; public class ConverseStream { public static void main(String[] args) { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Create a handler to extract and print the response text in real-time. var responseStreamHandler = ConverseStreamResponseHandler.builder() .subscriber(ConverseStreamResponseHandler.Visitor.builder() .onContentBlockDelta(chunk -> { String responseText = chunk.delta().text(); System.out.print(responseText); }).build() ).onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()) ).build(); try { // Send the message with a basic inference configuration and attach the handler. client.converseStream(request -> request.modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F) ), responseStreamHandler).get(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); } } }
  • API 세부 정보는 API 참조를 참조하십시오 ConverseStream.AWS SDK for Java 2.x

다음 코드 예제는 Invoke Model API를 사용하여 Cohere Command R 및 R+에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Cohere Command R. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class Command_R_InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html var nativeRequestTemplate = "{ \"message\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/text").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 Invoke Model API를 사용하여 Cohere Command에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Cohere Command. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class Command_InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command Light. var modelId = "cohere.command-light-text-v14"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command.html var nativeRequestTemplate = "{ \"prompt\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/generations/0/text").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 응답 스트림과 함께 Invoke Model API를 사용하여 Cohere Command에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Cohere Command R // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class Command_R_InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html var nativeRequestTemplate = "{ \"message\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { // Extract and print the text from the model's native response. var response = new JSONObject(chunk.bytes().asUtf8String()); var text = new JSONPointer("/text").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 응답 스트림과 함께 Invoke Model API를 사용하여 Cohere Command에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Cohere Command // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class Command_InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command Light. var modelId = "cohere.command-light-text-v14"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command.html var nativeRequestTemplate = "{ \"prompt\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { // Extract and print the text from the model's native response. var response = new JSONObject(chunk.bytes().asUtf8String()); var text = new JSONPointer("/generations/0/text").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

메타 라마

다음 코드 예제는 베드락의 컨버스 API를 사용하여 메타 라마에게 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 메타 라마에게 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Meta Llama. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse; import software.amazon.awssdk.services.bedrockruntime.model.Message; public class Converse { public static String converse() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); try { // Send the message with a basic inference configuration. ConverseResponse response = client.converse(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F))); // Retrieve the generated text from Bedrock's response object. var responseText = response.output().message().content().get(0).text(); System.out.println(responseText); return responseText; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converse(); } }

비동기 자바 클라이언트와 함께 베드락의 컨버스 API를 사용하여 메타 라마에게 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Meta Llama // with the async Java client. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ConverseAsync { public static String converseAsync() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Send the message with a basic inference configuration. var request = client.converse(params -> params .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F)) ); // Prepare a future object to handle the asynchronous response. CompletableFuture<String> future = new CompletableFuture<>(); // Handle the response or error using the future object. request.whenComplete((response, error) -> { if (error == null) { // Extract the generated text from Bedrock's response object. String responseText = response.output().message().content().get(0).text(); future.complete(responseText); } else { future.completeExceptionally(error); } }); try { // Wait for the future object to complete and retrieve the generated text. String responseText = future.get(); System.out.println(responseText); return responseText; } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converseAsync(); } }

다음 코드 예제는 베드록의 컨버스 API를 사용하여 메타 라마에게 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 메타 라마에게 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하세요.

// Use the Converse API to send a text message to Meta Llama // and print the response stream. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.ExecutionException; public class ConverseStream { public static void main(String[] args) { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Create a handler to extract and print the response text in real-time. var responseStreamHandler = ConverseStreamResponseHandler.builder() .subscriber(ConverseStreamResponseHandler.Visitor.builder() .onContentBlockDelta(chunk -> { String responseText = chunk.delta().text(); System.out.print(responseText); }).build() ).onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()) ).build(); try { // Send the message with a basic inference configuration and attach the handler. client.converseStream(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F) ), responseStreamHandler).get(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); } } }
  • API 세부 정보는 API 레퍼런스를 참조하십시오. ConverseStreamAWS SDK for Java 2.x

다음 코드 예제는 Invoke Model API를 사용하여 메타 라마 2에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Meta Llama 2. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class Llama2_InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 2 Chat 13B. var modelId = "meta.llama2-13b-chat-v1"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 2's instruction format. var instruction = "<s>[INST] {{prompt}} [/INST]\\n".replace("{{prompt}}", prompt); // Embed the instruction in the the native request payload. var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/generation").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 Invoke Model API를 사용하여 메타 라마 3에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Meta Llama 3. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class Llama3_InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 3's instruction format. var instruction = ( "<|begin_of_text|>\\n" + "<|start_header_id|>user<|end_header_id|>\\n" + "{{prompt}} <|eot_id|>\\n" + "<|start_header_id|>assistant<|end_header_id|>\\n" ).replace("{{prompt}}", prompt); // Embed the instruction in the the native request payload. var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/generation").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 Invoke Model API를 사용하여 Meta Lama 2에 문자 메시지를 보내고 응답 스트림을 인쇄하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Meta Llama 2 // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class Llama2_InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 2 Chat 13B. var modelId = "meta.llama2-13b-chat-v1"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 2's instruction format. var instruction = "<s>[INST] {{prompt}} [/INST]\\n".replace("{{prompt}}", prompt); // Embed the instruction in the the native request payload. var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { // Extract and print the text from the model's native response. var response = new JSONObject(chunk.bytes().asUtf8String()); var text = new JSONPointer("/generation").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }

다음 코드 예제는 Invoke Model API를 사용하여 Meta Lama 3에 문자 메시지를 보내고 응답 스트림을 인쇄하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Meta Llama 3 // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class Llama3_InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 3's instruction format. var instruction = ( "<|begin_of_text|>\\n" + "<|start_header_id|>user<|end_header_id|>\\n" + "{{prompt}} <|eot_id|>\\n" + "<|start_header_id|>assistant<|end_header_id|>\\n" ).replace("{{prompt}}", prompt); // Embed the instruction in the the native request payload. var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { // Extract and print the text from the model's native response. var response = new JSONObject(chunk.bytes().asUtf8String()); var text = new JSONPointer("/generation").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }

미스트랄 AI

다음 코드 예제는 베드락의 컨버스 API를 사용하여 미스트랄에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

더 많은 정보가 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드락의 컨버스 API를 사용하여 미스트랄에 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Mistral. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse; import software.amazon.awssdk.services.bedrockruntime.model.Message; public class Converse { public static String converse() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); try { // Send the message with a basic inference configuration. ConverseResponse response = client.converse(request -> request .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F))); // Retrieve the generated text from Bedrock's response object. var responseText = response.output().message().content().get(0).text(); System.out.println(responseText); return responseText; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converse(); } }

비동기 자바 클라이언트와 함께 베드락의 컨버스 API를 사용하여 미스트랄에 문자 메시지를 보내세요.

// Use the Converse API to send a text message to Mistral // with the async Java client. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ConverseAsync { public static String converseAsync() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Send the message with a basic inference configuration. var request = client.converse(params -> params .modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F)) ); // Prepare a future object to handle the asynchronous response. CompletableFuture<String> future = new CompletableFuture<>(); // Handle the response or error using the future object. request.whenComplete((response, error) -> { if (error == null) { // Extract the generated text from Bedrock's response object. String responseText = response.output().message().content().get(0).text(); future.complete(responseText); } else { future.completeExceptionally(error); } }); try { // Wait for the future object to complete and retrieve the generated text. String responseText = future.get(); System.out.println(responseText); return responseText; } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { converseAsync(); } }

다음 코드 예제는 Bedrock의 Converse API를 사용하여 Mistral에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

베드록의 컨버스 API를 사용하여 미스트랄에 문자 메시지를 보내고 응답 스트림을 실시간으로 처리하세요.

// Use the Converse API to send a text message to Mistral // and print the response stream. import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock; import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole; import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler; import software.amazon.awssdk.services.bedrockruntime.model.Message; import java.util.concurrent.ExecutionException; public class ConverseStream { public static void main(String[] args) { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Create the input text and embed it in a message object with the user role. var inputText = "Describe the purpose of a 'hello world' program in one line."; var message = Message.builder() .content(ContentBlock.fromText(inputText)) .role(ConversationRole.USER) .build(); // Create a handler to extract and print the response text in real-time. var responseStreamHandler = ConverseStreamResponseHandler.builder() .subscriber(ConverseStreamResponseHandler.Visitor.builder() .onContentBlockDelta(chunk -> { String responseText = chunk.delta().text(); System.out.print(responseText); }).build() ).onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()) ).build(); try { // Send the message with a basic inference configuration and attach the handler. client.converseStream(request -> request.modelId(modelId) .messages(message) .inferenceConfig(config -> config .maxTokens(512) .temperature(0.5F) .topP(0.9F) ), responseStreamHandler).get(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); } } }
  • API 세부 정보는 API 레퍼런스를 참조하십시오. ConverseStreamAWS SDK for Java 2.x

다음 코드 예제는 Invoke Model API를 사용하여 Mistral 모델에 문자 메시지를 보내는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하여 문자 메시지를 보내세요.

// Use the native inference API to send a text message to Mistral. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-mistral-text-completion.html var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Mistral's instruction format. var instruction = "<s>[INST] {{prompt}} [/INST]\\n".replace("{{prompt}}", prompt); // Embed the instruction in the the native request payload. var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/outputs/0/text").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • API 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

다음 코드 예제는 Invoke Model API를 사용하여 Mistral AI 모델에 문자 메시지를 보내고 응답 스트림을 인쇄하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

Invoke Model API를 사용하면 문자 메시지를 보내고 응답 스트림을 실시간으로 처리할 수 있습니다.

// Use the native inference API to send a text message to Mistral // and print the response stream. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest; import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler; import java.util.concurrent.ExecutionException; import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor; public class InvokeModelWithResponseStream { public static String invokeModelWithResponseStream() throws ExecutionException, InterruptedException { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeAsyncClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // The InvokeModelWithResponseStream API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-mistral-text-completion.html var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Mistral's instruction format. var instruction = "<s>[INST] {{prompt}} [/INST]\\n".replace("{{prompt}}", prompt); // Embed the instruction in the the native request payload. var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction); // Create a request with the model ID and the model's native request payload. var request = InvokeModelWithResponseStreamRequest.builder() .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) .build(); // Prepare a buffer to accumulate the generated response text. var completeResponseTextBuffer = new StringBuilder(); // Prepare a handler to extract, accumulate, and print the response text in real-time. var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder() .subscriber(Visitor.builder().onChunk(chunk -> { // Extract and print the text from the model's native response. var response = new JSONObject(chunk.bytes().asUtf8String()); var text = new JSONPointer("/outputs/0/text").queryFrom(response); System.out.print(text); // Append the text to the response text buffer. completeResponseTextBuffer.append(text); }).build()).build(); try { // Send the request and wait for the handler to process the response. client.invokeModelWithResponseStream(request, responseStreamHandler).get(); // Return the complete response text. return completeResponseTextBuffer.toString(); } catch (ExecutionException | InterruptedException e) { System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) throws ExecutionException, InterruptedException { invokeModelWithResponseStream(); } }

시나리오

다음 코드 예제는 다양한 양식을 통해 Amazon Bedrock 기반 모델과 상호 작용할 수 있는 플레이그라운드를 생성하는 방법을 보여줍니다.

SDK for Java 2.x

Java 기반 모델(FM) 플레이그라운드는 Amazon Bedrock을 Java와 함께 사용하는 방법을 보여주는 스프링 부트 샘플 애플리케이션입니다. 이 예제는 Java 개발자가 Amazon Bedrock을 사용하여 생성형 AI 지원 애플리케이션을 구축하는 방법을 보여줍니다. 다음 네 가지 플레이그라운드를 사용하여 Amazon Bedrock 기반 모델을 테스트하고 상호 작용할 수 있습니다.

  • 텍스트 플레이그라운드.

  • 채팅 플레이그라운드.

  • 이미지 플레이그라운드.

또한 이 예제에서는 액세스할 수 있는 기본 모델을 해당 특성과 함께 나열하고 표시합니다. 소스 코드 및 배포 지침은 에서 프로젝트를 참조하십시오 GitHub.

이 예시에서 사용되는 서비스
  • Amazon Bedrock 런타임

Stable Diffusion

다음 코드 예제는 Amazon Bedrock에서 Stability.ai 스테이블 디퓨전 XL을 호출하여 이미지를 생성하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

안정적 확산이 적용된 이미지를 만드세요.

// Create an image with Stable Diffusion. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; import java.math.BigInteger; import java.security.SecureRandom; import static com.example.bedrockruntime.libs.ImageTools.displayImage; public class InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Stable Diffusion XL v1. var modelId = "stability.stable-diffusion-xl-v1"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-diffusion-1-0-text-image.html var nativeRequestTemplate = """ { "text_prompts": [{ "text": "{{prompt}}" }], "style_preset": "{{style}}", "seed": {{seed}} }"""; // Define the prompt for the image generation. var prompt = "A stylized picture of a cute old steampunk robot"; // Get a random 32-bit seed for the image generation (max. 4,294,967,295). var seed = new BigInteger(31, new SecureRandom()); // Choose a style preset. var style = "cinematic"; // Embed the prompt, seed, and style in the model's native request payload. String nativeRequest = nativeRequestTemplate .replace("{{prompt}}", prompt) .replace("{{seed}}", seed.toString()) .replace("{{style}}", style); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated image data from the model's response. var base64ImageData = new JSONPointer("/artifacts/0/base64") .queryFrom(responseBody) .toString(); return base64ImageData; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { System.out.println("Generating image. This may take a few seconds..."); String base64ImageData = invokeModel(); displayImage(base64ImageData); } }
  • API 세부 정보는 AWS SDK for Java 2.x API 레퍼런스를 참조하십시오 InvokeModel.