Skip to content

Python & .NET: Amazon Nova Text & Image Generation #7250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 20, 2025
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
48 changes: 48 additions & 0 deletions .doc_gen/metadata/bedrock-runtime_metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,22 @@ bedrock-runtime_Converse_AmazonNovaText:
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
snippet_tags:
- bedrock-runtime.java2.Converse_AmazonNovaText
.NET:
versions:
- sdk_version: 3
github: dotnetv3/Bedrock-runtime
excerpts:
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
snippet_tags:
- BedrockRuntime.dotnetv3.Converse_AmazonNovaText
Python:
versions:
- sdk_version: 3
github: python/example_code/bedrock-runtime
excerpts:
- description: Send a text message to Amazon Nova, using Bedrock's Converse API.
snippet_tags:
- python.example_code.bedrock-runtime.Converse_AmazonNovaText
services:
bedrock-runtime: {Converse}

Expand Down Expand Up @@ -349,6 +365,22 @@ 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:
- bedrock-runtime.java2.ConverseStream_AmazonNovaText
.NET:
versions:
- sdk_version: 3
github: dotnetv3/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:
- BedrockRuntime.dotnetv3.ConverseStream_AmazonNovaText
Python:
versions:
- sdk_version: 3
github: python/example_code/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:
- python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText
services:
bedrock-runtime: {ConverseStream}

Expand Down Expand Up @@ -1137,6 +1169,22 @@ bedrock-runtime_InvokeModel_AmazonNovaImageGeneration:
- description: Create an image with Amazon Nova Canvas.
snippet_tags:
- bedrock-runtime.java2.InvokeModel_AmazonNovaImageGeneration
.NET:
versions:
- sdk_version: 3
github: dotnetv3/Bedrock-runtime
excerpts:
- description: Create an image with Amazon Nova Canvas.
snippet_tags:
- BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration
Python:
versions:
- sdk_version: 3
github: python/example_code/bedrock-runtime
excerpts:
- description: Create an image with the Amazon Nova Canvas.
snippet_tags:
- python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration
services:
bedrock-runtime: {InvokeModel}

Expand Down
1 change: 1 addition & 0 deletions dotnetv3/Bedrock-runtime/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/.vs/
/Tools/
**/generated-images/
31 changes: 31 additions & 0 deletions dotnetv3/Bedrock-runtime/BedrockRuntimeExamples.sln
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvokeModelWithResponseStre
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvokeModelWithResponseStream", "Models\AnthropicClaude\InvokeModelWithResponseStream\InvokeModelWithResponseStream.csproj", "{C75F2BBE-7C84-4B01-9836-7279DAE41499}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AmazonNovaText", "AmazonNovaText", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AmazonNova", "AmazonNova", "{3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Converse", "Models\AmazonNova\AmazonNovaText\Converse\Converse.csproj", "{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConverseStream", "Models\AmazonNova\AmazonNovaText\ConverseStream\ConverseStream.csproj", "{E144492A-337A-0755-EAB4-DA083C3A2DDB}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AmazonNovaCanvas", "AmazonNovaCanvas", "{4D3E429C-CCAE-42DE-A062-4717E71D8403}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InvokeModel", "Models\AmazonNova\AmazonNovaCanvas\InvokeModel\InvokeModel.csproj", "{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -200,6 +212,18 @@ Global
{C75F2BBE-7C84-4B01-9836-7279DAE41499}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C75F2BBE-7C84-4B01-9836-7279DAE41499}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C75F2BBE-7C84-4B01-9836-7279DAE41499}.Release|Any CPU.Build.0 = Release|Any CPU
{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Release|Any CPU.Build.0 = Release|Any CPU
{E144492A-337A-0755-EAB4-DA083C3A2DDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E144492A-337A-0755-EAB4-DA083C3A2DDB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E144492A-337A-0755-EAB4-DA083C3A2DDB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E144492A-337A-0755-EAB4-DA083C3A2DDB}.Release|Any CPU.Build.0 = Release|Any CPU
{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -227,6 +251,7 @@ Global
{3D6441FC-0FE8-4D0C-910D-3D9310599C71} = {3F96ECB4-1644-43E8-8643-2CDCF9E679F1}
{D1B0719F-4F84-4DBC-BCAD-E856FB3193D7} = {8BAC2322-AD3C-484A-B51D-8263BC4E6646}
{1E62D4FB-CC59-4F1E-BB22-574CEC08C94B} = {BBB79D3E-5DF2-4FF6-B467-52D0EEB91C4B}
{B753CEB9-EA53-4AE1-997E-B7D54A299D58} = {65504C76-7E32-4A12-A42E-BCDA4FE79BC1}
{2A6989CB-B273-4841-BD3E-7B1BBA4DD25F} = {EF45C0B9-ED76-4B7A-A0A7-F102E979B71C}
{BCC66C37-4980-484F-819D-066D2FF2669C} = {EF45C0B9-ED76-4B7A-A0A7-F102E979B71C}
{52CDA3F4-F090-4224-978A-5F42388DCF92} = {3F96ECB4-1644-43E8-8643-2CDCF9E679F1}
Expand All @@ -235,6 +260,12 @@ Global
{4B5A00D6-B9F1-449F-A9D2-80E860D6BD75} = {65504C76-7E32-4A12-A42E-BCDA4FE79BC1}
{EFC7D088-EF45-464B-97CD-0BBA486B224A} = {BBB79D3E-5DF2-4FF6-B467-52D0EEB91C4B}
{C75F2BBE-7C84-4B01-9836-7279DAE41499} = {8BAC2322-AD3C-484A-B51D-8263BC4E6646}
{02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6}
{3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6} = {41B69207-8F29-41BC-9114-78EE740485C8}
{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{E144492A-337A-0755-EAB4-DA083C3A2DDB} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{4D3E429C-CCAE-42DE-A062-4717E71D8403} = {3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6}
{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D} = {4D3E429C-CCAE-42DE-A062-4717E71D8403}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E48A5088-1BBB-4A8B-9AB2-CC5CE0482466}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AWSSDK.BedrockRuntime" Version="3.7.403.14" />
<PackageReference Include="AWSSDK.Core" Version="3.7.400.26" />
<PackageReference Include="AWSSDK.BedrockRuntime" Version="3.7.412.14" />
<PackageReference Include="AWSSDK.Core" Version="3.7.402.2" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AWSSDK.BedrockRuntime" Version="3.7.403.14" />
<PackageReference Include="AWSSDK.Core" Version="3.7.400.26" />
<PackageReference Include="AWSSDK.BedrockRuntime" Version="3.7.412.14" />
<PackageReference Include="AWSSDK.Core" Version="3.7.402.2" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

// snippet-start:[BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration]
// Use the native inference API to create an image with Amazon Nova Canvas.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID.
var modelId = "amazon.nova-canvas-v1:0";

// Define the image generation prompt for the model.
var prompt = "A stylized picture of a cute old steampunk robot.";

// Create a random seed between 0 and 858,993,459
int seed = new Random().Next(0, 858993460);

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
taskType = "TEXT_IMAGE",
textToImageParams = new
{
text = prompt
},
imageGenerationConfig = new
{
seed,
quality = "standard",
width = 512,
height = 512,
numberOfImages = 1
}
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
ModelId = modelId,
Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
ContentType = "application/json"
};

try
{
// Send the request to the Bedrock Runtime and wait for the response.
var response = await client.InvokeModelAsync(request);

// Decode the response body.
var modelResponse = await JsonNode.ParseAsync(response.Body);

// Extract the image data.
var base64Image = modelResponse["images"]?[0].ToString() ?? "";

// Save the image in a local folder
string savedPath = AmazonNovaCanvas.InvokeModel.SaveBase64Image(base64Image);
Console.WriteLine($"Image saved to: {savedPath}");
}
catch (AmazonBedrockRuntimeException e)
{
Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
throw;
}

// snippet-end:[BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration]

// Create a partial class to make the top-level script testable.
namespace AmazonNovaCanvas
{
public partial class InvokeModel
{
public static string SaveBase64Image(string base64String, string outputFolderName = "generated-images")
{
// Get the directory where the script is located
string scriptDirectory = AppDomain.CurrentDomain.BaseDirectory;

// Navigate to the script's folder
if (scriptDirectory.Contains("bin"))
{
scriptDirectory = Directory.GetParent(scriptDirectory)?.Parent?.Parent?.Parent?.FullName
?? throw new DirectoryNotFoundException("Could not find script directory");
}

// Combine script directory with output folder
string outputPath = Path.Combine(scriptDirectory, outputFolderName);

// Create directory if it doesn't exist
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}

// Remove base64 header if present (e.g., "data:image/jpeg;base64,")
string base64Data = base64String;
if (base64String.Contains(","))
{
base64Data = base64String.Split(',')[1];
}

// Convert base64 to bytes
byte[] imageBytes = Convert.FromBase64String(base64Data);

// Find the next available number
int fileNumber = 1;
string filePath;
do
{
string paddedNumber = fileNumber.ToString("D2"); // Pads with leading zero
filePath = Path.Combine(outputPath, $"image_{paddedNumber}.jpg");
fileNumber++;
} while (File.Exists(filePath));

// Save the image
File.WriteAllBytes(filePath, imageBytes);

return filePath;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>AmazonNovaCanvas.$(MSBuildProjectName)</AssemblyName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AWSSDK.BedrockRuntime" Version="3.7.412.14" />
<PackageReference Include="AWSSDK.Core" Version="3.7.402.2" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

// snippet-start:[BedrockRuntime.dotnetv3.Converse_AmazonNovaText]
// Use the Converse API to send a text message to Amazon Nova.

using System;
using System.Collections.Generic;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Amazon Nova Lite.
var modelId = "amazon.nova-lite-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseRequest
{
ModelId = modelId,
Messages = new List<Message>
{
new Message
{
Role = ConversationRole.User,
Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
}
},
InferenceConfig = new InferenceConfiguration()
{
MaxTokens = 512,
Temperature = 0.5F,
TopP = 0.9F
}
};

try
{
// Send the request to the Bedrock Runtime and wait for the result.
var response = await client.ConverseAsync(request);

// Extract and print the response text.
string responseText = response?.Output?.Message?.Content?[0]?.Text ?? "";
Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
throw;
}

// snippet-end:[BedrockRuntime.dotnetv3.Converse_AmazonNovaText]

// Create a partial class to make the top-level script testable.
namespace AmazonNovaText { public partial class Converse { } }
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>AmazonNovaText.$(MSBuildProjectName)</AssemblyName>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AWSSDK.BedrockRuntime" Version="3.7.412.14" />
<PackageReference Include="AWSSDK.Core" Version="3.7.402.2" />
</ItemGroup>
</Project>
Loading