Skip to content

Commit ae2207e

Browse files
amasottiscmacdon
andauthored
Kotlin: Add Bedrock Runtime invoke model example (#7221)
Co-authored-by: scmacdon <[email protected]>
1 parent 8f7f791 commit ae2207e

File tree

5 files changed

+230
-0
lines changed

5 files changed

+230
-0
lines changed

.doc_gen/metadata/bedrock-runtime_metadata.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,14 @@ bedrock-runtime_InvokeModel_TitanText:
673673
- description: Use the Invoke Model API to send a text message.
674674
snippet_tags:
675675
- bedrock-runtime.java2.InvokeModel_AmazonTitanText
676+
Kotlin:
677+
versions:
678+
- sdk_version: 1
679+
github: kotlin/services/bedrock-runtime
680+
excerpts:
681+
- description: Use the Invoke Model API to generate a short story.
682+
snippet_tags:
683+
- bedrock-runtime.kotlin.InvokeModel_AmazonTitanText
676684
.NET:
677685
versions:
678686
- sdk_version: 3
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Amazon Bedrock Runtime code examples for the SDK for Kotlin
2+
3+
## Overview
4+
5+
Shows how to use the AWS SDK for Kotlin to work with Amazon Bedrock Runtime.
6+
7+
<!--custom.overview.start-->
8+
This section provides examples that show how to invoke foundation models using the Amazon Bedrock Runtime API with the AWS SDK for Kotlin.
9+
<!--custom.overview.end-->
10+
11+
_Amazon Bedrock Runtime is a fully managed service that makes it easy to use foundation models from third-party providers and Amazon._
12+
13+
## ⚠ Important
14+
15+
* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/).
16+
* Running the tests might result in charges to your AWS account.
17+
* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege).
18+
* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
19+
20+
<!--custom.important.start-->
21+
<!--custom.important.end-->
22+
23+
## Code examples
24+
25+
### Prerequisites
26+
27+
For prerequisites, see the [README](../../README.md#Prerequisites) in the `kotlin` folder.
28+
29+
30+
<!--custom.prerequisites.start-->
31+
> ⚠ 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).
32+
<!--custom.prerequisites.end-->
33+
### Amazon Titan Text
34+
35+
- [InvokeModel](src/main/kotlin/com/example/bedrockruntime/InvokeModel.kt#L6)
36+
37+
38+
<!--custom.examples.start-->
39+
<!--custom.examples.end-->
40+
41+
## Run the examples
42+
43+
### Instructions
44+
45+
46+
<!--custom.instructions.start-->
47+
<!--custom.instructions.end-->
48+
49+
50+
51+
### Tests
52+
53+
⚠ Running tests might result in charges to your AWS account.
54+
55+
56+
To find instructions for running these tests, see the [README](../../README.md#Tests)
57+
in the `kotlin` folder.
58+
59+
60+
61+
<!--custom.tests.start-->
62+
<!--custom.tests.end-->
63+
64+
## Additional resources
65+
66+
- [Amazon Bedrock Runtime User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
67+
- [Amazon Bedrock Runtime API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html)
68+
- [SDK for Kotlin Amazon Bedrock Runtime reference](https://sdk.amazonaws.com/kotlin/api/latest/bedrock-runtime/index.html)
69+
70+
<!--custom.resources.start-->
71+
<!--custom.resources.end-->
72+
73+
---
74+
75+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
76+
77+
SPDX-License-Identifier: Apache-2.0
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
plugins {
2+
kotlin("jvm") version "2.1.10"
3+
id("org.jetbrains.kotlin.plugin.serialization") version "2.1.10"
4+
id("org.jlleitschuh.gradle.ktlint") version "11.3.1" apply true
5+
application
6+
}
7+
8+
group = "com.example.bedrockruntime"
9+
version = "1.0-SNAPSHOT"
10+
11+
repositories {
12+
mavenCentral()
13+
}
14+
15+
buildscript {
16+
repositories {
17+
maven("https://plugins.gradle.org/m2/")
18+
}
19+
dependencies {
20+
classpath("org.jlleitschuh.gradle:ktlint-gradle:11.3.1")
21+
}
22+
}
23+
24+
dependencies {
25+
implementation("aws.sdk.kotlin:bedrockruntime:1.4.11")
26+
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.8.0")
27+
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
28+
}
29+
30+
application {
31+
mainClass.set("com.example.bedrockruntime.InvokeModelKt")
32+
}
33+
34+
// Java and Kotlin configuration
35+
kotlin {
36+
jvmToolchain(21)
37+
}
38+
39+
java {
40+
toolchain {
41+
languageVersion = JavaLanguageVersion.of(21)
42+
}
43+
}
44+
45+
tasks.test {
46+
useJUnitPlatform()
47+
testLogging {
48+
events("passed", "skipped", "failed")
49+
}
50+
51+
// Define the test source set
52+
testClassesDirs += files("build/classes/kotlin/test")
53+
classpath += files("build/classes/kotlin/main", "build/resources/main")
54+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package com.example.bedrockruntime
5+
6+
// snippet-start:[bedrock-runtime.kotlin.InvokeModel_AmazonTitanText]
7+
import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient
8+
import aws.sdk.kotlin.services.bedrockruntime.model.InvokeModelRequest
9+
import kotlinx.serialization.Serializable
10+
import kotlinx.serialization.json.Json
11+
12+
/**
13+
* Before running this Kotlin code example, set up your development environment, including your credentials.
14+
*
15+
* This example demonstrates how to invoke the Titan Text model (amazon.titan-text-lite-v1).
16+
* Remember that you must enable the model before you can use it. See notes in the README.md file.
17+
*
18+
* For more information, see the following documentation topic:
19+
* https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
20+
*/
21+
suspend fun main() {
22+
val prompt = """
23+
Write a short, funny story about a time-traveling cat who
24+
ends up in ancient Egypt at the time of the pyramids.
25+
""".trimIndent()
26+
27+
val response = invokeModel(prompt, "amazon.titan-text-lite-v1")
28+
println("Generated story:\n$response")
29+
}
30+
31+
suspend fun invokeModel(prompt: String, modelId: String): String {
32+
BedrockRuntimeClient { region = "eu-central-1" }.use { client ->
33+
val request = InvokeModelRequest {
34+
this.modelId = modelId
35+
contentType = "application/json"
36+
accept = "application/json"
37+
body = """
38+
{
39+
"inputText": "${prompt.replace(Regex("\\s+"), " ").trim()}",
40+
"textGenerationConfig": {
41+
"maxTokenCount": 1000,
42+
"stopSequences": [],
43+
"temperature": 1,
44+
"topP": 0.7
45+
}
46+
}
47+
""".trimIndent().toByteArray()
48+
}
49+
50+
val response = client.invokeModel(request)
51+
val responseBody = response.body.toString(Charsets.UTF_8)
52+
53+
val jsonParser = Json { ignoreUnknownKeys = true }
54+
return jsonParser
55+
.decodeFromString<BedrockResponse>(responseBody)
56+
.results
57+
.first()
58+
.outputText
59+
}
60+
}
61+
62+
@Serializable
63+
private data class BedrockResponse(val results: List<Result>)
64+
65+
@Serializable
66+
private data class Result(val outputText: String)
67+
// snippet-end:[bedrock-runtime.kotlin.InvokeModel_AmazonTitanText]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
import com.example.bedrockruntime.invokeModel
5+
import kotlinx.coroutines.runBlocking
6+
import org.junit.jupiter.api.Assertions.assertTrue
7+
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation
8+
import org.junit.jupiter.api.Order
9+
import org.junit.jupiter.api.Test
10+
import org.junit.jupiter.api.TestInstance
11+
import org.junit.jupiter.api.TestMethodOrder
12+
13+
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
14+
@TestMethodOrder(OrderAnnotation::class)
15+
class InvokeModelTest {
16+
@Test
17+
@Order(1)
18+
fun listFoundationModels() = runBlocking {
19+
val prompt = "What is the capital of France?"
20+
21+
val answer = invokeModel(prompt, "amazon.titan-text-lite-v1")
22+
assertTrue(answer.isNotBlank())
23+
}
24+
}

0 commit comments

Comments
 (0)