使用適用於 Java 2.x 的 SDK 的 Amazon 基岩運行時示例 - AWS SDK for Java 2.x

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用適用於 Java 2.x 的 SDK 的 Amazon 基岩運行時示例

下列程式碼範例說明如何使用 Amazon 基岩執行階段來執行動作和實作常見案例。 AWS SDK for Java 2.x

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

每個範例都包含一個連結 GitHub,您可以在其中找到如何在內容中設定和執行程式碼的指示。

愛 21 實驗室茱莉亞西克 -2

下面的代碼示例演示了如何發送文本消息到 AI21 實驗室 Jurassic-2,使用基岩的匡威 API。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用基岩的匡威 API 向 AI21 實驗室侏羅西克 -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(); } }

將文本消息發送到 AI21 實驗室侏羅西克 -2,使用基岩的匡威 API 與異步 Java 客戶端。

// 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 的詳細信息,請參閱 AWS SDK for Java 2.x API 參考中的交談

下面的代碼示例演示了如何發送文本消息到 AI21 實驗室 Jurassic-2,使用調用模型 API。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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 基岩上調用 Amazon Titan 圖像來生成圖像。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用 Amazon 泰坦圖像生成器創建圖像。

// 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中的。

Amazon 泰坦文本

下面的代碼示例演示了如何使用基岩的匡威 API 將文本消息發送到 Amazon 泰坦文本。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用基岩的匡威 API 向 Amazon 泰坦文本發送短信。

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

發送文本消息 Amazon 泰坦文本,使用基岩的匡威 API 與異步 Java 客戶端。

// 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(); } }
  • 有關 API 的詳細信息,請參閱 AWS SDK for Java 2.x API 參考中的交談

下列程式碼範例示範如何使用基岩的匡威 API 傳送文字訊息至 Amazon Titan 文字,並即時處理回應串流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用基岩的匡威 API 傳送文字訊息至 Amazon Titan 文字,並即時處理回應串流。

// 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考ConverseStream中的。

下列程式碼範例顯示如何使用叫用模型 API,將文字訊息傳送至 Amazon Titan 文字。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例顯示如何使用叫用模型 API 傳送文字訊息至 Amazon Titan 文字模型,以及如何列印回應串流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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)。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用 Titan 文本嵌入 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(); } }

調用 Titan 文本嵌入 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考InvokeModel中的。

Anthropic Claude

下面的代碼示例演示了如何使用基岩的匡威 API 將文本消息發送給人類克勞德。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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 和非同步 Java 客戶端發送文本消息給人為克勞德。

// 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 的詳細信息,請參閱 AWS SDK for Java 2.x API 參考中的交談

下面的代碼示例演示了如何使用基岩的匡威 API 發送文本消息給人類克勞德,並實時處理響應流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考ConverseStream中的。

下列程式碼範例示範如何使用叫用模型 API,將文字訊息傳送至人性克勞德。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例示範如何使用叫用模型 API,將文字訊息傳送至人性克勞德模型,以及列印回應資料流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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

下面的代碼示例演示了如何發送文本消息 Cohere 命令,使用基岩的匡威 API。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

發送文本消息到 Cohere 命令,使用基岩的匡威 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(); } }

發送文本消息給 Cohere 命令,使用基岩的匡威 API 與異步 Java 客戶端。

// 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 的詳細信息,請參閱 AWS SDK for Java 2.x API 參考中的交談

下面的代碼示例演示了如何使用基岩的匡威 API 發送文本消息到 Cohere 命令,並實時處理響應流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用基岩的匡威 API 向 Cohere 命令發送文本消息,並實時處理響應流。

// 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考ConverseStream中的。

下列程式碼範例示範如何使用叫用模型 API,將文字訊息傳送至 Cohere 命令 R 和 R +。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例示範如何使用叫用模型 API,將文字訊息傳送至 Cohere 命令。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例會示範如何使用叫用模型 API 搭配回應資料流,將文字訊息傳送至 Cohere 命令。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例會示範如何使用叫用模型 API 搭配回應資料流,將文字訊息傳送至 Cohere 命令。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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 將文本消息發送到元駱駝。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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 與異步 Java 客戶端。

// 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 的詳細信息,請參閱 AWS SDK for Java 2.x API 參考中的交談

下面的代碼示例演示了如何使用基岩的匡威 API 發送文本消息到 Meta Lama 並實時處理響應流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考ConverseStream中的。

下列程式碼範例示範如何使用叫用模型 API,將文字訊息傳送至 Meta Lama 2。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例示範如何使用叫用模型 API,將文字訊息傳送至 Meta Lama 3。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下面的代碼示例演示了如何使用調用模型 API 發送文本消息到 Meta Lama 2,並打印響應流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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(); } }

下面的代碼示例演示了如何使用調用模型 API 發送文本消息到 Meta Lama 3,並打印響應流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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(); } }

米斯特拉尔

下面的代碼示例演示了如何發送文本消息到米斯特拉爾,使用基岩的匡威 API。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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 與異步 Java 客戶端。

// 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(); } }
  • 有關 API 的詳細信息,請參閱 AWS SDK for Java 2.x API 參考中的交談

下面的代碼示例演示了如何發送文本消息到米斯特拉爾,使用基岩的匡威 API 和處理實時響應流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考ConverseStream中的。

下面的代碼示例演示了如何發送一個文本消息到米斯特拉爾模型,使用調用模型 API。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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中的。

下列程式碼範例會示範如何使用叫用模型 API 傳送文字訊息至 Mistral AI 模型,以及列印回應串流。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

使用叫用模型 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 基礎模型互動。

適用於 Java 2.x 的 SDK

Java 基礎模型(FM)遊樂場是一個春季啟動示例應用程序,展示了如何使用 Amazon 基岩與 Java。此範例顯示 Java 開發人員如何使用 Amazon 基岩來建置支援 AI 的生成應用程式。您可以使用下列三個遊樂場來測試 Amazon 基礎模型並與之互動:

  • 一個文本遊樂場。

  • 一個聊天遊樂場。

  • 圖像遊樂場。

此範例也會列出並顯示您可存取的基礎模型及其特性。如需原始程式碼和部署指示,請參閱中的專案GitHub

此範例中使用的服務
  • Amazon 基岩運行時

Stable Diffusion

以下代碼示例演示瞭如何在 Amazon 基岩上調用 Stability.ai 穩定擴散 XL 以生成圖像。

適用於 Java 2.x 的 SDK
注意

還有更多關於 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中的。