Skip to content

Commit 8843315

Browse files
committed
Add example for Nova Canvas
1 parent 24027a3 commit 8843315

File tree

12 files changed

+172
-19
lines changed

12 files changed

+172
-19
lines changed

.doc_gen/metadata/bedrock-runtime_metadata.yaml

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,14 @@ bedrock-runtime_Converse_AmazonNovaText:
100100
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
101101
snippet_tags:
102102
- bedrock-runtime.java2.Converse_AmazonNovaText
103+
Kotlin:
104+
versions:
105+
- sdk_version: 1
106+
github: kotlin/services/bedrock-runtime
107+
excerpts:
108+
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
109+
snippet_tags:
110+
- bedrock-runtime.kotlin.Converse_AmazonNovaText
103111
.NET:
104112
versions:
105113
- sdk_version: 3
@@ -423,6 +431,14 @@ bedrock-runtime_ConverseStream_AmazonNovaText:
423431
- description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time.
424432
snippet_tags:
425433
- bedrock-runtime.java2.ConverseStream_AmazonNovaText
434+
Kotlin:
435+
versions:
436+
- sdk_version: 1
437+
github: kotlin/services/bedrock-runtime
438+
excerpts:
439+
- description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time.
440+
snippet_tags:
441+
- bedrock-runtime.kotlin.ConverseStream_AmazonNovaText
426442
.NET:
427443
versions:
428444
- sdk_version: 3
@@ -736,7 +752,7 @@ bedrock-runtime_InvokeModel_TitanText:
736752
- sdk_version: 1
737753
github: kotlin/services/bedrock-runtime
738754
excerpts:
739-
- description: Use the Invoke Model API to generate a short story.
755+
- description: Use the Invoke Model API to send a text message.
740756
snippet_tags:
741757
- bedrock-runtime.kotlin.InvokeModel_AmazonTitanText
742758
.NET:
@@ -1235,6 +1251,14 @@ bedrock-runtime_InvokeModel_AmazonNovaImageGeneration:
12351251
- description: Create an image with Amazon Nova Canvas.
12361252
snippet_tags:
12371253
- bedrock-runtime.java2.InvokeModel_AmazonNovaImageGeneration
1254+
Kotlin:
1255+
versions:
1256+
- sdk_version: 1
1257+
github: kotlin/services/bedrock-runtime
1258+
excerpts:
1259+
- description: Create an image with Amazon Nova Canvas.
1260+
snippet_tags:
1261+
- bedrock-runtime.kotlin.InvokeModel_AmazonNovaImageGeneration
12381262
.NET:
12391263
versions:
12401264
- sdk_version: 3

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ kotlin/services/**/build/
3636
kotlin/services/**/gradle/
3737
kotlin/services/**/gradlew
3838
kotlin/services/**/gradlew.bat
39+
kotlin/services/**/.kotlin/

kotlin/services/bedrock-runtime/build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ dependencies {
2121

2222
testImplementation("org.junit.jupiter:junit-jupiter:$junitVersion")
2323
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
24+
testImplementation("org.jetbrains.kotlin:kotlin-reflect")
2425
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
2526
}
2627

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package com.example.bedrockruntime.libs
5+
6+
import java.io.ByteArrayInputStream
7+
import java.io.IOException
8+
import javax.imageio.ImageIO
9+
import javax.swing.ImageIcon
10+
import javax.swing.JFrame
11+
import javax.swing.JLabel
12+
13+
object ImageTools {
14+
fun displayImage(imageData: ByteArray) {
15+
try {
16+
val image = ImageIO.read(ByteArrayInputStream(imageData))
17+
JFrame("Image").apply {
18+
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
19+
contentPane.add(JLabel(ImageIcon(image)))
20+
pack()
21+
isVisible = true
22+
}
23+
} catch (e: IOException) {
24+
throw RuntimeException(e)
25+
}
26+
}
27+
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package com.example.bedrockruntime.models.amazon.nova.canvas
5+
6+
// snippet-start:[bedrock-runtime.kotlin.InvokeModel_AmazonNovaImageGeneration]
7+
8+
import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient
9+
import aws.sdk.kotlin.services.bedrockruntime.model.InvokeModelRequest
10+
import com.example.bedrockruntime.libs.ImageTools.displayImage
11+
import kotlinx.serialization.Serializable
12+
import kotlinx.serialization.json.Json
13+
import java.util.*
14+
15+
/**
16+
* This example demonstrates how to use Amazon Nova Canvas to generate images.
17+
* It shows how to:
18+
* - Set up the Amazon Bedrock runtime client
19+
* - Configure the image generation parameters
20+
* - Send a request to generate an image
21+
* - Process the response and display the generated image
22+
*/
23+
suspend fun main() {
24+
println("Generating image. This may take a few seconds...")
25+
val imageData = invokeModel()
26+
displayImage(imageData)
27+
}
28+
29+
// Data class for parsing the model's response
30+
@Serializable
31+
private data class Response(val images: List<String>)
32+
33+
// Configure JSON parser to ignore unknown fields in the response
34+
private val json = Json { ignoreUnknownKeys = true }
35+
36+
suspend fun invokeModel(): ByteArray {
37+
// Create and configure the Bedrock runtime client
38+
BedrockRuntimeClient { region = "us-east-1" }.use { client ->
39+
40+
// Specify the model ID. For the latest available models, see:
41+
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
42+
val modelId = "amazon.nova-canvas-v1:0"
43+
44+
// Configure the generation parameters and create the request
45+
// First, set the main parameters:
46+
// - prompt: Text description of the image to generate
47+
// - seed: Random number for reproducible generation (0 to 858,993,459)
48+
val prompt = "A stylized picture of a cute old steampunk robot"
49+
val seed = (0..858_993_459).random()
50+
51+
// Then, create the request using a template with the following structure:
52+
// - taskType: TEXT_IMAGE (specifies text-to-image generation)
53+
// - textToImageParams: Contains the text prompt
54+
// - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.)
55+
// For a list of available request parameters, see:
56+
// https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html
57+
val request = """
58+
{
59+
"taskType": "TEXT_IMAGE",
60+
"textToImageParams": {
61+
"text": "$prompt"
62+
},
63+
"imageGenerationConfig": {
64+
"seed": $seed,
65+
"quality": "standard"
66+
}
67+
}
68+
""".trimIndent()
69+
70+
// Send the request and process the model's response
71+
runCatching {
72+
// Send the request to the model
73+
val response = client.invokeModel(InvokeModelRequest {
74+
this.modelId = modelId
75+
body = request.toByteArray()
76+
})
77+
78+
// Parse the response and extract the generated image
79+
val jsonResponse = response.body.toString(Charsets.UTF_8)
80+
val parsedResponse = json.decodeFromString<Response>(jsonResponse)
81+
82+
// Extract the generated image and return it as a byte array for better handling
83+
val base64Image = parsedResponse.images.first()
84+
return Base64.getDecoder().decode(base64Image)
85+
86+
}.getOrElse { error ->
87+
System.err.println("ERROR: Can't invoke '$modelId'. Reason: ${error.message}")
88+
throw RuntimeException("Failed to generate image with model $modelId", error)
89+
}
90+
}
91+
}
92+
93+
// snippet-end:[bedrock-runtime.kotlin.InvokeModel_AmazonNovaImageGeneration]

kotlin/services/bedrock-runtime/src/main/kotlin/com/example/bedrockruntime/models/amazon/nova/text/Converse.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ suspend fun converse(): String {
2727
// Create and configure the Bedrock runtime client
2828
BedrockRuntimeClient { region = "us-east-1" }.use { client ->
2929

30-
// For the latest available models, see:
30+
// Specify the model ID. For the latest available models, see:
3131
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
3232
val modelId = "amazon.nova-lite-v1:0"
3333

kotlin/services/bedrock-runtime/src/main/kotlin/com/example/bedrockruntime/models/amazon/nova/text/ConverseStream.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ suspend fun converseStream(): String {
2828
// Create and configure the Bedrock runtime client
2929
BedrockRuntimeClient { region = "us-east-1" }.use { client ->
3030

31-
// For the latest available models, see:
31+
// Specify the model ID. For the latest available models, see:
3232
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
3333
val modelId = "amazon.nova-lite-v1:0"
3434

kotlin/services/bedrock-runtime/src/main/kotlin/com/example/bedrockruntime/models/amazon/titan/text/InvokeModel.kt

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,24 @@ suspend fun main() {
2222
invokeModel().also { println(it) }
2323
}
2424

25+
// Data class for parsing the model's response
26+
@Serializable
27+
private data class BedrockResponse(val results: List<Result>) {
28+
@Serializable
29+
data class Result(
30+
val outputText: String
31+
)
32+
}
33+
34+
2535
// Initialize JSON parser with relaxed configuration
2636
private val json = Json { ignoreUnknownKeys = true }
2737

2838
suspend fun invokeModel(): String {
2939
// Create and configure the Bedrock runtime client
3040
BedrockRuntimeClient { region = "us-east-1" }.use { client ->
3141

32-
// For the latest available models, see:
42+
// Specify the model ID. For the latest available models, see:
3343
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
3444
val modelId = "amazon.titan-text-lite-v1"
3545

@@ -45,7 +55,7 @@ suspend fun invokeModel(): String {
4555
"temperature": 0.5
4656
}
4757
}
48-
""".trimIndent()
58+
""".trimIndent()
4959

5060
// Send the request and process the model's response
5161
runCatching {
@@ -73,10 +83,4 @@ suspend fun invokeModel(): String {
7383
}
7484
}
7585

76-
@Serializable
77-
private data class BedrockResponse(val results: List<Result>)
78-
79-
@Serializable
80-
private data class Result(val outputText: String)
81-
8286
// snippet-end:[bedrock-runtime.kotlin.InvokeModel_AmazonTitanText]

kotlin/services/bedrock-runtime/src/test/kotlin/models/AbstractModelTest.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,6 @@ abstract class AbstractModelTest {
8181
*/
8282
data class ModelTest(
8383
val name: String,
84-
val function: suspend () -> String
84+
val function: suspend () -> Any
8585
)
8686
}

kotlin/services/bedrock-runtime/src/test/kotlin/models/TestConverse.kt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
package models
55

6-
import com.example.bedrockruntime.models.amazon.nova.text.converse
7-
86
import java.util.stream.Stream
97

108
/**
@@ -18,7 +16,7 @@ class TestConverse : AbstractModelTest() {
1816
*/
1917
override fun modelProvider(): Stream<ModelTest> {
2018
return listOf(
21-
ModelTest("Amazon Nova", ::converse)
19+
ModelTest("Amazon Nova") { com.example.bedrockruntime.models.amazon.nova.text.converse() }
2220
).stream()
2321
}
2422
}

0 commit comments

Comments
 (0)