Skip to content

Commit 1d50ab0

Browse files
DennisTraubscmacdon
authored andcommitted
Add Python examples for Amazon Nova and Nova Canvas
1 parent 7b6650a commit 1d50ab0

File tree

8 files changed

+197
-32
lines changed

8 files changed

+197
-32
lines changed

.doc_gen/metadata/bedrock-runtime_metadata.yaml

Lines changed: 24 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
- BedrockRuntime.dotnetv3.Converse_AmazonNovaText
111+
Python:
112+
versions:
113+
- sdk_version: 3
114+
github: python/example_code/bedrock-runtime
115+
excerpts:
116+
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
117+
snippet_tags:
118+
- python.example_code.bedrock-runtime.Converse_AmazonNovaText
111119
services:
112120
bedrock-runtime: {Converse}
113121

@@ -365,6 +373,14 @@ bedrock-runtime_ConverseStream_AmazonNovaText:
365373
- description: Send a text message to Amazon Nova, using Bedrock's Converse API and process the response stream in real-time.
366374
snippet_tags:
367375
- BedrockRuntime.dotnetv3.ConverseStream_AmazonNovaText
376+
Python:
377+
versions:
378+
- sdk_version: 3
379+
github: python/example_code/bedrock-runtime
380+
excerpts:
381+
- description: Send a text message to Amazon Nova, using Bedrock's Converse API and process the response stream in real-time.
382+
snippet_tags:
383+
- python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText
368384
services:
369385
bedrock-runtime: {ConverseStream}
370386

@@ -1161,6 +1177,14 @@ bedrock-runtime_InvokeModel_AmazonNovaImageGeneration:
11611177
- description: Create an image with Amazon Nova Canvas.
11621178
snippet_tags:
11631179
- BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration
1180+
Python:
1181+
versions:
1182+
- sdk_version: 3
1183+
github: python/example_code/bedrock-runtime
1184+
excerpts:
1185+
- description: Create an image with the Amazon Nova Canvas.
1186+
snippet_tags:
1187+
- python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration
11641188
services:
11651189
bedrock-runtime: {InvokeModel}
11661190

python/example_code/bedrock-runtime/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,15 @@ python -m pip install -r requirements.txt
4848
- [Converse](models/ai21_labs_jurassic2/converse.py#L4)
4949
- [InvokeModel](models/ai21_labs_jurassic2/invoke_model.py#L4)
5050

51+
### Amazon Nova
52+
53+
- [Converse](models/amazon_nova/amazon_nova_text/converse.py#L4)
54+
- [ConverseStream](models/amazon_nova/amazon_nova_text/converse_stream.py#L4)
55+
56+
### Amazon Nova Canvas
57+
58+
- [InvokeModel](models/amazon_nova/amazon_nova_canvas/invoke_model.py#L4)
59+
5160
### Amazon Titan Image Generator
5261

5362
- [InvokeModel](models/amazon_titan_image_generator/invoke_model.py#L4)
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
# snippet-start:[python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration]
5+
# Use the native inference API to create an image with Amazon Nova Canvas
6+
7+
import base64
8+
import json
9+
import os
10+
import random
11+
12+
import boto3
13+
14+
# Create a Bedrock Runtime client in the AWS Region of your choice.
15+
client = boto3.client("bedrock-runtime", region_name="us-east-1")
16+
17+
# Set the model ID.
18+
model_id = "amazon.nova-canvas-v1:0"
19+
20+
# Define the image generation prompt for the model.
21+
prompt = "A stylized picture of a cute old steampunk robot."
22+
23+
# Generate a random seed between 0 and 858,993,459
24+
seed = random.randint(0, 858993460)
25+
26+
# Format the request payload using the model's native structure.
27+
native_request = {
28+
"taskType": "TEXT_IMAGE",
29+
"textToImageParams": {"text": prompt},
30+
"imageGenerationConfig": {
31+
"seed": seed,
32+
"quality": "standard",
33+
"height": 512,
34+
"width": 512,
35+
"numberOfImages": 1,
36+
},
37+
}
38+
39+
# Convert the native request to JSON.
40+
request = json.dumps(native_request)
41+
42+
# Invoke the model with the request.
43+
response = client.invoke_model(modelId=model_id, body=request)
44+
45+
# Decode the response body.
46+
model_response = json.loads(response["body"].read())
47+
48+
# Extract the image data.
49+
base64_image_data = model_response["images"][0]
50+
51+
# Save the generated image to a local folder.
52+
i, output_dir = 1, "output"
53+
if not os.path.exists(output_dir):
54+
os.makedirs(output_dir)
55+
while os.path.exists(os.path.join(output_dir, f"nova_canvas_{i}.png")):
56+
i += 1
57+
58+
image_data = base64.b64decode(base64_image_data)
59+
60+
image_path = os.path.join(output_dir, f"nova_canvas_{i}.png")
61+
with open(image_path, "wb") as file:
62+
file.write(image_data)
63+
64+
print(f"The generated image has been saved to {image_path}")
65+
66+
# snippet-end:[python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration]
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
# snippet-start:[python.example_code.bedrock-runtime.Converse_AmazonNovaText]
5+
# Use the Conversation API to send a text message to Amazon Nova.
6+
7+
import boto3
8+
from botocore.exceptions import ClientError
9+
10+
# Create a Bedrock Runtime client in the AWS Region you want to use.
11+
client = boto3.client("bedrock-runtime", region_name="us-east-1")
12+
13+
# Set the model ID, e.g., Amazon Nova Lite.
14+
model_id = "amazon.nova-lite-v1:0"
15+
16+
# Start a conversation with the user message.
17+
user_message = "Describe the purpose of a 'hello world' program in one line."
18+
conversation = [
19+
{
20+
"role": "user",
21+
"content": [{"text": user_message}],
22+
}
23+
]
24+
25+
try:
26+
# Send the message to the model, using a basic inference configuration.
27+
response = client.converse(
28+
modelId=model_id,
29+
messages=conversation,
30+
inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
31+
)
32+
33+
# Extract and print the response text.
34+
response_text = response["output"]["message"]["content"][0]["text"]
35+
print(response_text)
36+
37+
except (ClientError, Exception) as e:
38+
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
39+
exit(1)
40+
41+
# snippet-end:[python.example_code.bedrock-runtime.Converse_AmazonNovaText]
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
# snippet-start:[python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText]
5+
# Use the Conversation API to send a text message to Amazon Nova Text
6+
# and print the response stream.
7+
8+
import boto3
9+
from botocore.exceptions import ClientError
10+
11+
# Create a Bedrock Runtime client in the AWS Region you want to use.
12+
client = boto3.client("bedrock-runtime", region_name="us-east-1")
13+
14+
# Set the model ID, e.g., Amazon Nova Lite.
15+
model_id = "amazon.nova-lite-v1:0"
16+
17+
# Start a conversation with the user message.
18+
user_message = "Describe the purpose of a 'hello world' program in one line."
19+
conversation = [
20+
{
21+
"role": "user",
22+
"content": [{"text": user_message}],
23+
}
24+
]
25+
26+
try:
27+
# Send the message to the model, using a basic inference configuration.
28+
streaming_response = client.converse_stream(
29+
modelId=model_id,
30+
messages=conversation,
31+
inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
32+
)
33+
34+
# Extract and print the streamed response text in real-time.
35+
for chunk in streaming_response["stream"]:
36+
if "contentBlockDelta" in chunk:
37+
text = chunk["contentBlockDelta"]["delta"]["text"]
38+
print(text, end="")
39+
40+
except (ClientError, Exception) as e:
41+
print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
42+
exit(1)
43+
44+
# snippet-end:[python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText]
Lines changed: 7 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,12 @@
1-
beautifulsoup4==4.12.3
2-
boto3==1.35.28
3-
botocore==1.35.28
4-
certifi==2024.8.30
5-
charset-normalizer==3.3.2
1+
boto3==1.36.22
2+
botocore==1.36.22
63
colorama==0.4.6
7-
contourpy==1.3.0
8-
cycler==0.12.1
9-
fonttools==4.54.1
10-
geojson==3.1.0
11-
idna==3.10
124
iniconfig==2.0.0
135
jmespath==1.0.1
14-
kiwisolver==1.4.7
15-
lxml==5.3.0
16-
matplotlib==3.9.2
17-
numpy==2.1.1
18-
packaging==24.1
19-
pandas==2.2.3
20-
pillow==10.4.0
21-
pip-review==1.3.0
6+
packaging==24.2
227
pluggy==1.5.0
23-
pyparsing==3.1.4
24-
pytest==8.3.3
25-
pytest-asyncio==0.24.0
8+
pytest==8.3.4
269
python-dateutil==2.9.0.post0
27-
pytz==2024.2
28-
requests==2.32.3
29-
s3transfer==0.10.2
30-
six==1.16.0
31-
soupsieve==2.6
32-
tzdata==2024.2
33-
ujson==5.10.0
34-
urllib3==2.2.3
35-
xarray==2024.9.0
10+
s3transfer==0.11.2
11+
six==1.17.0
12+
urllib3==2.3.0

python/example_code/bedrock-runtime/test/test_converse.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: Apache-2.0
33

4-
import pytest
54
import subprocess
65
import sys
76

7+
import pytest
8+
89
files_under_test = [
910
"models/ai21_labs_jurassic2/converse.py",
11+
"models/amazon_nova/amazon_nova_text/converse.py",
1012
"models/amazon_titan_text/converse.py",
1113
"models/anthropic_claude/converse.py",
1214
"models/cohere_command/converse.py",

python/example_code/bedrock-runtime/test/test_invoke_model.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
# SPDX-License-Identifier: Apache-2.0
33

4-
import pytest
54
import subprocess
65
import sys
76

7+
import pytest
8+
89
files_under_test = [
910
# Text models
1011
"models/ai21_labs_jurassic2/invoke_model.py",
12+
"models/amazon_nova/amazon_nova_canvas/invoke_model.py",
1113
"models/amazon_titan_text/invoke_model.py",
1214
"models/anthropic_claude/invoke_model.py",
1315
"models/cohere_command/command_invoke_model.py",

0 commit comments

Comments
 (0)