Skip to content

Commit 4293c6a

Browse files
AWSChrisrlhagerm
andcommitted
Python: Added Hello bedrock runtime examples for Amazon Bedrock (#7244)
--------- Co-authored-by: Rachel Hagerman <[email protected]>
1 parent 7b31c19 commit 4293c6a

File tree

6 files changed

+244
-1
lines changed

6 files changed

+244
-1
lines changed

.doc_gen/metadata/bedrock-runtime_metadata.yaml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@ bedrock-runtime_Hello:
2121
- description:
2222
snippet_files:
2323
- javascriptv3/example_code/bedrock-runtime/hello.js
24+
25+
Python:
26+
versions:
27+
- sdk_version: 3
28+
github: python/example_code/bedrock-runtime
29+
sdkguide:
30+
excerpts:
31+
- description: Send a prompt to a model with the InvokeModel operation.
32+
snippet_tags:
33+
- bedrock-runtime.example_code.hello_bedrock_invoke.complete
34+
- description: Send a user message to a model with the Converse operation.
35+
snippet_tags:
36+
- bedrock-runtime.example_code.hello_bedrock_converse.complete
37+
2438
services:
2539
bedrock-runtime: {InvokeModel}
2640

python/example_code/bedrock-runtime/README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ python -m pip install -r requirements.txt
3838
> see [Model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html).
3939
>
4040
<!--custom.prerequisites.end-->
41+
42+
### Get started
43+
44+
- [Hello Amazon Bedrock Runtime](hello/hello_bedrock_runtime_invoke.py#L5) (`InvokeModel`)
45+
4146
### AI21 Labs Jurassic-2
4247

4348
- [Converse](models/ai21_labs_jurassic2/converse.py#L4)
@@ -120,6 +125,13 @@ Mistral AI.
120125

121126
<!--custom.instructions.end-->
122127

128+
#### Hello Amazon Bedrock Runtime
129+
130+
This example shows you how to get started using Amazon Bedrock Runtime.
131+
132+
```
133+
python hello/hello_bedrock_runtime_invoke.py
134+
```
123135

124136

125137
### Tests
@@ -148,4 +160,4 @@ in the `python` folder.
148160

149161
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
150162

151-
SPDX-License-Identifier: Apache-2.0
163+
SPDX-License-Identifier: Apache-2.0
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
5+
# snippet-start:[bedrock-runtime.example_code.hello_bedrock_converse.complete]
6+
7+
"""
8+
Uses the Amazon Bedrock runtime client Converse operation to send a user message to a model.
9+
"""
10+
import logging
11+
import boto3
12+
13+
from botocore.exceptions import ClientError
14+
15+
16+
logging.basicConfig(level=logging.INFO)
17+
logger = logging.getLogger(__name__)
18+
19+
20+
def converse(brt, model_id, user_message):
21+
"""
22+
Uses the Converse operation to send a user message to the supplied model.
23+
param brt: A bedrock runtime boto3 client
24+
param model_id: The model ID for the model that you want to use.
25+
param user message: The user message that you want to send to the model.
26+
27+
:return: The text response from the model.
28+
"""
29+
30+
# Format the request payload using the model's native structure.
31+
conversation = [
32+
{
33+
"role": "user",
34+
"content": [{"text": user_message}],
35+
}
36+
]
37+
38+
try:
39+
# Send the message to the model, using a basic inference configuration.
40+
response = brt.converse(
41+
modelId=model_id,
42+
messages=conversation,
43+
inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
44+
)
45+
46+
# Extract and print the response text.
47+
response_text = response["output"]["message"]["content"][0]["text"]
48+
return response_text
49+
50+
except (ClientError, Exception) as e:
51+
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
52+
raise
53+
54+
55+
def main():
56+
"""Entry point for the example. Uses the AWS SDK for Python (Boto3)
57+
to create an Amazon Bedrock runtime client. Then sends a user message to a model
58+
in the region set in the callers profile and credentials.
59+
"""
60+
61+
# Create an Amazon Bedrock Runtime client.
62+
brt = boto3.client("bedrock-runtime")
63+
64+
# Set the model ID, e.g., Amazon Titan Text G1 - Express.
65+
model_id = "amazon.titan-text-express-v1"
66+
67+
# Define the message for the model.
68+
message = "Describe the purpose of a 'hello world' program in one line."
69+
70+
# Send the message to the model.
71+
response = converse(brt, model_id, message)
72+
73+
print(f"Response: {response}")
74+
75+
logger.info("Done.")
76+
77+
78+
if __name__ == "__main__":
79+
main()
80+
81+
# snippet-end:[bedrock-runtime.example_code.hello_bedrock_converse.complete]
82+
83+
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
5+
# snippet-start:[bedrock-runtime.example_code.hello_bedrock_invoke.complete]
6+
7+
"""
8+
Uses the Amazon Bedrock runtime client InvokeModel operation to send a prompt to a model.
9+
"""
10+
import logging
11+
import json
12+
import boto3
13+
14+
15+
from botocore.exceptions import ClientError
16+
17+
18+
logging.basicConfig(level=logging.INFO)
19+
logger = logging.getLogger(__name__)
20+
21+
22+
def invoke_model(brt, model_id, prompt):
23+
"""
24+
Invokes the specified model with the supplied prompt.
25+
param brt: A bedrock runtime boto3 client
26+
param model_id: The model ID for the model that you want to use.
27+
param prompt: The prompt that you want to send to the model.
28+
29+
:return: The text response from the model.
30+
"""
31+
32+
# Format the request payload using the model's native structure.
33+
native_request = {
34+
"inputText": prompt,
35+
"textGenerationConfig": {
36+
"maxTokenCount": 512,
37+
"temperature": 0.5,
38+
"topP": 0.9
39+
}
40+
}
41+
42+
# Convert the native request to JSON.
43+
request = json.dumps(native_request)
44+
45+
try:
46+
# Invoke the model with the request.
47+
response = brt.invoke_model(modelId=model_id, body=request)
48+
49+
# Decode the response body.
50+
model_response = json.loads(response["body"].read())
51+
52+
# Extract and print the response text.
53+
response_text = model_response["results"][0]["outputText"]
54+
return response_text
55+
56+
except (ClientError, Exception) as e:
57+
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
58+
raise
59+
60+
61+
def main():
62+
"""Entry point for the example. Uses the AWS SDK for Python (Boto3)
63+
to create an Amazon Bedrock runtime client. Then sends a prompt to a model
64+
in the region set in the callers profile and credentials.
65+
"""
66+
67+
# Create an Amazon Bedrock Runtime client.
68+
brt = boto3.client("bedrock-runtime")
69+
70+
# Set the model ID, e.g., Amazon Titan Text G1 - Express.
71+
model_id = "amazon.titan-text-express-v1"
72+
73+
# Define the prompt for the model.
74+
prompt = "Describe the purpose of a 'hello world' program in one line."
75+
76+
# Send the prompt to the model.
77+
response = invoke_model(brt, model_id, prompt)
78+
79+
print(f"Response: {response}")
80+
81+
logger.info("Done.")
82+
83+
84+
if __name__ == "__main__":
85+
main()
86+
87+
# snippet-end:[bedrock-runtime.example_code.hello_bedrock_invoke.complete]
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
import pytest
5+
import subprocess
6+
import sys
7+
8+
files_under_test = [
9+
# Text models
10+
"hello/hello_bedrock_runtime_invoke.py"
11+
]
12+
13+
14+
@pytest.mark.integ
15+
@pytest.mark.parametrize("file", files_under_test)
16+
def test_hello_bedrock(file):
17+
result = subprocess.run(
18+
[sys.executable, file],
19+
capture_output=True,
20+
text=True,
21+
)
22+
assert result.stdout != ""
23+
assert result.returncode == 0
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 pytest
5+
import subprocess
6+
import sys
7+
8+
files_under_test = [
9+
# Text models
10+
"hello/hello_bedrock_runtime_invoke.py",
11+
"hello/hello_bedrock_runtime_converse.py"
12+
]
13+
14+
15+
@pytest.mark.integ
16+
@pytest.mark.parametrize("file", files_under_test)
17+
def test_hello_bedrock(file):
18+
result = subprocess.run(
19+
[sys.executable, file],
20+
capture_output=True,
21+
text=True,
22+
)
23+
assert result.stdout != ""
24+
assert result.returncode == 0

0 commit comments

Comments
 (0)