|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +// |
| 4 | +// snippet-start:[swift.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration] |
| 5 | +// Use the native inference API to create an image with Amazon Nova Canvas |
| 6 | + |
| 7 | +import AWSBedrockRuntime |
| 8 | +import AWSSDKIdentity |
| 9 | +import Foundation |
| 10 | + |
| 11 | +struct NovaImageOutput: Decodable { |
| 12 | + let images: [Data] |
| 13 | +} |
| 14 | + |
| 15 | +func generateImage(_ textPrompt: String) async throws { |
| 16 | + // Create a Bedrock Runtime client in the AWS Region you want to use. |
| 17 | + let config = |
| 18 | + try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( |
| 19 | + region: "us-east-1" |
| 20 | + ) |
| 21 | + config.awsCredentialIdentityResolver = try SSOAWSCredentialIdentityResolver() |
| 22 | + |
| 23 | + let client = BedrockRuntimeClient(config: config) |
| 24 | + |
| 25 | + // Set the model ID. |
| 26 | + let modelId = "amazon.nova-canvas-v1:0" |
| 27 | + |
| 28 | + // Format the request payload using the model's native structure. |
| 29 | + let input = InvokeModelInput( |
| 30 | + accept: "application/json", |
| 31 | + body: """ |
| 32 | + { |
| 33 | + "textToImageParams": { |
| 34 | + "text": "\(textPrompt)" |
| 35 | + }, |
| 36 | + "taskType": "TEXT_IMAGE", |
| 37 | + "imageGenerationConfig": { |
| 38 | + "seed": 42, |
| 39 | + "quality": "standard", |
| 40 | + "width": 512, |
| 41 | + "height": 512, |
| 42 | + "numberOfImages": 1 |
| 43 | + } |
| 44 | + } |
| 45 | + """.data(using: .utf8), |
| 46 | + modelId: modelId |
| 47 | + ) |
| 48 | + |
| 49 | + // Invoke the model with the request. |
| 50 | + let response = try await client.invokeModel(input: input) |
| 51 | + |
| 52 | + // Decode the response body. |
| 53 | + let output = try JSONDecoder().decode(NovaImageOutput.self, from: response.body!) |
| 54 | + |
| 55 | + // Extract the image data. |
| 56 | + guard let data = output.images.first else { |
| 57 | + print("No image data found") |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + // Save the generated image to a local folder. |
| 62 | + let fileURL = URL.documentsDirectory.appending(path: "nova_canvas.png") |
| 63 | + print(fileURL) |
| 64 | + try data.write(to: fileURL) |
| 65 | + print("Image is saved at \(fileURL)") |
| 66 | +} |
| 67 | + |
| 68 | +// snippet-end:[swift.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration] |
| 69 | + |
| 70 | +do { |
| 71 | + try await generateImage( |
| 72 | + "A tabby cat in a teacup" |
| 73 | + ) |
| 74 | +} catch { |
| 75 | + print("An error occurred: \(error)") |
| 76 | +} |
0 commit comments