Richiama Amazon Titan Image G1 su Amazon Bedrock per generare un'immagine - Amazon Bedrock

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Richiama Amazon Titan Image G1 su Amazon Bedrock per generare un'immagine

I seguenti esempi di codice mostrano come richiamare Amazon Titan Image G1 su Amazon Bedrock per generare un'immagine.

.NET
AWS SDK for .NET
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Richiama in modo asincrono il modello base Amazon Titan Image Generator G1 per generare immagini.

/// <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; }
  • Per i dettagli sull'API, consulta la sezione API Reference. InvokeModelAWS SDK for .NET

Go
SDK per Go V2
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Richiama il modello Amazon Titan Image Generator G1 per generare immagini.

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 }
  • Per i dettagli sull'API, consulta la sezione API InvokeModelReference AWS SDK for Go .

Java
SDK per Java 2.x
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Richiama in modo asincrono il modello Amazon Titan Image Generator G1 per generare immagini.

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

Richiama il modello Amazon Titan Image Generator G1 per generare immagini.

/** * 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; }
  • Per i dettagli sull'API, consulta la sezione API InvokeModelReference AWS SDK for Java 2.x .

PHP
SDK per PHP
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Richiama il modello Amazon Titan Image Generator G1 per generare immagini.

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; }
  • Per i dettagli sull'API, consulta la sezione API InvokeModelReference AWS SDK for PHP .

Python
SDK per Python (Boto3)
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Richiama il modello Amazon Titan Image Generator G1 per generare immagini.

# 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}")
  • Per i dettagli sull'API, consulta InvokeModel AWSSDK for Python (Boto3) API Reference.

Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. Utilizzo di questo servizio con un AWS SDK Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.