Skip to content

Commit 8d758ee

Browse files
committed
Add example for Nova Canvas
# Conflicts: # .doc_gen/metadata/bedrock-runtime_metadata.yaml
1 parent dfe64a7 commit 8d758ee

File tree

12 files changed

+163
-18
lines changed

12 files changed

+163
-18
lines changed

.doc_gen/metadata/bedrock-runtime_metadata.yaml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,14 @@ bedrock-runtime_Converse_AmazonNovaText:
108108
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
109109
snippet_tags:
110110
- javascript.v3.bedrock-runtime.Converse_AmazonNovaText
111+
Kotlin:
112+
versions:
113+
- sdk_version: 1
114+
github: kotlin/services/bedrock-runtime
115+
excerpts:
116+
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
117+
snippet_tags:
118+
- bedrock-runtime.kotlin.Converse_AmazonNovaText
111119
.NET:
112120
versions:
113121
- sdk_version: 3
@@ -439,6 +447,14 @@ bedrock-runtime_ConverseStream_AmazonNovaText:
439447
- description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time.
440448
snippet_tags:
441449
- javascript.v3.bedrock-runtime.ConverseStream_AmazonNovaText
450+
Kotlin:
451+
versions:
452+
- sdk_version: 1
453+
github: kotlin/services/bedrock-runtime
454+
excerpts:
455+
- description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time.
456+
snippet_tags:
457+
- bedrock-runtime.kotlin.ConverseStream_AmazonNovaText
442458
.NET:
443459
versions:
444460
- 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)