Invoke Model API を使用して Amazon Bedrock で AI21 Labs Jurassic-2 モデルを呼び出す - Amazon Bedrock

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Invoke Model API を使用して Amazon Bedrock で AI21 Labs Jurassic-2 モデルを呼び出す

次のコード例は、Invoke Model API を使用して AI21 Labs Jurassic-2models にテキストメッセージを送信する方法を示しています。

.NET
AWS SDK for .NET
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

/// <summary> /// Asynchronously invokes the AI21 Labs Jurassic-2 model to run an inference based on the provided input. /// </summary> /// <param name="prompt">The prompt that you want Claude to complete.</param> /// <returns>The inference response from the model</returns> /// <remarks> /// The different model providers have individual request and response formats. /// For the format, ranges, and default values for AI21 Labs Jurassic-2, refer to: /// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html /// </remarks> public static async Task<string> InvokeJurassic2Async(string prompt) { string jurassic2ModelId = "ai21.j2-mid-v1"; AmazonBedrockRuntimeClient client = new(RegionEndpoint.USEast1); string payload = new JsonObject() { { "prompt", prompt }, { "maxTokens", 200 }, { "temperature", 0.5 } }.ToJsonString(); string generatedText = ""; try { InvokeModelResponse response = await client.InvokeModelAsync(new InvokeModelRequest() { ModelId = jurassic2ModelId, Body = AWSSDKUtils.GenerateMemoryStreamFromString(payload), ContentType = "application/json", Accept = "application/json" }); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { return JsonNode.ParseAsync(response.Body) .Result?["completions"]? .AsArray()[0]?["data"]? .AsObject()["text"]?.GetValue<string>() ?? ""; } else { Console.WriteLine("InvokeModelAsync failed with status code " + response.HttpStatusCode); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine(e.Message); } return generatedText; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

Go
SDK for Go V2
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

// Each model provider has their own individual request and response formats. // For the format, ranges, and default values for AI21 Labs Jurassic-2, refer to: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html type Jurassic2Request struct { Prompt string `json:"prompt"` MaxTokens int `json:"maxTokens,omitempty"` Temperature float64 `json:"temperature,omitempty"` } type Jurassic2Response struct { Completions []Completion `json:"completions"` } type Completion struct { Data Data `json:"data"` } type Data struct { Text string `json:"text"` } // Invokes AI21 Labs Jurassic-2 on Amazon Bedrock to run an inference using the input // provided in the request body. func (wrapper InvokeModelWrapper) InvokeJurassic2(prompt string) (string, error) { modelId := "ai21.j2-mid-v1" body, err := json.Marshal(Jurassic2Request{ Prompt: prompt, MaxTokens: 200, Temperature: 0.5, }) if err != nil { log.Fatal("failed to marshal", err) } output, err := wrapper.BedrockRuntimeClient.InvokeModel(context.TODO(), &bedrockruntime.InvokeModelInput{ ModelId: aws.String(modelId), ContentType: aws.String("application/json"), Body: body, }) if err != nil { ProcessError(err, modelId) } var response Jurassic2Response if err := json.Unmarshal(output.Body, &response); err != nil { log.Fatal("failed to unmarshal", err) } return response.Completions[0].Data.Text, nil }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for Go

Java
SDK for Java 2.x
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを非同期的に送信します。

/** * Asynchronously invokes the AI21 Labs Jurassic-2 model to run an inference * based on the provided input. * * @param prompt The prompt that you want Jurassic to complete. * @return The inference response generated by the model. */ public static String invokeJurassic2(String prompt) { /* * The different model providers have individual request and response formats. * For the format, ranges, and default values for Anthropic Claude, refer to: * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html */ String jurassic2ModelId = "ai21.j2-mid-v1"; BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder() .region(Region.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); String payload = new JSONObject() .put("prompt", prompt) .put("temperature", 0.5) .put("maxTokens", 200) .toString(); InvokeModelRequest request = InvokeModelRequest.builder() .body(SdkBytes.fromUtf8String(payload)) .modelId(jurassic2ModelId) .contentType("application/json") .accept("application/json") .build(); CompletableFuture<InvokeModelResponse> completableFuture = client.invokeModel(request) .whenComplete((response, exception) -> { if (exception != null) { System.out.println("Model invocation failed: " + exception); } }); String generatedText = ""; try { InvokeModelResponse response = completableFuture.get(); JSONObject responseBody = new JSONObject(response.body().asUtf8String()); generatedText = responseBody .getJSONArray("completions") .getJSONObject(0) .getJSONObject("data") .getString("text"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.err.println(e.getMessage()); } catch (ExecutionException e) { System.err.println(e.getMessage()); } return generatedText; }

モデル呼び出し API を使用してテキストメッセージを送信します。

/** * Invokes the AI21 Labs Jurassic-2 model to run an inference based on the * provided input. * * @param prompt The prompt for Jurassic to complete. * @return The generated response. */ public static String invokeJurassic2(String prompt) { /* * The different model providers have individual request and response formats. * For the format, ranges, and default values for AI21 Labs Jurassic-2, refer * to: * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html */ String jurassic2ModelId = "ai21.j2-mid-v1"; BedrockRuntimeClient client = BedrockRuntimeClient.builder() .region(Region.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); String payload = new JSONObject() .put("prompt", prompt) .put("temperature", 0.5) .put("maxTokens", 200) .toString(); InvokeModelRequest request = InvokeModelRequest.builder() .body(SdkBytes.fromUtf8String(payload)) .modelId(jurassic2ModelId) .contentType("application/json") .accept("application/json") .build(); InvokeModelResponse response = client.invokeModel(request); JSONObject responseBody = new JSONObject(response.body().asUtf8String()); String generatedText = responseBody .getJSONArray("completions") .getJSONObject(0) .getJSONObject("data") .getString("text"); return generatedText; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for JavaScript (v3)
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { FoundationModels } from "../../config/foundation_models.js"; import { BedrockRuntimeClient, InvokeModelCommand, } from "@aws-sdk/client-bedrock-runtime"; /** * @typedef {Object} Data * @property {string} text * * @typedef {Object} Completion * @property {Data} data * * @typedef {Object} ResponseBody * @property {Completion[]} completions */ /** * Invokes an AI21 Labs Jurassic-2 model. * * @param {string} prompt - The input text prompt for the model to complete. * @param {string} [modelId] - The ID of the model to use. Defaults to "ai21.j2-mid-v1". */ export const invokeModel = async (prompt, modelId = "ai21.j2-mid-v1") => { // Create a new Bedrock Runtime client instance. const client = new BedrockRuntimeClient({ region: "us-east-1" }); // Prepare the payload for the model. const payload = { prompt, maxTokens: 500, temperature: 0.5, }; // Invoke the model with the payload and wait for the response. const command = new InvokeModelCommand({ contentType: "application/json", body: JSON.stringify(payload), modelId, }); const apiResponse = await client.send(command); // Decode and return the response(s). const decodedResponseBody = new TextDecoder().decode(apiResponse.body); /** @type {ResponseBody} */ const responseBody = JSON.parse(decodedResponseBody); return responseBody.completions[0].data.text; }; // Invoke the function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { const prompt = 'Complete the following in one sentence: "Once upon a time..."'; const modelId = FoundationModels.JURASSIC2_MID.modelId; console.log(`Prompt: ${prompt}`); console.log(`Model ID: ${modelId}`); try { console.log("-".repeat(53)); const response = await invokeModel(prompt, modelId); console.log(response); } catch (err) { console.log(err); } }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for JavaScript

PHP
SDK for PHP
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

public function invokeJurassic2($prompt) { # The different model providers have individual request and response formats. # For the format, ranges, and default values for AI21 Labs Jurassic-2, refer to: # https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html $completion = ""; try { $modelId = 'ai21.j2-mid-v1'; $body = [ 'prompt' => $prompt, 'temperature' => 0.5, 'maxTokens' => 200, ]; $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => json_encode($body), 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $completion = $response_body->completions[0]->data->text; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $completion; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for PHP

Python
SDK for Python (Boto3)
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

# Use the native inference API to send a text message to AI21 Labs Jurassic-2. import boto3 import json # Create a Bedrock Runtime client in the AWS Region of your choice. client = boto3.client("bedrock-runtime", region_name="us-east-1") # Set the model ID, e.g., Jurassic-2 Mid. model_id = "ai21.j2-mid-v1" # Define the prompt for the model. prompt = "Describe the purpose of a 'hello world' program in one line." # Format the request payload using the model's native structure. native_request = { "prompt": prompt, "maxTokens": 512, "temperature": 0.5, } # Convert the native request to JSON. request = json.dumps(native_request) # Invoke the model with the request. response = client.invoke_model(modelId=model_id, body=request) # Decode the response body. model_response = json.loads(response["body"].read()) # Extract and print the response text. response_text = model_response["completions"][0]["data"]["text"] print(response_text)
  • API の詳細については、 InvokeModel AWS SDK for Python (Boto3) API リファレンスの「」を参照してください。

AWS SDK デベロッパーガイドとコード例の完全なリストについては、「」を参照してくださいAWS SDK でこのサービスを使用する。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。