Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .doc_gen/metadata/bedrock-runtime_metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ bedrock-runtime_Converse_AmazonNovaText:
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
snippet_tags:
- javascript.v3.bedrock-runtime.Converse_AmazonNovaText
Kotlin:
versions:
- sdk_version: 1
github: kotlin/services/bedrock-runtime
excerpts:
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
snippet_tags:
- bedrock-runtime.kotlin.Converse_AmazonNovaText
.NET:
versions:
- sdk_version: 3
Expand Down Expand Up @@ -439,6 +447,14 @@ bedrock-runtime_ConverseStream_AmazonNovaText:
- description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time.
snippet_tags:
- javascript.v3.bedrock-runtime.ConverseStream_AmazonNovaText
Kotlin:
versions:
- sdk_version: 1
github: kotlin/services/bedrock-runtime
excerpts:
- description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time.
snippet_tags:
- bedrock-runtime.kotlin.ConverseStream_AmazonNovaText
.NET:
versions:
- sdk_version: 3
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ kotlin/services/**/build/
kotlin/services/**/gradle/
kotlin/services/**/gradlew
kotlin/services/**/gradlew.bat
kotlin/services/**/.kotlin/
11 changes: 10 additions & 1 deletion kotlin/services/bedrock-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,18 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `kotli
<!--custom.prerequisites.start-->
> ⚠ You must request access to a model before you can use it. If you try to use the model (with the API or console) before you have requested access to it, you will receive an error message. For more information, see [Model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html).
<!--custom.prerequisites.end-->
### Amazon Nova

- [Converse](src/main/kotlin/com/example/bedrockruntime/models/amazon/nova/text/Converse.kt#L6)
- [ConverseStream](src/main/kotlin/com/example/bedrockruntime/models/amazon/nova/text/ConverseStream.kt#L6)

### Amazon Nova Canvas

- [InvokeModel](src/main/kotlin/com/example/bedrockruntime/models/amazon/nova/canvas/InvokeModel.kt#L6)

### Amazon Titan Text

- [InvokeModel](src/main/kotlin/com/example/bedrockruntime/InvokeModel.kt#L6)
- [InvokeModel](src/main/kotlin/com/example/bedrockruntime/models/amazon/titan/text/InvokeModel.kt#L6)


<!--custom.examples.start-->
Expand Down
37 changes: 12 additions & 25 deletions kotlin/services/bedrock-runtime/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,54 +1,41 @@
plugins {
kotlin("jvm") version "2.1.10"
id("org.jetbrains.kotlin.plugin.serialization") version "2.1.10"
Comment thread
DennisTraub marked this conversation as resolved.
id("org.jlleitschuh.gradle.ktlint") version "11.3.1" apply true
id("org.jlleitschuh.gradle.ktlint") version "12.1.1"
application
}

group = "com.example.bedrockruntime"
version = "1.0-SNAPSHOT"

val awsSdkVersion = "1.4.27"
val junitVersion = "5.12.0"

repositories {
mavenCentral()
}

buildscript {
repositories {
maven("https://plugins.gradle.org/m2/")
}
dependencies {
classpath("org.jlleitschuh.gradle:ktlint-gradle:11.3.1")
}
}

dependencies {
implementation("aws.sdk.kotlin:bedrockruntime:1.4.11")
implementation("aws.sdk.kotlin:bedrockruntime:$awsSdkVersion")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.8.0")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
}

application {
mainClass.set("com.example.bedrockruntime.InvokeModelKt")
testImplementation("org.junit.jupiter:junit-jupiter:$junitVersion")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
testImplementation("org.jetbrains.kotlin:kotlin-reflect")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

// Java and Kotlin configuration
kotlin {
jvmToolchain(21)
}

java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}

tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}

// Define the test source set
testClassesDirs += files("build/classes/kotlin/test")
classpath += files("build/classes/kotlin/main", "build/resources/main")
application {
mainClass.set("com.example.bedrockruntime.InvokeModelKt")
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package com.example.bedrockruntime.libs

import java.io.ByteArrayInputStream
import java.io.IOException
import javax.imageio.ImageIO
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel

/**
* Utility object for handling image-related operations.
*/
object ImageTools {
/**
* Displays a byte array as an image in a new window.
*
* Creates a new JFrame window that displays the image represented by the provided byte array.
* The window will close the application when closed (EXIT_ON_CLOSE).
*
* @param imageData The image data as a byte array
* @throws RuntimeException if there is an error reading the image data
*/
fun displayImage(imageData: ByteArray) {
try {
val image = ImageIO.read(ByteArrayInputStream(imageData))
JFrame("Image").apply {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
contentPane.add(JLabel(ImageIcon(image)))
pack()
isVisible = true
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package com.example.bedrockruntime.models.amazon.nova.canvas

// snippet-start:[bedrock-runtime.kotlin.InvokeModel_AmazonNovaImageGeneration]

import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient
import aws.sdk.kotlin.services.bedrockruntime.model.InvokeModelRequest
import com.example.bedrockruntime.libs.ImageTools.displayImage
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.util.*

/**
* This example demonstrates how to use Amazon Nova Canvas to generate images.
* It shows how to:
* - Set up the Amazon Bedrock runtime client
* - Configure the image generation parameters
* - Send a request to generate an image
* - Process the response and display the generated image
*/
suspend fun main() {
println("Generating image. This may take a few seconds...")
val imageData = invokeModel()
displayImage(imageData)
}

// Data class for parsing the model's response
@Serializable
private data class Response(val images: List<String>)

// Configure JSON parser to ignore unknown fields in the response
private val json = Json { ignoreUnknownKeys = true }

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

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

// Configure the generation parameters and create the request
// First, set the main parameters:
// - prompt: Text description of the image to generate
// - seed: Random number for reproducible generation (0 to 858,993,459)
val prompt = "A stylized picture of a cute old steampunk robot"
val seed = (0..858_993_459).random()

// Then, create the request using a template with the following structure:
// - taskType: TEXT_IMAGE (specifies text-to-image generation)
// - textToImageParams: Contains the text prompt
// - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.)
// For a list of available request parameters, see:
// https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html
val request = """
{
"taskType": "TEXT_IMAGE",
"textToImageParams": {
"text": "$prompt"
},
"imageGenerationConfig": {
"seed": $seed,
"quality": "standard"
}
}
""".trimIndent()

// Send the request and process the model's response
runCatching {
// Send the request to the model
val response = client.invokeModel(
InvokeModelRequest {
this.modelId = modelId
body = request.toByteArray()
},
)

// Parse the response and extract the generated image
val jsonResponse = response.body.toString(Charsets.UTF_8)
val parsedResponse = json.decodeFromString<Response>(jsonResponse)

// Extract the generated image and return it as a byte array for better handling
val base64Image = parsedResponse.images.first()
return Base64.getDecoder().decode(base64Image)
}.getOrElse { error ->
System.err.println("ERROR: Can't invoke '$modelId'. Reason: ${error.message}")
throw RuntimeException("Failed to generate image with model $modelId", error)
}
}
}

// snippet-end:[bedrock-runtime.kotlin.InvokeModel_AmazonNovaImageGeneration]
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package com.example.bedrockruntime.models.amazon.nova.text

// snippet-start:[bedrock-runtime.kotlin.Converse_AmazonNovaText]

import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient
import aws.sdk.kotlin.services.bedrockruntime.model.ContentBlock
import aws.sdk.kotlin.services.bedrockruntime.model.ConversationRole
import aws.sdk.kotlin.services.bedrockruntime.model.ConverseRequest
import aws.sdk.kotlin.services.bedrockruntime.model.Message

/**
* This example demonstrates how to use the Amazon Nova foundation models to generate text.
* It shows how to:
* - Set up the Amazon Bedrock runtime client
* - Create a message
* - Configure and send a request
* - Process the response
*/
suspend fun main() {
converse().also { println(it) }
}

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

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

// Create the message with the user's prompt
val prompt = "Describe the purpose of a 'hello world' program in one line."
val message = Message {
role = ConversationRole.User
content = listOf(ContentBlock.Text(prompt))
}

// Configure the request with optional model parameters
val request = ConverseRequest {
this.modelId = modelId
messages = listOf(message)
inferenceConfig {
maxTokens = 500 // Maximum response length
temperature = 0.5F // Lower values: more focused output
// topP = 0.8F // Alternative to temperature
}
}

// Send the request and process the model's response
runCatching {
val response = client.converse(request)
return response.output!!.asMessage().content.first().asText()
}.getOrElse { error ->
error.message?.let { e -> System.err.println("ERROR: Can't invoke '$modelId'. Reason: $e") }
throw RuntimeException("Failed to generate text with model $modelId", error)
}
}
}
// snippet-end:[bedrock-runtime.kotlin.Converse_AmazonNovaText]
Loading
Loading