Panggil Amazon Titan Image G1 di Amazon Bedrock untuk menghasilkan gambar - Amazon Bedrock

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Panggil Amazon Titan Image G1 di Amazon Bedrock untuk menghasilkan gambar

Contoh kode berikut menunjukkan cara memanggil Amazon Titan Image G1 di Amazon Bedrock untuk menghasilkan gambar.

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Secara asinkron memanggil model dasar Amazon Titan Image Generator G1 untuk menghasilkan gambar.

/// <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; }
  • Untuk detail API, lihat InvokeModeldi Referensi AWS SDK for .NET API.

Go
SDK untuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Minta model Amazon Titan Image Generator G1 untuk menghasilkan gambar.

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 }
  • Untuk detail API, lihat InvokeModeldi Referensi AWS SDK for Go API.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Secara asinkron memanggil model Amazon Titan Image Generator G1 untuk menghasilkan gambar.

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

Minta model Amazon Titan Image Generator G1 untuk menghasilkan gambar.

/** * 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; }
  • Untuk detail API, lihat InvokeModeldi Referensi AWS SDK for Java 2.x API.

PHP
SDK untuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Minta model Amazon Titan Image Generator G1 untuk menghasilkan gambar.

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; }
  • Untuk detail API, lihat InvokeModeldi Referensi AWS SDK for PHP API.

Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Minta model Amazon Titan Image Generator G1 untuk menghasilkan gambar.

# 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}")
  • Untuk detail API, lihat InvokeModeldi AWS SDK for Python (Boto3) Referensi API.

Untuk daftar lengkap panduan pengembang AWS SDK dan contoh kode, lihatMenggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.