├── .gitignore ├── image ├── output │ ├── 20231025125933694-Sri-lanka-tea-planta.png │ ├── 20240312102950597-Robot-in-wonderland.png │ ├── 20240312103834558-A-lighthouse-on-a-cl.png │ ├── 20240312105056735-red-backpack-on-a-ta.png │ ├── 20231025063023999-a-beautiful-mountain-landscape.png │ ├── 20231025125833627-a-beautiful-mountain-landscape.png │ └── 20240312104045885-a-beautiful-mountain-landscape.png ├── stable-diffusion-simple.mjs ├── amazon-titan-simple.mjs └── stable-diffusion-advanced.mjs ├── package.json ├── LICENSE ├── README.MD ├── list-foundation-models.mjs ├── text ├── claude.mjs ├── mistral.mjs ├── llama.mjs ├── command.mjs ├── jurassic.mjs ├── claude-3.mjs └── command-r.mjs └── embedding ├── titan.mjs └── cohere.mjs /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | .DS_STORE -------------------------------------------------------------------------------- /image/output/20231025125933694-Sri-lanka-tea-planta.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20231025125933694-Sri-lanka-tea-planta.png -------------------------------------------------------------------------------- /image/output/20240312102950597-Robot-in-wonderland.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20240312102950597-Robot-in-wonderland.png -------------------------------------------------------------------------------- /image/output/20240312103834558-A-lighthouse-on-a-cl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20240312103834558-A-lighthouse-on-a-cl.png -------------------------------------------------------------------------------- /image/output/20240312105056735-red-backpack-on-a-ta.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20240312105056735-red-backpack-on-a-ta.png -------------------------------------------------------------------------------- /image/output/20231025063023999-a-beautiful-mountain-landscape.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20231025063023999-a-beautiful-mountain-landscape.png -------------------------------------------------------------------------------- /image/output/20231025125833627-a-beautiful-mountain-landscape.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20231025125833627-a-beautiful-mountain-landscape.png -------------------------------------------------------------------------------- /image/output/20240312104045885-a-beautiful-mountain-landscape.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YAV-AI/amazon-bedrock-node-js-samples/HEAD/image/output/20240312104045885-a-beautiful-mountain-landscape.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "amazon-bedrock-node-js-samples", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "list-foundation-models.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/YAV-AI/amazon-bedrock-node-js-samples.git" 12 | }, 13 | "author": "YAV.AI", 14 | "license": "MIT", 15 | "bugs": { 16 | "url": "https://github.com/YAV-AI/amazon-bedrock-node-js-samples/issues" 17 | }, 18 | "homepage": "https://github.com/YAV-AI/amazon-bedrock-node-js-samples#readme", 19 | "dependencies": { 20 | "@aws-sdk/client-bedrock": "^3.435.0", 21 | "@aws-sdk/client-bedrock-runtime": "^3.435.0" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 YAV.AI 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # Amazon Bedrock Node.js Samples 2 | 3 | This repository contains Node.js examples to get started with the Amazon Bedrock service. 4 | 5 | ## Installation 6 | 7 | ```bash 8 | yarn 9 | ``` 10 | 11 | or 12 | 13 | ```bash 14 | npm install 15 | ``` 16 | 17 | ## Configuration 18 | 19 | Ensure you have properly configured your AWS credentials and region to use the AWS SDK for JavaScript. You can do this using various methods, such as: 20 | 21 | ### AWS CLI: 22 | 23 | Use the `aws configure` command to set up your AWS credentials. 24 | 25 | ### Setting Credentials in Node.js: 26 | 27 | https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html 28 | 29 | ### IAM Roles: 30 | 31 | If your application is running on an AWS resource with an associated IAM role, it will inherit permissions and credentials from that role. 32 | 33 | ## Run an example 34 | 35 | ```bash 36 | node text/claude.mjs 37 | ``` 38 | 39 | ```bash 40 | node image/stable-diffusion-simple.mjs 41 | ``` 42 | 43 | ## Further reading 44 | 45 | https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock/ 46 | https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/ 47 | -------------------------------------------------------------------------------- /list-foundation-models.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockClient, 3 | ListFoundationModelsCommand, 4 | } from "@aws-sdk/client-bedrock"; 5 | 6 | async function listFoundationModels() { 7 | // Create a BedrockClient 8 | const client = new BedrockClient({ region: "us-east-1" }); // Replace 'us-east-1' with your desired region 9 | 10 | try { 11 | // Create a ListFoundationModelsCommand 12 | const command = new ListFoundationModelsCommand({}); 13 | 14 | // Execute the command to list foundational models 15 | const response = await client.send(command); 16 | 17 | // Access the list of foundational models from the response 18 | const foundationalModels = response.modelSummaries; 19 | 20 | // Process and use the foundational models as needed 21 | foundationalModels.forEach((model) => { 22 | console.log(`-----------------------------------------`); 23 | console.log(`- Model Name: ${model.modelName}`); 24 | console.log(`- Model ID: ${model.modelId}`); 25 | console.log(`- Provider Name: ${model.providerName}`); 26 | }); 27 | } catch (error) { 28 | console.error("Error listing foundational models:", error); 29 | } 30 | } 31 | 32 | // Call the function to list foundational models 33 | listFoundationModels(); 34 | -------------------------------------------------------------------------------- /text/claude.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const prompt = `Hi! how are you?`; 10 | 11 | const input = { 12 | // You can change the modelId 13 | // "anthropic.claude-v1" 14 | // "anthropic.claude-instant-v1" 15 | // "anthropic.claude-v2" 16 | // "anthropic.claude-v2:1" 17 | modelId: "anthropic.claude-instant-v1", 18 | contentType: "application/json", 19 | accept: "application/json", 20 | body: JSON.stringify({ 21 | prompt: `\n\nHuman:${prompt}\n\nAssistant:`, 22 | max_tokens_to_sample: 300, 23 | temperature: 0.5, 24 | top_k: 250, 25 | top_p: 1, 26 | }), 27 | }; 28 | 29 | // Create an InvokeModelCommand with the input parameters 30 | const command = new InvokeModelCommand(input); 31 | 32 | // Send the command to invoke the model and await the response 33 | const response = await client.send(command); 34 | console.log("-------------------"); 35 | console.log("---Full Response---"); 36 | console.log("-------------------"); 37 | console.log(response); 38 | 39 | // response.body = Uint8ArrayBlobAdapter(65) [Uint8Array] [ 40 | // 123, 34, 99, 111, 109, 112, 108, 101, 116, 105, 111, 41 | // 110, 34, 58, 34, 32, 73, 39, 109, 32, 119, 101, 42 | // 108, 108, 44, 32, 116, 104, 97, 110, 107, 115, 33, 43 | // 34, 44, 34, 115, 116, 111, 112, 95, 114, 101, 97, 44 | // 115, 111, 110, 34, 58, 34, 115, 116, 111, 112, 95, 45 | // 115, 101, 113, 117, 101, 110, 99, 101, 34, 125 46 | // ] 47 | 48 | // Save the raw response 49 | const rawRes = response.body; 50 | 51 | // Convert it to a JSON String 52 | const jsonString = new TextDecoder().decode(rawRes); 53 | 54 | // Parse the JSON string 55 | const parsedResponse = JSON.parse(jsonString); 56 | 57 | console.log("-------------------------"); 58 | console.log("---Parsed Response Body---"); 59 | console.log("-------------------------"); 60 | // Answers are in parsedResponse.completion 61 | console.log(parsedResponse); 62 | console.log("-------------------------"); 63 | // Output: 64 | // { 65 | // completion: " I'm doing well, thanks for asking!", 66 | // stop_reason: 'stop_sequence' 67 | // } 68 | -------------------------------------------------------------------------------- /embedding/titan.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const input = { 10 | // amazon.titan-embed-text-v2:0 11 | modelId: "amazon.titan-embed-text-v1", 12 | contentType: "application/json", 13 | accept: "application/json", 14 | body: JSON.stringify({ 15 | inputText: "this is where you place your input text", 16 | // !! Only for v2 !! 17 | // 18 | // dimensions: 512, 19 | // normalize: true, 20 | }), 21 | }; 22 | 23 | // Create an InvokeModelCommand with the input parameters 24 | const command = new InvokeModelCommand(input); 25 | 26 | // Send the command to invoke the model and await the response 27 | const response = await client.send(command); 28 | console.log("-------------------"); 29 | console.log("---Full Response---"); 30 | console.log("-------------------"); 31 | console.log(response); 32 | 33 | // response.body 34 | // 35 | // Uint8ArrayBlobAdapter(16954) [Uint8Array] [ 36 | // 123, 34, 101, 109, 98, 101, 100, 100, 105, 110, 103, 34, 37 | // 58, 91, 48, 46, 57, 49, 55, 57, 54, 56, 55, 53, 38 | // 44, 48, 46, 50, 56, 49, 50, 53, 44, 45, 48, 46, 39 | // 53, 51, 53, 49, 53, 54, 50, 53, 44, 48, 46, 54, 40 | // 54, 55, 57, 54, 56, 55, 53, 44, 45, 48, 46, 57, 41 | // 51, 51, 53, 57, 51, 55, 53, 44, 45, 48, 46, 52, 42 | // 49, 48, 49, 53, 54, 50, 53, 44, 45, 48, 46, 48, 43 | // 54, 52, 52, 53, 51, 49, 50, 53, 44, 45, 52, 46, 44 | // 57, 50, 48, 57, 45 | // ... 16854 more items 46 | // ] 47 | 48 | // // Save the raw response 49 | const rawRes = response.body; 50 | 51 | // Convert it to a JSON String 52 | const jsonString = new TextDecoder().decode(rawRes); 53 | 54 | // Parse the JSON string 55 | const parsedResponse = JSON.parse(jsonString); 56 | 57 | console.log("-------------------------"); 58 | console.log("---Parsed Response Body---"); 59 | console.log("-------------------------"); 60 | console.log(parsedResponse); 61 | // { 62 | // embedding: [ 63 | // 0.91796875, 64 | // ... 65 | // ] 66 | // } 67 | 68 | // Answers are in parsedResponse.embedding 69 | console.log("-------------------------"); 70 | console.log("--------Embedding--------"); 71 | console.log("-------------------------"); 72 | console.log(parsedResponse.embedding); 73 | console.log("-------------------------"); 74 | -------------------------------------------------------------------------------- /text/mistral.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const prompt = ` 10 | [INST] What is your favourite condiment? [/INST] 11 | Well, I'm quite partial to a good squeeze of fresh lemon juice. 12 | It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen! 13 | [INST] Do you have mayonnaise recipes? [/INST] 14 | `; 15 | 16 | const input = { 17 | // You can change the modelId 18 | // mistral.mistral-7b-instruct-v0:2 19 | // mistral.mixtral-8x7b-instruct-v0:1 20 | modelId: "mistral.mistral-large-2402-v1:0", 21 | contentType: "application/json", 22 | accept: "application/json", 23 | body: JSON.stringify({ 24 | prompt, 25 | max_tokens: 400, 26 | top_k: 50, 27 | top_p: 0.7, 28 | temperature: 0.7, 29 | }), 30 | }; 31 | 32 | // Create an InvokeModelCommand with the input parameters 33 | const command = new InvokeModelCommand(input); 34 | 35 | // Send the command to invoke the model and await the response 36 | const response = await client.send(command); 37 | console.log("-------------------"); 38 | console.log("---Full Response---"); 39 | console.log("-------------------"); 40 | console.log(response); 41 | 42 | // response.body = Uint8ArrayBlobAdapter(65) [Uint8Array] [ 43 | // 123, 34, 99, 111, 109, 112, 108, 101, 116, 105, 111, 44 | // 110, 34, 58, 34, 32, 73, 39, 109, 32, 119, 101, 45 | // 108, 108, 44, 32, 116, 104, 97, 110, 107, 115, 33, 46 | // 34, 44, 34, 115, 116, 111, 112, 95, 114, 101, 97, 47 | // 115, 111, 110, 34, 58, 34, 115, 116, 111, 112, 95, 48 | // 115, 101, 113, 117, 101, 110, 99, 101, 34, 125 49 | // ] 50 | 51 | // Save the raw response 52 | const rawRes = response.body; 53 | 54 | // Convert it to a JSON String 55 | const jsonString = new TextDecoder().decode(rawRes); 56 | 57 | // Parse the JSON string 58 | const parsedResponse = JSON.parse(jsonString); 59 | 60 | console.log("-------------------------"); 61 | console.log("---Parsed Response Body---"); 62 | console.log("-------------------------"); 63 | // Answers are in parsedResponse.outputs[0].text 64 | console.log(parsedResponse); 65 | console.log("-------------------------"); 66 | // Output: 67 | // { 68 | // outputs: [ 69 | // { 70 | // text: 71 | // "Yes, indeed! Here's a simple recipe for homemade mayonnaise:\n" + 72 | // "\n" + 73 | // "Ingredients:\n" + 74 | // "- 1 egg yolk\n" + 75 | // "- 1 tablespoon of mustard (Dijon is a good choice)\n" + 76 | // "..." 77 | // stop_reason: "stop", 78 | // }, 79 | // ]; 80 | // } 81 | -------------------------------------------------------------------------------- /text/llama.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const prompt = ` 10 | [INST]You are a very intelligent bot with exceptional critical thinking[/INST] 11 | I went to the market and bought 10 apples. 12 | I gave 2 apples to your friend and 2 to the helper. 13 | I then went and bought 5 more apples and ate 1. 14 | How many apples did I remain with? 15 | Let's think step by step 16 | `; 17 | 18 | const input = { 19 | // You can change the modelId 20 | // meta.llama2-70b-chat-v1 21 | // meta.llama3-8b-instruct-v1:0 22 | modelId: "meta.llama3-70b-instruct-v1:0", 23 | contentType: "application/json", 24 | accept: "application/json", 25 | body: JSON.stringify({ 26 | prompt, 27 | max_gen_len: 512, 28 | temperature: 0.5, 29 | top_p: 0.9, 30 | }), 31 | }; 32 | 33 | // Create an InvokeModelCommand with the input parameters 34 | const command = new InvokeModelCommand(input); 35 | 36 | // Send the command to invoke the model and await the response 37 | const response = await client.send(command); 38 | console.log("-------------------"); 39 | console.log("---Full Response---"); 40 | console.log("-------------------"); 41 | console.log(response); 42 | 43 | // response.body = Uint8ArrayBlobAdapter(65) [Uint8Array] [ 44 | // 123, 34, 99, 111, 109, 112, 108, 101, 116, 105, 111, 45 | // 110, 34, 58, 34, 32, 73, 39, 109, 32, 119, 101, 46 | // 108, 108, 44, 32, 116, 104, 97, 110, 107, 115, 33, 47 | // 34, 44, 34, 115, 116, 111, 112, 95, 114, 101, 97, 48 | // 115, 111, 110, 34, 58, 34, 115, 116, 111, 112, 95, 49 | // 115, 101, 113, 117, 101, 110, 99, 101, 34, 125 50 | // ] 51 | 52 | // Save the raw response 53 | const rawRes = response.body; 54 | 55 | // Convert it to a JSON String 56 | const jsonString = new TextDecoder().decode(rawRes); 57 | 58 | // Parse the JSON string 59 | const parsedResponse = JSON.parse(jsonString); 60 | 61 | console.log("-------------------------"); 62 | console.log("---Parsed Response Body---"); 63 | console.log("-------------------------"); 64 | // Answers are in parsedResponse.completion 65 | console.log(parsedResponse); 66 | console.log("-------------------------"); 67 | // Output: 68 | // { 69 | // generation: '\n' + 70 | // 'First, I gave 2 apples to your friend, so I have 10 - 2 = 8 apples left.\n' + 71 | // 'Next, I gave 2 apples to the helper, so I have 8 - 2 = 6 apples left.\n' + 72 | // 'Then, I went and bought 5 more apples, so I have 6 + 5 = 11 apples left.\n' + 73 | // 'Finally, I ate 1 apple, so I have 11 - 1 = 10 apples left.\n' + 74 | // '\n' + 75 | // 'So, I remain with 10 apples.', 76 | // prompt_token_count: 89, 77 | // generation_token_count: 128, 78 | // stop_reason: 'stop' 79 | // } 80 | -------------------------------------------------------------------------------- /text/command.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const input = { 10 | // cohere.command-light-text-v14 11 | modelId: "cohere.command-text-v14", 12 | contentType: "application/json", 13 | accept: "*/*", 14 | body: JSON.stringify({ 15 | prompt: 'Translate the word "Good Morning" to French', 16 | max_tokens: 400, 17 | temperature: 0.75, 18 | p: 0.01, 19 | k: 0, 20 | stop_sequences: [], 21 | return_likelihoods: "NONE", 22 | }), 23 | }; 24 | 25 | // Create an InvokeModelCommand with the input parameters 26 | const command = new InvokeModelCommand(input); 27 | 28 | // Send the command to invoke the model and await the response 29 | const response = await client.send(command); 30 | console.log("-------------------"); 31 | console.log("---Full Response---"); 32 | console.log("-------------------"); 33 | console.log(response); 34 | 35 | // response.body 36 | // 37 | // Uint8ArrayBlobAdapter(250) [Uint8Array] [ 38 | // 123, 34, 103, 101, 110, 101, 114, 97, 116, 105, 111, 110, 39 | // 115, 34, 58, 91, 123, 34, 105, 100, 34, 58, 34, 52, 40 | // 48, 98, 102, 102, 98, 100, 48, 45, 55, 49, 52, 51, 41 | // 45, 52, 52, 53, 51, 45, 57, 49, 54, 100, 45, 97, 42 | // 57, 51, 53, 98, 50, 55, 98, 51, 100, 57, 97, 34, 43 | // 44, 34, 116, 101, 120, 116, 34, 58, 34, 32, 84, 104, 44 | // 101, 32, 97, 110, 115, 119, 101, 114, 32, 105, 115, 32, 45 | // 66, 111, 110, 106, 111, 117, 114, 32, 105, 115, 32, 116, 46 | // 104, 101, 32, 70, 47 | // ... 150 more items 48 | // ] 49 | 50 | // // Save the raw response 51 | const rawRes = response.body; 52 | 53 | // Convert it to a JSON String 54 | const jsonString = new TextDecoder().decode(rawRes); 55 | 56 | // Parse the JSON string 57 | const parsedResponse = JSON.parse(jsonString); 58 | 59 | console.log("-------------------------"); 60 | console.log("---Parsed Response Body---"); 61 | console.log("-------------------------"); 62 | console.log(parsedResponse); 63 | console.log("-------------------------"); 64 | // Output: 65 | // { 66 | // generations: [ 67 | // { 68 | // id: '6e7079d3-fbb4-477d-aa94-b1690f501c09', 69 | // text: ' The answer is Bonjour is the French translation of Good Morning.' 70 | // } 71 | // ], 72 | // id: '64bdce94-6148-4836-bb13-ebbb3df68390', 73 | // prompt: 'Translate the word "Good Morning" to French\n\nBonjour' 74 | // } 75 | 76 | console.log("-------------------------"); 77 | console.log("----Generation Result----"); 78 | console.log("-------------------------"); 79 | // Answers are in parsedResponse.generations[0].data.text 80 | console.log(parsedResponse.generations[0].text); 81 | console.log("-------------------------"); 82 | -------------------------------------------------------------------------------- /text/jurassic.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const input = { 10 | // You can change the modelId 11 | // "ai21.j2-mid-v1" 12 | // "ai21.j2-ultra-v1" 13 | modelId: "ai21.j2-mid-v1", 14 | contentType: "application/json", 15 | accept: "application/json", 16 | body: JSON.stringify({ 17 | prompt: "How do you say Good Morning in French?", 18 | maxTokens: 200, 19 | temperature: 0.7, 20 | topP: 1, 21 | stopSequences: [], 22 | countPenalty: { scale: 0 }, 23 | presencePenalty: { scale: 0 }, 24 | frequencyPenalty: { scale: 0 }, 25 | }), 26 | }; 27 | 28 | // Create an InvokeModelCommand with the input parameters 29 | const command = new InvokeModelCommand(input); 30 | 31 | // Send the command to invoke the model and await the response 32 | const response = await client.send(command); 33 | console.log("-------------------"); 34 | console.log("---Full Response---"); 35 | console.log("-------------------"); 36 | console.log(response); 37 | 38 | // response.body 39 | // 40 | // Uint8ArrayBlobAdapter(1855)[Uint8Array][ 41 | // 123, 34, 105, 100, 34, 58, 49, 50, 51, 52, 44, 34, 42 | // 112, 114, 111, 109, 112, 116, 34, 58, 123, 34, 116, 101, 43 | // 120, 116, 34, 58, 34, 72, 111, 119, 32, 100, 111, 32, 44 | // 121, 111, 117, 32, 115, 97, 121, 32, 71, 111, 111, 100, 45 | // 32, 77, 111, 114, 110, 105, 110, 103, 32, 105, 110, 32, 46 | // 70, 114, 101, 110, 99, 104, 63, 34, 44, 34, 116, 111, 47 | // 107, 101, 110, 115, 34, 58, 91, 123, 34, 103, 101, 110, 48 | // 101, 114, 97, 116, 101, 100, 84, 111, 107, 101, 110, 34, 49 | // 58, 123, 34, 116, 50 | // ... 1755 more items 51 | // ] 52 | 53 | // Save the raw response 54 | const rawRes = response.body; 55 | 56 | // Convert it to a JSON String 57 | const jsonString = new TextDecoder().decode(rawRes); 58 | 59 | // Parse the JSON string 60 | const parsedResponse = JSON.parse(jsonString); 61 | 62 | console.log("-------------------------"); 63 | console.log("---Parsed Response Body---"); 64 | console.log("-------------------------"); 65 | console.log(parsedResponse); 66 | console.log("-------------------------"); 67 | // Output: 68 | // { 69 | // id: 1234, 70 | // prompt: { 71 | // text: 'How do you say Good Morning in French?', 72 | // tokens: [ [Object], [Object], [Object], [Object], [Object], [Object] ] 73 | // }, 74 | // completions: [ { data: [Object], finishReason: [Object] } ] 75 | // } 76 | 77 | console.log("-------------------------"); 78 | console.log("----Completion Result----"); 79 | console.log("-------------------------"); 80 | // Answers are in parsedResponse.completions[0].data.text 81 | console.log(parsedResponse.completions[0].data.text); 82 | console.log("-------------------------"); 83 | -------------------------------------------------------------------------------- /embedding/cohere.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const input = { 10 | // cohere.embed-multilingual-v3 11 | modelId: "cohere.embed-english-v3", 12 | contentType: "application/json", 13 | accept: "*/*", 14 | body: JSON.stringify({ 15 | texts: ["Hello world", "This is a test"], 16 | input_type: "search_document", 17 | }), 18 | }; 19 | 20 | // Create an InvokeModelCommand with the input parameters 21 | const command = new InvokeModelCommand(input); 22 | 23 | // Send the command to invoke the model and await the response 24 | const response = await client.send(command); 25 | console.log("-------------------"); 26 | console.log("---Full Response---"); 27 | console.log("-------------------"); 28 | console.log(response); 29 | 30 | // response.body 31 | // 32 | // Uint8ArrayBlobAdapter(25633) [Uint8Array] [ 33 | // 123, 34, 105, 100, 34, 58, 34, 99, 51, 50, 101, 50, 34 | // 50, 56, 100, 45, 49, 55, 98, 102, 45, 52, 97, 100, 35 | // 101, 45, 56, 98, 51, 102, 45, 48, 100, 99, 98, 99, 36 | // 97, 48, 50, 55, 99, 49, 57, 34, 44, 34, 116, 101, 37 | // 120, 116, 115, 34, 58, 91, 34, 104, 101, 108, 108, 111, 38 | // 32, 119, 111, 114, 108, 100, 34, 44, 34, 116, 104, 105, 39 | // 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 34, 40 | // 93, 44, 34, 101, 109, 98, 101, 100, 100, 105, 110, 103, 41 | // 115, 34, 58, 91, 42 | // ... 25533 more items 43 | // ] 44 | 45 | // Save the raw response 46 | const rawRes = response.body; 47 | 48 | // Convert it to a JSON String 49 | const jsonString = new TextDecoder().decode(rawRes); 50 | 51 | // Parse the JSON string 52 | const parsedResponse = JSON.parse(jsonString); 53 | 54 | console.log("-------------------------"); 55 | console.log("---Parsed Response Body---"); 56 | console.log("-------------------------"); 57 | console.log(parsedResponse); 58 | // { 59 | // id: 'c32e228d-17bf-4ade-8b3f-0dcbca027c19', 60 | // texts: [ 'hello world', 'this is a test' ], 61 | // embeddings: [ 62 | // [ 63 | // -0.029205322, -0.02357483, -0.05987549, -0.05819702, 64 | // -0.03540039, -0.030151367, -0.033294678, 0.054748535, 65 | // ... 924 more items 66 | // ], 67 | // [ 68 | // -0.013885498, 0.009994507, -0.03253174, -0.024993896, -0.0102005005, 69 | // 0.0002374649, 0.015380859, -0.0074310303, -0.0031375885, -0.027282715, 70 | // ... 924 more items 71 | // ] 72 | // ], 73 | // response_type: 'embeddings_floats' 74 | // } 75 | 76 | // Answers are in parsedResponse.embeddings 77 | console.log("-------------------------"); 78 | console.log("--------Embeddings--------"); 79 | console.log("-------------------------"); 80 | console.log(parsedResponse.embeddings); 81 | console.log("-------------------------"); 82 | -------------------------------------------------------------------------------- /text/claude-3.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const question = "Give me 5 random cat names"; 10 | const prompt = ` 11 | Human: You are a Cat name generator. Here are some instructions 12 | 13 | Always respond in JSON with 2 keys 14 | 1. question: typeOf String 15 | 2. answer: typeOf Array 16 | 17 | Question: ${question} 18 | Assistant: 19 | `; 20 | 21 | const input = { 22 | // anthropic.claude-3-sonnet-20240229-v1:0 23 | modelId: "anthropic.claude-3-haiku-20240307-v1:0", 24 | contentType: "application/json", 25 | accept: "application/json", 26 | body: JSON.stringify({ 27 | anthropic_version: "bedrock-2023-05-31", 28 | max_tokens: 1000, 29 | messages: [ 30 | { 31 | role: "user", 32 | content: [ 33 | { 34 | type: "text", 35 | text: prompt, 36 | }, 37 | ], 38 | }, 39 | ], 40 | }), 41 | }; 42 | 43 | // Create an InvokeModelCommand with the input parameters 44 | const command = new InvokeModelCommand(input); 45 | 46 | // Send the command to invoke the model and await the response 47 | const response = await client.send(command); 48 | console.log("-------------------"); 49 | console.log("---Full Response---"); 50 | console.log("-------------------"); 51 | console.log(response); 52 | 53 | // response.body = Uint8ArrayBlobAdapter(65) [Uint8Array] [ 54 | // 123, 34, 105, 100, 34, 58, 34, 109, 115, 103, 95, 48, 55 | // 49, 81, 76, 84, 57, 114, 110, 74, 87, 103, 120, 75, 56 | // 119, 54, 85, 122, 122, 54, 66, 118, 86, 52, 78, 34, 57 | // 44, 34, 116, 121, 112, 101, 34, 58, 34, 109, 101, 115, 58 | // 115, 97, 103, 101, 34, 44, 34, 114, 111, 108, 101, 34, 59 | // 58, 34, 97, 115, 115, 105, 115, 116, 97, 110, 116, 34, 60 | // 44, 34, 99, 111, 110, 116, 101, 110, 116, 34, 58, 91, 61 | // 123, 34, 116, 121, 112, 101, 34, 58, 34, 116, 101, 120, 62 | // 116, 34, 44, 34, 63 | // ... 296 more items 64 | // ] 65 | 66 | // Save the raw response 67 | const rawRes = response.body; 68 | 69 | // Convert it to a JSON String 70 | const jsonString = new TextDecoder().decode(rawRes); 71 | 72 | // Parse the JSON string 73 | const parsedResponse = JSON.parse(jsonString); 74 | 75 | console.log("-------------------------"); 76 | console.log("---Parsed Response Body---"); 77 | console.log("-------------------------"); 78 | // Answers are in parsedResponse.completion 79 | console.log(parsedResponse); 80 | console.log("-------------------------"); 81 | // Output: 82 | // { 83 | // id: 'msg_01QLT9rnJWgxKw6Uzz6BvV4N', 84 | // type: 'message', 85 | // role: 'assistant', 86 | // content: [ 87 | // { 88 | // type: 'text', 89 | // text: '{\n' + 90 | // ' "question": "Give me 5 random cat names",\n' + 91 | // ' "answer": [\n' + 92 | // ' "Whiskers",\n' + 93 | // ' "Luna",\n' + 94 | // ' "Simba",\n' + 95 | // ' "Bella",\n' + 96 | // ' "Max"\n' + 97 | // ' ]\n' + 98 | // '}' 99 | // } 100 | // ], 101 | // model: 'claude-3-haiku-48k-20240307', 102 | // stop_reason: 'end_turn', 103 | // stop_sequence: null, 104 | // usage: { input_tokens: 70, output_tokens: 60 } 105 | // } 106 | -------------------------------------------------------------------------------- /image/stable-diffusion-simple.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | import fs from "fs"; 7 | import path from "path"; 8 | import { fileURLToPath } from "url"; 9 | import { dirname } from "path"; 10 | 11 | // Create a BedrockRuntimeClient with your configuration 12 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 13 | 14 | const prompt = "A lighthouse on a cliff"; 15 | 16 | const input = { 17 | modelId: "stability.stable-diffusion-xl-v1", 18 | contentType: "application/json", 19 | accept: "application/json", 20 | body: JSON.stringify({ 21 | text_prompts: [{ text: prompt, weight: 1 }], 22 | cfg_scale: 10, 23 | // If you want to set a seed, specify the seed value below 24 | // seed: 452345, 25 | steps: 30, 26 | width: 512, 27 | height: 512, 28 | }), 29 | }; 30 | 31 | // Create an InvokeModelCommand with the input parameters 32 | const command = new InvokeModelCommand(input); 33 | 34 | // Send the command to invoke the model and await the response 35 | const response = await client.send(command); 36 | console.log("-------------------"); 37 | console.log("---Full Response---"); 38 | console.log("-------------------"); 39 | console.log(response); 40 | 41 | // response.body = Uint8ArrayBlobAdapter(65) [Uint8Array] [ 42 | // 123, 34, 99, 111, 109, 112, 108, 101, 116, 105, 111, 43 | // 110, 34, 58, 34, 32, 73, 39, 109, 32, 119, 101, 44 | // 108, 108, 44, 32, 116, 104, 97, 110, 107, 115, 33, 45 | // 34, 44, 34, 115, 116, 111, 112, 95, 114, 101, 97, 46 | // 115, 111, 110, 34, 58, 34, 115, 116, 111, 112, 95, 47 | // 115, 101, 113, 117, 101, 110, 99, 101, 34, 125 48 | // ] 49 | 50 | // Save the raw response 51 | const rawRes = response.body; 52 | 53 | // Convert it to a JSON String 54 | const jsonString = new TextDecoder().decode(rawRes); 55 | 56 | // Parse the JSON string 57 | const parsedResponse = JSON.parse(jsonString); 58 | 59 | console.log("-------------------------"); 60 | console.log("---Parsed Response Body---"); 61 | console.log("-------------------------"); 62 | console.log(parsedResponse); 63 | // { 64 | // result: 'success', 65 | // artifacts: [ 66 | // { 67 | // seed: 0, 68 | // base64: 'iVBORw0K .....' 69 | // } 70 | // ] 71 | // } 72 | 73 | // Lets create the image from the base64 data 74 | const base64ImageData = parsedResponse.artifacts[0].base64; 75 | 76 | // Remove the data URI prefix if it exists 77 | const base64Data = base64ImageData.replace(/^data:image\/\w+;base64,/, ""); 78 | 79 | // Create a buffer from the base64 data 80 | const imageBuffer = Buffer.from(base64Data, "base64"); 81 | 82 | // Generate a timestamp (e.g., current date and time) 83 | const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, ""); 84 | 85 | // Trim the prompt text to not exceed 20 characters 86 | const trimmedPrompt = prompt.slice(0, 20); 87 | 88 | // Remove all special characters from the prompt 89 | const promptWithoutSpecialChars = trimmedPrompt.replace(/[^\w\s]/g, ""); 90 | 91 | // Create a prompt slug by replacing spaces with hyphens 92 | const promptSlug = promptWithoutSpecialChars.replace(/\s+/g, "-"); 93 | 94 | // Get the current directory 95 | const currentDir = dirname(fileURLToPath(import.meta.url)); 96 | 97 | // Define the "output" directory 98 | const outputDirectory = path.join(currentDir, "output"); 99 | 100 | // Create the filename 101 | const filename = `${timestamp}-${promptSlug}.png`; 102 | 103 | // Construct the absolute file path 104 | const filePath = path.join(outputDirectory, filename); 105 | 106 | // Save the image buffer to the file 107 | fs.writeFileSync(filePath, imageBuffer); 108 | 109 | console.log("------------------------"); 110 | console.log("-------Image Path-------"); 111 | console.log("------------------------"); 112 | console.log(`Image saved to: ${filePath}`); 113 | -------------------------------------------------------------------------------- /text/command-r.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | // Create a BedrockRuntimeClient with your configuration 7 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 8 | 9 | const prompt = ` 10 | You are an expert in data formatting. For the following csv data, output it as json. 11 | Output the json only. 12 | 13 | \`\`\` 14 | name,age,occupation 15 | Jane Smith,25,Data Scientist 16 | Bob Johnson,42,Software Developer 17 | Emily Davis,37,Product Manager 18 | \`\`\` 19 | `; 20 | 21 | const input = { 22 | // cohere.command-r-plus-v1:0 23 | modelId: "cohere.command-r-v1:0", 24 | contentType: "application/json", 25 | accept: "*/*", 26 | body: JSON.stringify({ 27 | message: prompt, 28 | max_tokens: 400, 29 | temperature: 0.75, 30 | p: 0.01, 31 | k: 0, 32 | stop_sequences: [], 33 | }), 34 | }; 35 | 36 | // Create an InvokeModelCommand with the input parameters 37 | const command = new InvokeModelCommand(input); 38 | 39 | // Send the command to invoke the model and await the response 40 | const response = await client.send(command); 41 | console.log("-------------------"); 42 | console.log("---Full Response---"); 43 | console.log("-------------------"); 44 | console.log(response); 45 | 46 | // response.body 47 | // 48 | // Uint8ArrayBlobAdapter(975) [Uint8Array] [ 49 | // 123, 34, 99, 104, 97, 116, 95, 104, 105, 115, 116, 111, 50 | // 114, 121, 34, 58, 91, 123, 34, 109, 101, 115, 115, 97, 51 | // 103, 101, 34, 58, 34, 92, 110, 89, 111, 117, 32, 97, 52 | // 114, 101, 32, 97, 110, 32, 101, 120, 112, 101, 114, 116, 53 | // 32, 105, 110, 32, 100, 97, 116, 97, 32, 102, 111, 114, 54 | // 109, 97, 116, 116, 105, 110, 103, 46, 32, 70, 111, 114, 55 | // 32, 116, 104, 101, 32, 102, 111, 108, 108, 111, 119, 105, 56 | // 110, 103, 32, 99, 115, 118, 32, 100, 97, 116, 97, 44, 57 | // 32, 111, 117, 116, 58 | // ... 875 more items 59 | // ] 60 | 61 | // // Save the raw response 62 | const rawRes = response.body; 63 | 64 | // Convert it to a JSON String 65 | const jsonString = new TextDecoder().decode(rawRes); 66 | 67 | // Parse the JSON string 68 | const parsedResponse = JSON.parse(jsonString); 69 | 70 | console.log("-------------------------"); 71 | console.log("---Parsed Response Body---"); 72 | console.log("-------------------------"); 73 | console.log(parsedResponse); 74 | console.log("-------------------------"); 75 | // Output: 76 | // { 77 | // chat_history: [ 78 | // { 79 | // message: '\n' + 80 | // 'You are an expert in data formatting. For the following csv data, output it as json.\n' + 81 | // 'Output the json only.\n' + 82 | // '\n' + 83 | // '```\n' + 84 | // 'name,age,occupation\n' + 85 | // 'Jane Smith,25,Data Scientist\n' + 86 | // 'Bob Johnson,42,Software Developer\n' + 87 | // 'Emily Davis,37,Product Manager\n' + 88 | // '```\n', 89 | // role: 'USER' 90 | // }, 91 | // { 92 | // message: '```json\n' + 93 | // '[\n' + 94 | // ' {"name":"Jane Smith","age":25,"occupation":"Data Scientist"},\n' + 95 | // ' {"name":"Bob Johnson","age":42,"occupation":"Software Developer"},\n' + 96 | // ' {"name":"Emily Davis","age":37,"occupation":"Product Manager"}\n' + 97 | // ']\n' + 98 | // '```', 99 | // role: 'CHATBOT' 100 | // } 101 | // ], 102 | // finish_reason: 'COMPLETE', 103 | // generation_id: '57d52911-83cc-4902-967c-d7dc0195e20b', 104 | // response_id: '87ce6c02-4d2f-43c4-b017-608bdef5026e', 105 | // text: '```json\n' + 106 | // '[\n' + 107 | // ' {"name":"Jane Smith","age":25,"occupation":"Data Scientist"},\n' + 108 | // ' {"name":"Bob Johnson","age":42,"occupation":"Software Developer"},\n' + 109 | // ' {"name":"Emily Davis","age":37,"occupation":"Product Manager"}\n' + 110 | // ']\n' + 111 | // '```' 112 | // } 113 | 114 | console.log("-------------------------"); 115 | console.log("----Generation Result----"); 116 | console.log("-------------------------"); 117 | // Answers are in parsedResponse.text 118 | console.log(parsedResponse.text); 119 | console.log("-------------------------"); 120 | -------------------------------------------------------------------------------- /image/amazon-titan-simple.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | import fs from "fs"; 7 | import path from "path"; 8 | import { fileURLToPath } from "url"; 9 | import { dirname } from "path"; 10 | 11 | // Create a BedrockRuntimeClient with your configuration 12 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 13 | 14 | const prompt = "red backpack on a table"; 15 | 16 | const input = { 17 | modelId: "amazon.titan-image-generator-v1", 18 | contentType: "application/json", 19 | accept: "application/json", 20 | body: JSON.stringify({ 21 | textToImageParams: { 22 | text: prompt, 23 | negativeText: "people, faces", 24 | }, 25 | taskType: "TEXT_IMAGE", 26 | imageGenerationConfig: { 27 | cfgScale: 8, 28 | // if you want to specify a seed value 29 | // seed: 0, 30 | quality: "standard", // or premium 31 | width: 512, 32 | height: 512, 33 | numberOfImages: 1, 34 | }, 35 | }), 36 | }; 37 | 38 | // Create an InvokeModelCommand with the input parameters 39 | const command = new InvokeModelCommand(input); 40 | 41 | // Send the command to invoke the model and await the response 42 | const response = await client.send(command); 43 | console.log("-------------------"); 44 | console.log("---Full Response---"); 45 | console.log("-------------------"); 46 | console.log(response); 47 | 48 | // body: Uint8ArrayBlobAdapter(518508) [Uint8Array] [ 49 | // 123, 34, 105, 109, 97, 103, 101, 115, 34, 58, 91, 34, 50 | // 105, 86, 66, 79, 82, 119, 48, 75, 71, 103, 111, 65, 51 | // 65, 65, 65, 78, 83, 85, 104, 69, 85, 103, 65, 65, 52 | // 65, 103, 65, 65, 65, 65, 73, 65, 67, 65, 73, 65, 53 | // 65, 65, 66, 55, 71, 107, 79, 116, 65, 65, 69, 65, 54 | // 65, 69, 108, 69, 81, 86, 82, 52, 110, 70, 84, 57, 55 | // 51, 90, 73, 106, 83, 55, 73, 114, 106, 65, 70, 119, 56 | // 106, 121, 83, 55, 53, 57, 79, 70, 88, 108, 70, 118, 57 | // 111, 65, 117, 57, 58 | // ... 518408 more items 59 | // ] 60 | 61 | // Save the raw response 62 | const rawRes = response.body; 63 | 64 | // Convert it to a JSON String 65 | const jsonString = new TextDecoder().decode(rawRes); 66 | 67 | // Parse the JSON string 68 | const parsedResponse = JSON.parse(jsonString); 69 | 70 | console.log("-------------------------"); 71 | console.log("---Parsed Response Body---"); 72 | console.log("-------------------------"); 73 | console.log(parsedResponse); 74 | // { 75 | // images: [ 76 | // 'iVBORw0KGgoAA...', 77 | // 'siv03ldsnc...' 78 | // ] 79 | // error: null 80 | // } 81 | 82 | // Lets create the image from the base64 data 83 | // If you have multiple images, handle this in a loop. 84 | const base64ImageData = parsedResponse.images[0]; 85 | 86 | // Remove the data URI prefix if it exists 87 | const base64Data = base64ImageData.replace(/^data:image\/\w+;base64,/, ""); 88 | 89 | // Create a buffer from the base64 data 90 | const imageBuffer = Buffer.from(base64Data, "base64"); 91 | 92 | // Generate a timestamp (e.g., current date and time) 93 | const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, ""); 94 | 95 | // Trim the prompt text to not exceed 20 characters 96 | const trimmedPrompt = prompt.slice(0, 20); 97 | 98 | // Remove all special characters from the prompt 99 | const promptWithoutSpecialChars = trimmedPrompt.replace(/[^\w\s]/g, ""); 100 | 101 | // Create a prompt slug by replacing spaces with hyphens 102 | const promptSlug = promptWithoutSpecialChars.replace(/\s+/g, "-"); 103 | 104 | // Get the current directory 105 | const currentDir = dirname(fileURLToPath(import.meta.url)); 106 | 107 | // Define the "output" directory 108 | const outputDirectory = path.join(currentDir, "output"); 109 | 110 | // Create the filename 111 | const filename = `${timestamp}-${promptSlug}.png`; 112 | 113 | // Construct the absolute file path 114 | const filePath = path.join(outputDirectory, filename); 115 | 116 | // Save the image buffer to the file 117 | fs.writeFileSync(filePath, imageBuffer); 118 | 119 | console.log("------------------------"); 120 | console.log("-------Image Path-------"); 121 | console.log("------------------------"); 122 | console.log(`Image saved to: ${filePath}`); 123 | -------------------------------------------------------------------------------- /image/stable-diffusion-advanced.mjs: -------------------------------------------------------------------------------- 1 | import { 2 | BedrockRuntimeClient, 3 | InvokeModelCommand, 4 | } from "@aws-sdk/client-bedrock-runtime"; 5 | 6 | import fs from "fs"; 7 | import path from "path"; 8 | import { fileURLToPath } from "url"; 9 | import { dirname } from "path"; 10 | 11 | // Create a BedrockRuntimeClient with your configuration 12 | const client = new BedrockRuntimeClient({ region: "us-east-1" }); 13 | 14 | const prompt = "a beautiful mountain landscape"; 15 | const negativePrompts = [ 16 | "poorly rendered", 17 | "poor background details", 18 | "poorly drawn mountains", 19 | "disfigured mountain features", 20 | ]; 21 | const stylePreset = "photographic"; // (e.g. photographic, digital-art, cinematic, ...) 22 | const clipGuidancePreset = "FAST_GREEN"; // (e.g. FAST_BLUE FAST_GREEN NONE SIMPLE SLOW SLOWER SLOWEST) 23 | const sampler = "K_DPMPP_2S_ANCESTRAL"; // (e.g. DDIM, DDPM, K_DPMPP_SDE, K_DPMPP_2M, K_DPMPP_2S_ANCESTRAL, K_DPM_2, K_DPM_2_ANCESTRAL, K_EULER, K_EULER_ANCESTRAL, K_HEUN) 24 | 25 | const width = 768; 26 | const height = 1024; 27 | 28 | const textPrompts = [ 29 | { text: prompt, weight: 1.0 }, 30 | ...negativePrompts.map((negprompt) => ({ text: negprompt, weight: -1.0 })), 31 | ]; 32 | 33 | const input = { 34 | modelId: "stability.stable-diffusion-xl-v1", 35 | contentType: "application/json", 36 | accept: "application/json", 37 | body: JSON.stringify({ 38 | text_prompts: textPrompts, 39 | cfg_scale: 5, 40 | // If you want to set a seed, specify the seed value below 41 | // seed: 452345, 42 | steps: 50, 43 | style_preset: stylePreset, 44 | clip_guidance_preset: clipGuidancePreset, 45 | sampler: sampler, 46 | width: width, 47 | height: height, 48 | }), 49 | }; 50 | 51 | // Create an InvokeModelCommand with the input parameters 52 | const command = new InvokeModelCommand(input); 53 | 54 | // Send the command to invoke the model and await the response 55 | const response = await client.send(command); 56 | console.log("-------------------"); 57 | console.log("---Full Response---"); 58 | console.log("-------------------"); 59 | console.log(response); 60 | 61 | // response.body = Uint8ArrayBlobAdapter(65) [Uint8Array] [ 62 | // 123, 34, 99, 111, 109, 112, 108, 101, 116, 105, 111, 63 | // 110, 34, 58, 34, 32, 73, 39, 109, 32, 119, 101, 64 | // 108, 108, 44, 32, 116, 104, 97, 110, 107, 115, 33, 65 | // 34, 44, 34, 115, 116, 111, 112, 95, 114, 101, 97, 66 | // 115, 111, 110, 34, 58, 34, 115, 116, 111, 112, 95, 67 | // 115, 101, 113, 117, 101, 110, 99, 101, 34, 125 68 | // ] 69 | 70 | // Save the raw response 71 | const rawRes = response.body; 72 | 73 | // Convert it to a JSON String 74 | const jsonString = new TextDecoder().decode(rawRes); 75 | 76 | // Parse the JSON string 77 | const parsedResponse = JSON.parse(jsonString); 78 | 79 | console.log("-------------------------"); 80 | console.log("---Parsed Response Body---"); 81 | console.log("-------------------------"); 82 | console.log(parsedResponse); 83 | // { 84 | // result: 'success', 85 | // artifacts: [ 86 | // { 87 | // seed: 0, 88 | // base64: 'iVBORw0K .....' 89 | // } 90 | // ] 91 | // } 92 | 93 | // Lets create the image from the base64 data 94 | const base64ImageData = parsedResponse.artifacts[0].base64; 95 | 96 | // Remove the data URI prefix if it exists 97 | const base64Data = base64ImageData.replace(/^data:image\/\w+;base64,/, ""); 98 | 99 | // Create a buffer from the base64 data 100 | const imageBuffer = Buffer.from(base64Data, "base64"); 101 | 102 | // Generate a timestamp (e.g., current date and time) 103 | const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, ""); 104 | 105 | // Trim the prompt text to not exceed 100 characters 106 | const trimmedPrompt = prompt.slice(0, 100); 107 | 108 | // Create a prompt slug by replacing spaces with hyphens 109 | const promptSlug = trimmedPrompt.replace(/\s+/g, "-"); 110 | 111 | // Get the current directory 112 | const currentDir = dirname(fileURLToPath(import.meta.url)); 113 | 114 | // Define the "output" directory 115 | const outputDirectory = path.join(currentDir, "output"); 116 | 117 | // Create the filename 118 | const filename = `${timestamp}-${promptSlug}.png`; 119 | 120 | // Construct the absolute file path 121 | const filePath = path.join(outputDirectory, filename); 122 | 123 | // Save the image buffer to the file 124 | fs.writeFileSync(filePath, imageBuffer); 125 | 126 | console.log("------------------------"); 127 | console.log("-------Image Path-------"); 128 | console.log("------------------------"); 129 | console.log(`Image saved to: ${filePath}`); 130 | --------------------------------------------------------------------------------