모델 호출 API를 사용하여 Amazon Bedrock에서 AI21 Labs Jurassic-2 모델을 호출하십시오. - Amazon Bedrock

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

모델 호출 API를 사용하여 Amazon Bedrock에서 AI21 Labs Jurassic-2 모델을 호출하십시오.

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

.NET
AWS SDK for .NET
참고

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

Invoke Model 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 세부 정보는 AWS SDK for .NET API InvokeModel참조를 참조하십시오.

Go
SDK for Go V2
참고

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

Invoke Model 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 세부 정보는 AWS SDK for Go API InvokeModel참조를 참조하십시오.

Java
SDK for Java 2.x
참고

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

Invoke Model 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; }

Invoke Model 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 세부 정보는 AWS SDK for Java 2.x API InvokeModel참조를 참조하십시오.

JavaScript
JavaScript (v3) 용 SDK
참고

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

Invoke Model 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 세부 정보는 AWS SDK for JavaScript API InvokeModel참조를 참조하십시오.

PHP
SDK for PHP
참고

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

Invoke Model 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 세부 정보는 AWS SDK for PHP API InvokeModel참조를 참조하십시오.

Python
SDK for Python(Boto3)
참고

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

Invoke Model 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에 대한 자세한 내용은 파이썬용AWS SDK (Boto3) API 레퍼런스를 참조하십시오 InvokeModel.

AWS SDK 개발자 가이드 및 코드 예제의 전체 목록은 을 참조하십시오. AWS SDK와 함께 이 서비스 사용 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.