-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add JavaScript examples for Amazon Nova and Amazon Nova Canvas
- Loading branch information
1 parent
b6e9c0d
commit e161a98
Showing
11 changed files
with
361 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
/tempx/ | ||
/output/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
93 changes: 93 additions & 0 deletions
93
javascriptv3/example_code/bedrock-runtime/models/amazonNovaCanvas/invokeModel.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// snippet-start:[javascript.v3.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration] | ||
|
||
import { | ||
BedrockRuntimeClient, | ||
InvokeModelCommand, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
import { saveImage } from "../../utils/image-creation.js"; | ||
import { fileURLToPath } from "node:url"; | ||
|
||
/** | ||
* This example demonstrates how to use Amazon Nova Canvas to generate images. | ||
* It shows how to: | ||
* - Set up the Amazon Bedrock runtime client | ||
* - Configure the image generation parameters | ||
* - Send a request to generate an image | ||
* - Process the response and handle the generated image | ||
* | ||
* @returns {Promise<string>} Base64-encoded image data | ||
*/ | ||
export const invokeModel = async () => { | ||
// Step 1: Create the Amazon Bedrock runtime client | ||
// Credentials will be automatically loaded from the environment | ||
const client = new BedrockRuntimeClient({ region: "us-east-1" }); | ||
|
||
// Step 2: Specify which model to use | ||
// For the latest available models, see: | ||
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html | ||
const modelId = "amazon.nova-canvas-v1:0"; | ||
|
||
// Step 3: Configure the request payload | ||
// First, set the main parameters: | ||
// - prompt: Text description of the image to generate | ||
// - seed: Random number for reproducible generation (0 to 858,993,459) | ||
const prompt = "A stylized picture of a cute old steampunk robot"; | ||
const seed = Math.floor(Math.random() * 858993460); | ||
|
||
// Then, create the payload using the following structure: | ||
// - taskType: TEXT_IMAGE (specifies text-to-image generation) | ||
// - textToImageParams: Contains the text prompt | ||
// - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.) | ||
// For a list of available request parameters, see: | ||
// https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html | ||
const payload = { | ||
taskType: "TEXT_IMAGE", | ||
textToImageParams: { | ||
text: prompt, | ||
}, | ||
imageGenerationConfig: { | ||
seed, | ||
quality: "standard", | ||
}, | ||
}; | ||
|
||
// Step 4: Send and process the request | ||
// - Embed the payload in a request object | ||
// - Send the request to the model | ||
// - Extract and return the generated image data from the response | ||
try { | ||
const request = { | ||
modelId, | ||
body: JSON.stringify(payload), | ||
}; | ||
const response = await client.send(new InvokeModelCommand(request)); | ||
|
||
const decodedResponseBody = new TextDecoder().decode(response.body); | ||
// The response includes an array of base64-encoded PNG images | ||
/** @type {{images: string[]}} */ | ||
const responseBody = JSON.parse(decodedResponseBody); | ||
return responseBody.images[0]; // Base64-encoded image data | ||
} catch (error) { | ||
console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`); | ||
throw error; | ||
} | ||
}; | ||
|
||
// If run directly, execute the example and save the generated image | ||
if (process.argv[1] === fileURLToPath(import.meta.url)) { | ||
console.log("Generating image. This may take a few seconds..."); | ||
invokeModel() | ||
.then(async (imageData) => { | ||
const imagePath = await saveImage(imageData, "nova-canvas"); | ||
// Example path: javascriptv3/example_code/bedrock-runtime/output/nova-canvas/image-01.png | ||
console.log(`Image saved to: ${imagePath}`); | ||
}) | ||
.catch((error) => { | ||
console.error("Execution failed:", error); | ||
process.exitCode = 1; | ||
}); | ||
} | ||
// snippet-end:[javascript.v3.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration] |
68 changes: 68 additions & 0 deletions
68
javascriptv3/example_code/bedrock-runtime/models/amazonNovaText/converse.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// snippet-start:[javascript.v3.bedrock-runtime.Converse_AmazonNovaText] | ||
// This example demonstrates how to use the Amazon Nova foundation models to generate text. | ||
// It shows how to: | ||
// - Set up the Amazon Bedrock runtime client | ||
// - Create a message | ||
// - Configure and send a request | ||
// - Process the response | ||
|
||
import { | ||
BedrockRuntimeClient, | ||
ConversationRole, | ||
ConverseCommand, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
|
||
// Step 1: Create the Amazon Bedrock runtime client | ||
// Credentials will be automatically loaded from the environment | ||
const client = new BedrockRuntimeClient({ region: "us-east-1" }); | ||
|
||
// Step 2: Specify which model to use: | ||
// Available Amazon Nova models and their characteristics: | ||
// - Amazon Nova Micro: Text-only model optimized for lowest latency and cost | ||
// - Amazon Nova Lite: Fast, low-cost multimodal model for image, video, and text | ||
// - Amazon Nova Pro: Advanced multimodal model balancing accuracy, speed, and cost | ||
// | ||
// For the most current model IDs, see: | ||
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html | ||
const modelId = "amazon.nova-lite-v1:0"; | ||
|
||
// Step 3: Create the message | ||
// The message includes the text prompt and specifies that it comes from the user | ||
const inputText = | ||
"Describe the purpose of a 'hello world' program in one line."; | ||
const message = { | ||
content: [{ text: inputText }], | ||
role: ConversationRole.USER, | ||
}; | ||
|
||
// Step 4: Configure the request | ||
// Optional parameters to control the model's response: | ||
// - maxTokens: maximum number of tokens to generate | ||
// - temperature: randomness (max: 1.0, default: 0.7) | ||
// OR | ||
// - topP: diversity of word choice (max: 1.0, default: 0.9) | ||
// Note: Use either temperature OR topP, but not both | ||
const request = { | ||
modelId, | ||
messages: [message], | ||
inferenceConfig: { | ||
maxTokens: 500, // The maximum response length | ||
temperature: 0.5, // Using temperature for randomness control | ||
//topP: 0.9, // Alternative: use topP instead of temperature | ||
}, | ||
}; | ||
|
||
// Step 5: Send and process the request | ||
// - Send the request to the model | ||
// - Extract and return the generated text from the response | ||
try { | ||
const response = await client.send(new ConverseCommand(request)); | ||
console.log(response.output.message.content[0].text); | ||
} catch (error) { | ||
console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`); | ||
throw error; | ||
} | ||
// snippet-end:[javascript.v3.bedrock-runtime.Converse_AmazonNovaText] |
75 changes: 75 additions & 0 deletions
75
javascriptv3/example_code/bedrock-runtime/models/amazonNovaText/converseStream.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// snippet-start:[javascript.v3.bedrock-runtime.ConverseStream_AmazonNovaText] | ||
// This example demonstrates how to use the Amazon Nova foundation models | ||
// to generate streaming text responses. | ||
// It shows how to: | ||
// - Set up the Amazon Bedrock runtime client | ||
// - Create a message | ||
// - Configure a streaming request | ||
// - Process the streaming response | ||
|
||
import { | ||
BedrockRuntimeClient, | ||
ConversationRole, | ||
ConverseStreamCommand, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
|
||
// Step 1: Create the Amazon Bedrock runtime client | ||
// Credentials will be automatically loaded from the environment | ||
const client = new BedrockRuntimeClient({ region: "us-east-1" }); | ||
|
||
// Step 2: Specify which model to use | ||
// Available Amazon Nova models and their characteristics: | ||
// - Amazon Nova Micro: Text-only model optimized for lowest latency and cost | ||
// - Amazon Nova Lite: Fast, low-cost multimodal model for image, video, and text | ||
// - Amazon Nova Pro: Advanced multimodal model balancing accuracy, speed, and cost | ||
// | ||
// For the most current model IDs, see: | ||
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html | ||
const modelId = "amazon.nova-lite-v1:0"; | ||
|
||
// Step 3: Create the message | ||
// The message includes the text prompt and specifies that it comes from the user | ||
const inputText = | ||
"Describe the purpose of a 'hello world' program in one paragraph"; | ||
const message = { | ||
content: [{ text: inputText }], | ||
role: ConversationRole.USER, | ||
}; | ||
|
||
// Step 4: Configure the streaming request | ||
// Optional parameters to control the model's response: | ||
// - maxTokens: maximum number of tokens to generate | ||
// - temperature: randomness (max: 1.0, default: 0.7) | ||
// OR | ||
// - topP: diversity of word choice (max: 1.0, default: 0.9) | ||
// Note: Use either temperature OR topP, but not both | ||
const request = { | ||
modelId, | ||
messages: [message], | ||
inferenceConfig: { | ||
maxTokens: 500, // The maximum response length | ||
temperature: 0.5, // Using temperature for randomness control | ||
//topP: 0.9, // Alternative: use topP instead of temperature | ||
}, | ||
}; | ||
|
||
// Step 5: Send and process the streaming request | ||
// - Send the request to the model | ||
// - Process each chunk of the streaming response | ||
try { | ||
const response = await client.send(new ConverseStreamCommand(request)); | ||
|
||
for await (const chunk of response.stream) { | ||
if (chunk.contentBlockDelta) { | ||
// Print each text chunk as it arrives | ||
process.stdout.write(chunk.contentBlockDelta.delta?.text || ""); | ||
} | ||
} | ||
} catch (error) { | ||
console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`); | ||
process.exitCode = 1; | ||
} | ||
// snippet-end:[javascript.v3.bedrock-runtime.ConverseStream_AmazonNovaText] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
javascriptv3/example_code/bedrock-runtime/tests/image_generation.integration.test.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
import { describe, it } from "vitest"; | ||
import { invokeModel } from "../models/amazonNovaCanvas/invokeModel.js"; | ||
import { expectToBeANonEmptyString } from "./test_tools.js"; | ||
|
||
describe("Invoking Amazon Nova Canvas", () => { | ||
it("should return a response", async () => { | ||
const response = await invokeModel(); | ||
expectToBeANonEmptyString(response); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.