Skip to content

Commit ef8b58b

Browse files
[examples] Sync SDK examples from awsdocs/aws-doc-sdk-examples
Includes commit(s): 70b06d499f5a048088de0a371fc60d4a6438220c 8025bf7e42b94b424f5a40ecf6325d0a3a4a5d8a Co-authored-by: David Souther <[email protected]>
1 parent 13a271e commit ef8b58b

File tree

13 files changed

+770
-16
lines changed

13 files changed

+770
-16
lines changed

examples/examples/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ members = [
1010
"auto-scaling",
1111
"autoscalingplans",
1212
"batch",
13+
"bedrock-runtime",
1314
"cloudformation",
1415
"cloudwatch",
1516
"cloudwatchlogs",

examples/examples/aurora/README.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,19 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `rustv
3838

3939
Code excerpts that show you how to call individual service functions.
4040

41-
- [CreateDBCluster](src/aurora_scenario/mod.rs#L352)
42-
- [CreateDBClusterParameterGroup](src/aurora_scenario/mod.rs#L203)
43-
- [CreateDBClusterSnapshot](src/aurora_scenario/mod.rs#L352)
44-
- [CreateDBInstance](src/aurora_scenario/mod.rs#L352)
45-
- [DeleteDBCluster](src/aurora_scenario/mod.rs#L512)
46-
- [DeleteDBClusterParameterGroup](src/aurora_scenario/mod.rs#L512)
47-
- [DeleteDBInstance](src/aurora_scenario/mod.rs#L512)
48-
- [DescribeDBClusterParameters](src/aurora_scenario/mod.rs#L286)
49-
- [DescribeDBClusters](src/aurora_scenario/mod.rs#L352)
41+
- [CreateDBCluster](src/aurora_scenario/mod.rs#L353)
42+
- [CreateDBClusterParameterGroup](src/aurora_scenario/mod.rs#L204)
43+
- [CreateDBClusterSnapshot](src/aurora_scenario/mod.rs#L353)
44+
- [CreateDBInstance](src/aurora_scenario/mod.rs#L353)
45+
- [DeleteDBCluster](src/aurora_scenario/mod.rs#L513)
46+
- [DeleteDBClusterParameterGroup](src/aurora_scenario/mod.rs#L513)
47+
- [DeleteDBInstance](src/aurora_scenario/mod.rs#L513)
48+
- [DescribeDBClusterParameters](src/aurora_scenario/mod.rs#L287)
49+
- [DescribeDBClusters](src/aurora_scenario/mod.rs#L353)
5050
- [DescribeDBEngineVersions](src/aurora_scenario/mod.rs#L142)
51-
- [DescribeDBInstances](src/aurora_scenario/mod.rs#L512)
51+
- [DescribeDBInstances](src/aurora_scenario/mod.rs#L513)
5252
- [DescribeOrderableDBInstanceOptions](src/aurora_scenario/mod.rs#L179)
53-
- [ModifyDBClusterParameterGroup](src/aurora_scenario/mod.rs#L315)
53+
- [ModifyDBClusterParameterGroup](src/aurora_scenario/mod.rs#L316)
5454

5555
### Scenarios
5656

examples/examples/aurora/src/aurora_scenario/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ impl AuroraScenario {
193193
.map(|options| {
194194
options
195195
.iter()
196+
.filter(|o| o.storage_type() == Some("aurora"))
196197
.map(|o| o.db_instance_class().unwrap_or_default().to_string())
197198
.collect::<Vec<String>>()
198199
})

examples/examples/aurora/src/aurora_scenario/tests.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,19 @@ async fn test_scenario_get_instance_classes() {
205205
Ok(vec![
206206
OrderableDbInstanceOption::builder()
207207
.db_instance_class("t1")
208+
.storage_type("aurora")
209+
.build(),
210+
OrderableDbInstanceOption::builder()
211+
.db_instance_class("t1")
212+
.storage_type("aurora-iopt1")
208213
.build(),
209214
OrderableDbInstanceOption::builder()
210215
.db_instance_class("t2")
216+
.storage_type("aurora")
211217
.build(),
212218
OrderableDbInstanceOption::builder()
213219
.db_instance_class("t3")
220+
.storage_type("aurora")
214221
.build(),
215222
])
216223
});
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
2+
[package]
3+
name = "bedrock-runtime"
4+
version = "0.1.0"
5+
edition = "2021"
6+
publish = false
7+
8+
[dependencies]
9+
aws-config = { version = "1.5.4", path = "../../../sdk/aws-config" }
10+
aws-sdk-bedrockruntime = { version = "1.42.0", path = "../../../sdk/bedrockruntime" }
11+
aws-smithy-runtime-api = { version = "1.7.1", path = "../../../sdk/aws-smithy-runtime-api" }
12+
aws-smithy-types = { version = "1.2.0", path = "../../../sdk/aws-smithy-types" }
13+
reqwest = "0.12.5"
14+
serde = "1.0.204"
15+
serde_json = "1.0.120"
16+
tracing = "0.1.40"
17+
tracing-subscriber = "0.3.18"
18+
19+
[dependencies.tokio]
20+
version = "1.38.1"
21+
features = ["full"]
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 Rust
2+
3+
## Overview
4+
5+
Shows how to use the AWS SDK for Rust to work with Amazon Bedrock Runtime.
6+
7+
<!--custom.overview.start-->
8+
<!--custom.overview.end-->
9+
10+
_Amazon Bedrock Runtime is a fully managed service that makes it easy to use foundation models from third-party providers and Amazon._
11+
12+
## ⚠ Important
13+
14+
* 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/).
15+
* Running the tests might result in charges to your AWS account.
16+
* 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).
17+
* 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).
18+
19+
<!--custom.important.start-->
20+
<!--custom.important.end-->
21+
22+
## Code examples
23+
24+
### Prerequisites
25+
26+
For prerequisites, see the [README](../../README.md#Prerequisites) in the `rustv1` folder.
27+
28+
29+
<!--custom.prerequisites.start-->
30+
<!--custom.prerequisites.end-->
31+
### Anthropic Claude
32+
33+
- [Converse](src/bin/converse.rs#L43)
34+
- [ConverseStream](src/bin/converse-stream.rs#L70)
35+
- [Scenario: Tool use with the Converse API](src/bin/tool-use.rs#L242)
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 `rustv1` 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 Rust Amazon Bedrock Runtime reference](https://docs.rs/aws-sdk-bedrock-runtime/latest/aws_sdk_bedrock-runtime/)
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: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// snippet-start:[rust.bedrock-runtime.ConverseStream_AnthropicClaude.supporting]
5+
use aws_config::BehaviorVersion;
6+
use aws_sdk_bedrockruntime::{
7+
error::ProvideErrorMetadata,
8+
operation::converse_stream::ConverseStreamError,
9+
types::{
10+
error::ConverseStreamOutputError, ContentBlock, ConversationRole,
11+
ConverseStreamOutput as ConverseStreamOutputType, Message,
12+
},
13+
Client,
14+
};
15+
16+
// Set the model ID, e.g., Claude 3 Haiku.
17+
const MODEL_ID: &str = "anthropic.claude-3-haiku-20240307-v1:0";
18+
const CLAUDE_REGION: &str = "us-east-1";
19+
20+
// Start a conversation with the user message.
21+
const USER_MESSAGE: &str = "Describe the purpose of a 'hello world' program in one line.";
22+
23+
#[derive(Debug)]
24+
struct BedrockConverseStreamError(String);
25+
impl std::fmt::Display for BedrockConverseStreamError {
26+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27+
write!(f, "Can't invoke '{}'. Reason: {}", MODEL_ID, self.0)
28+
}
29+
}
30+
impl std::error::Error for BedrockConverseStreamError {}
31+
impl From<&str> for BedrockConverseStreamError {
32+
fn from(value: &str) -> Self {
33+
BedrockConverseStreamError(value.into())
34+
}
35+
}
36+
37+
impl From<&ConverseStreamError> for BedrockConverseStreamError {
38+
fn from(value: &ConverseStreamError) -> Self {
39+
BedrockConverseStreamError(
40+
match value {
41+
ConverseStreamError::ModelTimeoutException(_) => "Model took too long",
42+
ConverseStreamError::ModelNotReadyException(_) => "Model is not ready",
43+
_ => "Unknown",
44+
}
45+
.into(),
46+
)
47+
}
48+
}
49+
50+
impl From<&ConverseStreamOutputError> for BedrockConverseStreamError {
51+
fn from(value: &ConverseStreamOutputError) -> Self {
52+
match value {
53+
ConverseStreamOutputError::ValidationException(ve) => BedrockConverseStreamError(
54+
ve.message().unwrap_or("Unknown ValidationException").into(),
55+
),
56+
ConverseStreamOutputError::ThrottlingException(te) => BedrockConverseStreamError(
57+
te.message().unwrap_or("Unknown ThrottlingException").into(),
58+
),
59+
value => BedrockConverseStreamError(
60+
value
61+
.message()
62+
.unwrap_or("Unknown StreamOutput exception")
63+
.into(),
64+
),
65+
}
66+
}
67+
}
68+
// snippet-end:[rust.bedrock-runtime.ConverseStream_AnthropicClaude.supporting]
69+
70+
// snippet-start:[rust.bedrock-runtime.ConverseStream_AnthropicClaude]
71+
#[tokio::main]
72+
async fn main() -> Result<(), BedrockConverseStreamError> {
73+
tracing_subscriber::fmt::init();
74+
let sdk_config = aws_config::defaults(BehaviorVersion::latest())
75+
.region(CLAUDE_REGION)
76+
.load()
77+
.await;
78+
let client = Client::new(&sdk_config);
79+
80+
let response = client
81+
.converse_stream()
82+
.model_id(MODEL_ID)
83+
.messages(
84+
Message::builder()
85+
.role(ConversationRole::User)
86+
.content(ContentBlock::Text(USER_MESSAGE.to_string()))
87+
.build()
88+
.map_err(|_| "failed to build message")?,
89+
)
90+
.send()
91+
.await;
92+
93+
let mut stream = match response {
94+
Ok(output) => Ok(output.stream),
95+
Err(e) => Err(BedrockConverseStreamError::from(
96+
e.as_service_error().unwrap(),
97+
)),
98+
}?;
99+
100+
loop {
101+
let token = stream.recv().await;
102+
match token {
103+
Ok(Some(text)) => {
104+
let next = get_converse_output_text(text)?;
105+
print!("{}", next);
106+
Ok(())
107+
}
108+
Ok(None) => break,
109+
Err(e) => Err(e
110+
.as_service_error()
111+
.map(BedrockConverseStreamError::from)
112+
.unwrap_or(BedrockConverseStreamError(
113+
"Unknown error receiving stream".into(),
114+
))),
115+
}?
116+
}
117+
118+
println!();
119+
120+
Ok(())
121+
}
122+
123+
fn get_converse_output_text(
124+
output: ConverseStreamOutputType,
125+
) -> Result<String, BedrockConverseStreamError> {
126+
Ok(match output {
127+
ConverseStreamOutputType::ContentBlockDelta(event) => match event.delta() {
128+
Some(delta) => delta
129+
.as_text()
130+
.map(|s| s.clone())
131+
.unwrap_or_else(|_| "".into()),
132+
None => "".into(),
133+
},
134+
_ => "".into(),
135+
})
136+
}
137+
138+
// snippet-end:[rust.bedrock-runtime.ConverseStream_AnthropicClaude]

0 commit comments

Comments
 (0)