Amazon Bedrock で Amazon Titan Image G1 を呼び出してイメージを生成する - Amazon Bedrock

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

Amazon Bedrock で Amazon Titan Image G1 を呼び出してイメージを生成する

次のコード例は、Amazon Bedrock で Amazon Titan Image G1 を呼び出してイメージを生成する方法を示しています。

.NET
AWS SDK for .NET
注記

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

Amazon Titan Image Generator G1 基盤モデルを非同期的に呼び出して画像を生成します。

/// <summary> /// Asynchronously invokes the Amazon Titan Image Generator G1 model to run an inference based on the provided input. /// </summary> /// <param name="prompt">The prompt that describes the image Amazon Titan Image Generator G1 has to generate.</param> /// <returns>A base-64 encoded image generated by model</returns> /// <remarks> /// The different model providers have individual request and response formats. /// For the format, ranges, and default values for Amazon Titan Image Generator G1, refer to: /// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html /// </remarks> public static async Task<string?> InvokeTitanImageGeneratorG1Async(string prompt, int seed) { string titanImageGeneratorG1ModelId = "amazon.titan-image-generator-v1"; AmazonBedrockRuntimeClient client = new(RegionEndpoint.USEast1); string payload = new JsonObject() { { "taskType", "TEXT_IMAGE" }, { "textToImageParams", new JsonObject() { { "text", prompt } } }, { "imageGenerationConfig", new JsonObject() { { "numberOfImages", 1 }, { "quality", "standard" }, { "cfgScale", 8.0f }, { "height", 512 }, { "width", 512 }, { "seed", seed } } } }.ToJsonString(); try { InvokeModelResponse response = await client.InvokeModelAsync(new InvokeModelRequest() { ModelId = titanImageGeneratorG1ModelId, Body = AWSSDKUtils.GenerateMemoryStreamFromString(payload), ContentType = "application/json", Accept = "application/json" }); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { var results = JsonNode.ParseAsync(response.Body).Result?["images"]?.AsArray(); return results?[0]?.GetValue<string>(); } else { Console.WriteLine("InvokeModelAsync failed with status code " + response.HttpStatusCode); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine(e.Message); } return null; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

Go
SDK for Go V2
注記

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

Amazon Titan Image Generator G1 モデルを呼び出して画像を生成します。

type TitanImageRequest struct { TaskType string `json:"taskType"` TextToImageParams TextToImageParams `json:"textToImageParams"` ImageGenerationConfig ImageGenerationConfig `json:"imageGenerationConfig"` } type TextToImageParams struct { Text string `json:"text"` } type ImageGenerationConfig struct { NumberOfImages int `json:"numberOfImages"` Quality string `json:"quality"` CfgScale float64 `json:"cfgScale"` Height int `json:"height"` Width int `json:"width"` Seed int64 `json:"seed"` } type TitanImageResponse struct { Images []string `json:"images"` } // Invokes the Titan Image model to create an image using the input provided // in the request body. func (wrapper InvokeModelWrapper) InvokeTitanImage(prompt string, seed int64) (string, error) { modelId := "amazon.titan-image-generator-v1" body, err := json.Marshal(TitanImageRequest{ TaskType: "TEXT_IMAGE", TextToImageParams: TextToImageParams{ Text: prompt, }, ImageGenerationConfig: ImageGenerationConfig{ NumberOfImages: 1, Quality: "standard", CfgScale: 8.0, Height: 512, Width: 512, Seed: seed, }, }) 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 TitanImageResponse if err := json.Unmarshal(output.Body, &response); err != nil { log.Fatal("failed to unmarshal", err) } base64ImageData := response.Images[0] return base64ImageData, nil }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for Go

Java
SDK for Java 2.x
注記

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

Amazon Titan Image Generator G1 モデルを非同期で呼び出して画像を生成します。

/** * Invokes the Amazon Titan image generation model to create an image using the * input * provided in the request body. * * @param prompt The prompt that you want Amazon Titan to use for image * generation. * @param seed The random noise seed for image generation (Range: 0 to * 2147483647). * @return A Base64-encoded string representing the generated image. */ public static String invokeTitanImage(String prompt, long seed) { /* * The different model providers have individual request and response formats. * For the format, ranges, and default values for Titan Image models refer to: * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan- * image.html */ String titanImageModelId = "amazon.titan-image-generator-v1"; BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder() .region(Region.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); var textToImageParams = new JSONObject().put("text", prompt); var imageGenerationConfig = new JSONObject() .put("numberOfImages", 1) .put("quality", "standard") .put("cfgScale", 8.0) .put("height", 512) .put("width", 512) .put("seed", seed); JSONObject payload = new JSONObject() .put("taskType", "TEXT_IMAGE") .put("textToImageParams", textToImageParams) .put("imageGenerationConfig", imageGenerationConfig); InvokeModelRequest request = InvokeModelRequest.builder() .body(SdkBytes.fromUtf8String(payload.toString())) .modelId(titanImageModelId) .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 base64ImageData = ""; try { InvokeModelResponse response = completableFuture.get(); JSONObject responseBody = new JSONObject(response.body().asUtf8String()); base64ImageData = responseBody .getJSONArray("images") .getString(0); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.err.println(e.getMessage()); } catch (ExecutionException e) { System.err.println(e.getMessage()); } return base64ImageData; }

Amazon Titan Image Generator G1 モデルを呼び出して画像を生成します。

/** * Invokes the Amazon Titan image generation model to create an image using the * input * provided in the request body. * * @param prompt The prompt that you want Amazon Titan to use for image * generation. * @param seed The random noise seed for image generation (Range: 0 to * 2147483647). * @return A Base64-encoded string representing the generated image. */ public static String invokeTitanImage(String prompt, long seed) { /* * The different model providers have individual request and response formats. * For the format, ranges, and default values for Titan Image models refer to: * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan- * image.html */ String titanImageModelId = "amazon.titan-image-generator-v1"; BedrockRuntimeClient client = BedrockRuntimeClient.builder() .region(Region.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); var textToImageParams = new JSONObject().put("text", prompt); var imageGenerationConfig = new JSONObject() .put("numberOfImages", 1) .put("quality", "standard") .put("cfgScale", 8.0) .put("height", 512) .put("width", 512) .put("seed", seed); JSONObject payload = new JSONObject() .put("taskType", "TEXT_IMAGE") .put("textToImageParams", textToImageParams) .put("imageGenerationConfig", imageGenerationConfig); InvokeModelRequest request = InvokeModelRequest.builder() .body(SdkBytes.fromUtf8String(payload.toString())) .modelId(titanImageModelId) .contentType("application/json") .accept("application/json") .build(); InvokeModelResponse response = client.invokeModel(request); JSONObject responseBody = new JSONObject(response.body().asUtf8String()); String base64ImageData = responseBody .getJSONArray("images") .getString(0); return base64ImageData; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for Java 2.x

PHP
SDK for PHP
注記

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

Amazon Titan Image Generator G1 モデルを呼び出して画像を生成します。

public function invokeTitanImage(string $prompt, int $seed) { # The different model providers have individual request and response formats. # For the format, ranges, and default values for Titan Image models refer to: # https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html $base64_image_data = ""; try { $modelId = 'amazon.titan-image-generator-v1'; $request = json_encode([ 'taskType' => 'TEXT_IMAGE', 'textToImageParams' => [ 'text' => $prompt ], 'imageGenerationConfig' => [ 'numberOfImages' => 1, 'quality' => 'standard', 'cfgScale' => 8.0, 'height' => 512, 'width' => 512, 'seed' => $seed ] ]); $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => $request, 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $base64_image_data = $response_body->images[0]; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $base64_image_data; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for PHP

Python
SDK for Python (Boto3)
注記

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

Amazon Titan Image Generator G1 モデルを呼び出して画像を生成します。

# Use the native inference API to create an image with Amazon Titan Image Generator import base64 import boto3 import json import os import random # 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., Titan Image Generator G1. model_id = "amazon.titan-image-generator-v1" # Define the image generation prompt for the model. prompt = "A stylized picture of a cute old steampunk robot." # Generate a random seed. seed = random.randint(0, 2147483647) # Format the request payload using the model's native structure. native_request = { "taskType": "TEXT_IMAGE", "textToImageParams": {"text": prompt}, "imageGenerationConfig": { "numberOfImages": 1, "quality": "standard", "cfgScale": 8.0, "height": 512, "width": 512, "seed": seed, }, } # 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 the image data. base64_image_data = model_response["images"][0] # Save the generated image to a local folder. i, output_dir = 1, "output" if not os.path.exists(output_dir): os.makedirs(output_dir) while os.path.exists(os.path.join(output_dir, f"titan_{i}.png")): i += 1 image_data = base64.b64decode(base64_image_data) image_path = os.path.join(output_dir, f"titan_{i}.png") with open(image_path, "wb") as file: file.write(image_data) print(f"The generated image has been saved to {image_path}")
  • API の詳細については、 InvokeModel AWS SDK for Python (Boto3) API リファレンスの「」を参照してください。

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