Appelez Amazon Titan Image G1 sur Amazon Bedrock pour générer une image - Amazon Bedrock

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Appelez Amazon Titan Image G1 sur Amazon Bedrock pour générer une image

Les exemples de code suivants montrent comment invoquer Amazon Titan Image G1 sur Amazon Bedrock pour générer une image.

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

Invoquez de manière asynchrone le modèle de base Amazon Titan Image Generator G1 pour générer des images.

/// <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; }
  • Pour plus de détails sur l'API, reportez-vous InvokeModelà la section Référence des AWS SDK for .NET API.

Go
Kit SDK for Go V2
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

Appelez le modèle Amazon Titan Image Generator G1 pour générer des images.

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 }
  • Pour plus de détails sur l'API, reportez-vous InvokeModelà la section Référence des AWS SDK for Go API.

Java
SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

Invoquez de manière asynchrone le modèle Amazon Titan Image Generator G1 pour générer des images.

/** * 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; }

Appelez le modèle Amazon Titan Image Generator G1 pour générer des images.

/** * 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; }
  • Pour plus de détails sur l'API, reportez-vous InvokeModelà la section Référence des AWS SDK for Java 2.x API.

PHP
Kit SDK pour PHP
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

Appelez le modèle Amazon Titan Image Generator G1 pour générer des images.

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; }
  • Pour plus de détails sur l'API, reportez-vous InvokeModelà la section Référence des AWS SDK for PHP API.

Python
SDK pour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l'exemple complet et découvrez comment le configurer et l'exécuter dans le référentiel d'exemples de code AWS.

Appelez le modèle Amazon Titan Image Generator G1 pour générer des images.

# 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}")
  • Pour plus de détails sur l'API, consultez InvokeModelle AWS manuel de référence de l'API SDK for Python (Boto3).

Pour obtenir la liste complète des guides de développement du AWS SDK et des exemples de code, consultezUtilisation de ce service avec un AWS SDK. Cette rubrique comprend également des informations sur le démarrage et sur les versions précédentes de SDK.