bedrock-wrapper 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.example.env +13 -0
- package/LICENSE +21 -0
- package/README.md +119 -0
- package/bedrock-models.js +99 -0
- package/bedrock-wrapper.js +164 -0
- package/docs/bedrock-tunnel-endpoint.jpg +0 -0
- package/example.js +95 -0
- package/package.json +28 -0
package/.example.env
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# ========================
|
|
2
|
+
# == AWS AUTH VARIABLES ==
|
|
3
|
+
# ========================
|
|
4
|
+
AWS_REGION = "us-west-2"
|
|
5
|
+
AWS_ACCESS_KEY_ID = "AKxxxxxxxxxxxxxxxxxx"
|
|
6
|
+
AWS_SECRET_ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
|
7
|
+
|
|
8
|
+
# ================
|
|
9
|
+
# == LLM PARAMS ==
|
|
10
|
+
# ================
|
|
11
|
+
LLM_MAX_GEN_TOKENS = 800
|
|
12
|
+
LLM_TEMPERATURE = 0.1
|
|
13
|
+
LLM_TOP_P = 0.9
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Justin Parker
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# 🪨 Bedrock Wrapper
|
|
2
|
+
Bedrock Wrapper is an npm package that simplifies the integration of existing OpenAI-compatible API objects with AWS Bedrock's serverless inference LLMs. Follow the steps below to integrate into your own application, or alternativly use the 🪨 [Bedrock Proxy Endpoint](https://github.com/jparkerweb/bedrock-proxy-endpoint) project to spin up your own custom OpenAI server endpoint for even easier inference (using the standard `baseUrl`, and `apiKey` params).
|
|
3
|
+
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
### Install
|
|
7
|
+
|
|
8
|
+
- install package: `npm install bedrock-wrapper`
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
### Usage
|
|
13
|
+
|
|
14
|
+
1. import `bedrockWrapper`
|
|
15
|
+
```javascript
|
|
16
|
+
import { bedrockWrapper } from "bedrock-wrapper";
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
2. create an `awsCreds` object and fill in your AWS credentials
|
|
20
|
+
```javascript
|
|
21
|
+
const awsCreds = {
|
|
22
|
+
region: AWS_REGION,
|
|
23
|
+
accessKeyId: AWS_ACCESS_KEY_ID,
|
|
24
|
+
secretAccessKey: AWS_SECRET_ACCESS_KEY,
|
|
25
|
+
};
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
3. clone your openai chat completions object into `openaiChatCompletionsCreateObject` or create a new one and edit the values
|
|
29
|
+
```javascript
|
|
30
|
+
const openaiChatCompletionsCreateObject = {
|
|
31
|
+
"messages": messages,
|
|
32
|
+
"model": "Llama-3-8b",
|
|
33
|
+
"max_tokens": LLM_MAX_GEN_TOKENS,
|
|
34
|
+
"stream": true,
|
|
35
|
+
"temperature": LLM_TEMPERATURE,
|
|
36
|
+
"top_p": LLM_TOP_P,
|
|
37
|
+
};
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
the `messages` variable should be in openai's role/content format
|
|
41
|
+
```javascript
|
|
42
|
+
messages = [
|
|
43
|
+
{
|
|
44
|
+
role: "system",
|
|
45
|
+
content: "You are a helpful AI assistant that follows instructions extremely well. Answer the user questions accurately. Think step by step before answering the question. You will get a $100 tip if you provide the correct answer.",
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
role: "user",
|
|
49
|
+
content: "Describe why openai api standard used by lots of serverless LLM api providers is better than aws bedrock invoke api offered by aws bedrock. Limit your response to five sentences.",
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
role: "assistant",
|
|
53
|
+
content: "",
|
|
54
|
+
},
|
|
55
|
+
]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
***the `model` value should be either a corresponding `modelName` or `modelId` for the supported `bedrock_models` (see the Supported Models section below)***
|
|
59
|
+
|
|
60
|
+
4. call the `bedrockWrapper` function and pass in the previously defined `awsCreds` and `openaiChatCompletionsCreateObject` objects
|
|
61
|
+
```javascript
|
|
62
|
+
// create a variable to hold the complete response
|
|
63
|
+
let completeResponse = "";
|
|
64
|
+
// invoke the streamed bedrock api response
|
|
65
|
+
for await (const chunk of bedrockWrapper(awsCreds, openaiChatCompletionsCreateObject)) {
|
|
66
|
+
completeResponse += chunk;
|
|
67
|
+
// ---------------------------------------------------
|
|
68
|
+
// -- each chunk is streamed as it is received here --
|
|
69
|
+
// ---------------------------------------------------
|
|
70
|
+
process.stdout.write(chunk); // ⇠ do stuff with the streamed chunk
|
|
71
|
+
}
|
|
72
|
+
// console.log(`\n\completeResponse:\n${completeResponse}\n`); // ⇠ optional do stuff with the complete response returned from the API reguardless of stream or not
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
if calling the unstreamed version you can call bedrockWrapper like this
|
|
76
|
+
```javascript
|
|
77
|
+
// create a variable to hold the complete response
|
|
78
|
+
let completeResponse = "";
|
|
79
|
+
// invoke the streamed bedrock api response
|
|
80
|
+
if (!openaiChatCompletionsCreateObject.stream){ // invoke the unstreamed bedrock api response
|
|
81
|
+
const response = await bedrockWrapper(awsCreds, openaiChatCompletionsCreateObject);
|
|
82
|
+
for await (const data of response) {
|
|
83
|
+
const jsonString = new TextDecoder().decode(data.body);
|
|
84
|
+
const jsonResponse = JSON.parse(jsonString);
|
|
85
|
+
completeResponse += jsonResponse.generation;
|
|
86
|
+
}
|
|
87
|
+
// ----------------------------------------------------
|
|
88
|
+
// -- unstreamed complete response is available here --
|
|
89
|
+
// ----------------------------------------------------
|
|
90
|
+
console.log(`\n\completeResponse:\n${completeResponse}\n`); // ⇠ do stuff with the complete response
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
### Supported Models
|
|
96
|
+
|
|
97
|
+
| modelName | modelId |
|
|
98
|
+
|----------------|------------------------------------|
|
|
99
|
+
| Llama-3-8b | meta.llama3-8b-instruct-v1:0 |
|
|
100
|
+
| Llama-3-70b | meta.llama3-70b-instruct-v1:0 |
|
|
101
|
+
| Mixtral-8x7b | mistral.mixtral-8x7b-instruct-v0:1 |
|
|
102
|
+
| Mistral-Large | mistral.mistral-large-2402-v1:0 |
|
|
103
|
+
|
|
104
|
+
To return the list progrmatically you can import and call `listBedrockWrapperSupportedModels`:
|
|
105
|
+
```javascript
|
|
106
|
+
import { listBedrockWrapperSupportedModels } from 'bedrock-wrapper';
|
|
107
|
+
console.log(`\nsupported models:\n${JSON.stringify(await listBedrockWrapperSupportedModels())}\n`);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Additional Bedrock model support can be added.
|
|
111
|
+
Please modify the `bedrock_models.js` file and submit a PR 🏆 or create an Issue.
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
### 📢 P.S.
|
|
116
|
+
|
|
117
|
+
In case you missed it at the beginning of this doc, for an even easier setup, use the 🔀 [Bedrock Proxy Endpoint](https://github.com/jparkerweb/bedrock-proxy-endpoint) project to spin up your own custom OpenAI server endpoint (using the standard `baseUrl`, and `apiKey` params).
|
|
118
|
+
|
|
119
|
+

|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Description: This file contains the model configurations
|
|
2
|
+
export const bedrock_models = [
|
|
3
|
+
{
|
|
4
|
+
// ================
|
|
5
|
+
// == Llama 3 8b ==
|
|
6
|
+
// ================
|
|
7
|
+
"modelName": "Llama-3-8b",
|
|
8
|
+
"modelId": "meta.llama3-8b-instruct-v1:0",
|
|
9
|
+
"bos_text": "<|begin_of_text|>",
|
|
10
|
+
"role_system_message_prefix": "",
|
|
11
|
+
"role_system_message_suffix": "",
|
|
12
|
+
"role_system_prefix": "<|start_header_id|>",
|
|
13
|
+
"role_system_suffix": "<|end_header_id|>",
|
|
14
|
+
"role_user_message_prefix": "",
|
|
15
|
+
"role_user_message_suffix": "",
|
|
16
|
+
"role_user_prefix": "<|start_header_id|>",
|
|
17
|
+
"role_user_suffix": "<|end_header_id|>",
|
|
18
|
+
"role_assistant_message_prefix": "",
|
|
19
|
+
"role_assistant_message_suffix": "",
|
|
20
|
+
"role_assistant_prefix": "<|start_header_id|>",
|
|
21
|
+
"role_assistant_suffix": "<|end_header_id|>",
|
|
22
|
+
"eom_text": "<|eot_id|>",
|
|
23
|
+
"display_role_names": true,
|
|
24
|
+
"max_tokens_param_name": "max_gen_len",
|
|
25
|
+
"response_chunk_element": "generation",
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
// =================
|
|
29
|
+
// == Llama 3 70b ==
|
|
30
|
+
// =================
|
|
31
|
+
"modelName": "Llama-3-70b",
|
|
32
|
+
"modelId": "meta.llama3-70b-instruct-v1:0",
|
|
33
|
+
"bos_text": "<|begin_of_text|>",
|
|
34
|
+
"role_system_message_prefix": "",
|
|
35
|
+
"role_system_message_suffix": "",
|
|
36
|
+
"role_system_prefix": "<|start_header_id|>",
|
|
37
|
+
"role_system_suffix": "<|end_header_id|>",
|
|
38
|
+
"role_user_message_prefix": "",
|
|
39
|
+
"role_user_message_suffix": "",
|
|
40
|
+
"role_user_prefix": "<|start_header_id|>",
|
|
41
|
+
"role_user_suffix": "<|end_header_id|>",
|
|
42
|
+
"role_assistant_message_prefix": "",
|
|
43
|
+
"role_assistant_message_suffix": "",
|
|
44
|
+
"role_assistant_prefix": "<|start_header_id|>",
|
|
45
|
+
"role_assistant_suffix": "<|end_header_id|>",
|
|
46
|
+
"eom_text": "<|eot_id|>",
|
|
47
|
+
"display_role_names": true,
|
|
48
|
+
"max_tokens_param_name": "max_gen_len",
|
|
49
|
+
"response_chunk_element": "generation",
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
// ==================
|
|
53
|
+
// == Mixtral-8x7b ==
|
|
54
|
+
// ==================
|
|
55
|
+
"modelName": "Mixtral-8x7b",
|
|
56
|
+
"modelId": "mistral.mixtral-8x7b-instruct-v0:1",
|
|
57
|
+
"bos_text": "<s>",
|
|
58
|
+
"role_system_message_prefix": "",
|
|
59
|
+
"role_system_message_suffix": "",
|
|
60
|
+
"role_system_prefix": "",
|
|
61
|
+
"role_system_suffix": "",
|
|
62
|
+
"role_user_message_prefix": "[INST]",
|
|
63
|
+
"role_user_message_suffix": "[/INST]",
|
|
64
|
+
"role_user_prefix": "",
|
|
65
|
+
"role_user_suffix": "",
|
|
66
|
+
"role_assistant_message_prefix": "",
|
|
67
|
+
"role_assistant_message_suffix": "",
|
|
68
|
+
"role_assistant_prefix": "",
|
|
69
|
+
"role_assistant_suffix": "",
|
|
70
|
+
"eom_text": "</s>",
|
|
71
|
+
"display_role_names": false,
|
|
72
|
+
"max_tokens_param_name": "max_tokens",
|
|
73
|
+
"response_chunk_element": "outputs[0].text",
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
// ===================
|
|
77
|
+
// == Mistral Large ==
|
|
78
|
+
// ===================
|
|
79
|
+
"modelName": "Mistral-Large",
|
|
80
|
+
"modelId": "mistral.mistral-large-2402-v1:0",
|
|
81
|
+
"bos_text": "<s>",
|
|
82
|
+
"role_system_message_prefix": "",
|
|
83
|
+
"role_system_message_suffix": "",
|
|
84
|
+
"role_system_prefix": "",
|
|
85
|
+
"role_system_suffix": "",
|
|
86
|
+
"role_user_message_prefix": "[INST]",
|
|
87
|
+
"role_user_message_suffix": "[/INST]",
|
|
88
|
+
"role_user_prefix": "",
|
|
89
|
+
"role_user_suffix": "",
|
|
90
|
+
"role_assistant_message_prefix": "",
|
|
91
|
+
"role_assistant_message_suffix": "",
|
|
92
|
+
"role_assistant_prefix": "",
|
|
93
|
+
"role_assistant_suffix": "",
|
|
94
|
+
"eom_text": "</s>",
|
|
95
|
+
"display_role_names": false,
|
|
96
|
+
"max_tokens_param_name": "max_tokens",
|
|
97
|
+
"response_chunk_element": "outputs[0].text",
|
|
98
|
+
},
|
|
99
|
+
];
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// ======================================================================
|
|
2
|
+
// == 🪨 Bedrock Wrapper ==
|
|
3
|
+
// == ==
|
|
4
|
+
// == Bedrock Wrapper is an npm package that simplifies the integration ==
|
|
5
|
+
// == of existing OpenAI-compatible API objects AWS Bedrock's ==
|
|
6
|
+
// == serverless inference LLMs. ==
|
|
7
|
+
// ======================================================================
|
|
8
|
+
writeAsciiArt();
|
|
9
|
+
|
|
10
|
+
// -------------
|
|
11
|
+
// -- imports --
|
|
12
|
+
// -------------
|
|
13
|
+
import { bedrock_models } from "./bedrock-models.js";
|
|
14
|
+
import {
|
|
15
|
+
BedrockRuntimeClient,
|
|
16
|
+
InvokeModelCommand, InvokeModelWithResponseStreamCommand,
|
|
17
|
+
} from "@aws-sdk/client-bedrock-runtime";
|
|
18
|
+
|
|
19
|
+
// -------------------
|
|
20
|
+
// -- main function --
|
|
21
|
+
// -------------------
|
|
22
|
+
export async function* bedrockWrapper(awsCreds, openaiChatCompletionsCreateObject, { logging = false } = {} ) {
|
|
23
|
+
const { region, accessKeyId, secretAccessKey } = awsCreds;
|
|
24
|
+
const { messages, model, max_tokens, stream, temperature, top_p } = openaiChatCompletionsCreateObject;
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
// retrieve the model configuration
|
|
28
|
+
const awsModel = bedrock_models.find((x) => (x.modelName.toLowerCase() === model.toLowerCase() || x.modelId.toLowerCase() === model.toLowerCase()));
|
|
29
|
+
if (!awsModel) { throw new Error(`Model configuration not found for model: ${model}`); }
|
|
30
|
+
|
|
31
|
+
// cleanup message content before formatting prompt message
|
|
32
|
+
let message_cleaned = [];
|
|
33
|
+
for (let i = 0; i < messages.length; i++) {
|
|
34
|
+
if (messages[i].content !== "") {
|
|
35
|
+
message_cleaned.push(messages[i]);
|
|
36
|
+
} else if (awsModel.display_role_names) {
|
|
37
|
+
message_cleaned.push(messages[i]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (i === (messages.length - 1) && messages[i].content !== "" && awsModel.display_role_names) {
|
|
41
|
+
message_cleaned.push({role: "assistant", content: ""});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// format prompt message from message array
|
|
46
|
+
let prompt = awsModel.bos_text;
|
|
47
|
+
let eom_text_inserted = false;
|
|
48
|
+
for (let i = 0; i < message_cleaned.length; i++) {
|
|
49
|
+
prompt += "\n";
|
|
50
|
+
if (message_cleaned[i].role === "system") {
|
|
51
|
+
prompt += awsModel.role_system_message_prefix;
|
|
52
|
+
prompt += awsModel.role_system_prefix;
|
|
53
|
+
if (awsModel.display_role_names) { prompt += message_cleaned[i].role; }
|
|
54
|
+
prompt += awsModel.role_system_suffix;
|
|
55
|
+
if (awsModel.display_role_names) {prompt += "\n"; }
|
|
56
|
+
prompt += message_cleaned[i].content;
|
|
57
|
+
prompt += awsModel.role_system_message_suffix;
|
|
58
|
+
} else if (message_cleaned[i].role === "user") {
|
|
59
|
+
prompt += awsModel.role_user_message_prefix;
|
|
60
|
+
prompt += awsModel.role_user_prefix;
|
|
61
|
+
if (awsModel.display_role_names) { prompt += message_cleaned[i].role; }
|
|
62
|
+
prompt += awsModel.role_user_suffix;
|
|
63
|
+
if (awsModel.display_role_names) {prompt += "\n"; }
|
|
64
|
+
prompt += message_cleaned[i].content;
|
|
65
|
+
prompt += awsModel.role_user_message_suffix;
|
|
66
|
+
} else if (message_cleaned[i].role === "assistant") {
|
|
67
|
+
prompt += awsModel.role_assistant_message_prefix;
|
|
68
|
+
prompt += awsModel.role_assistant_prefix;
|
|
69
|
+
if (awsModel.display_role_names) { prompt += message_cleaned[i].role; }
|
|
70
|
+
prompt += awsModel.role_assistant_suffix;
|
|
71
|
+
if (awsModel.display_role_names) {prompt += "\n"; }
|
|
72
|
+
prompt += message_cleaned[i].content;
|
|
73
|
+
prompt += awsModel.role_assistant_message_suffix;
|
|
74
|
+
}
|
|
75
|
+
if (message_cleaned[i+1] && message_cleaned[i+1].content === "") {
|
|
76
|
+
prompt += `\n${awsModel.eom_text}`;
|
|
77
|
+
eom_text_inserted = true;
|
|
78
|
+
} else if ((i+1) === (message_cleaned.length - 1) && !eom_text_inserted) {
|
|
79
|
+
prompt += `\n${awsModel.eom_text}`;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// logging
|
|
84
|
+
if (logging) {
|
|
85
|
+
console.log(`\nPrompt: ${prompt}\n`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Format the request payload using the model's native structure.
|
|
89
|
+
const request = {
|
|
90
|
+
prompt,
|
|
91
|
+
// Optional inference parameters:
|
|
92
|
+
[awsModel.max_tokens_param_name]: max_tokens,
|
|
93
|
+
temperature: temperature,
|
|
94
|
+
top_p: top_p,
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// Create a Bedrock Runtime client in the AWS Region of your choice
|
|
98
|
+
const client = new BedrockRuntimeClient({
|
|
99
|
+
region: region,
|
|
100
|
+
credentials: {
|
|
101
|
+
accessKeyId: accessKeyId,
|
|
102
|
+
secretAccessKey: secretAccessKey,
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
if (stream) {
|
|
107
|
+
const responseStream = await client.send(
|
|
108
|
+
new InvokeModelWithResponseStreamCommand({
|
|
109
|
+
contentType: "application/json",
|
|
110
|
+
body: JSON.stringify(request),
|
|
111
|
+
modelId: awsModel.modelId,
|
|
112
|
+
}),
|
|
113
|
+
);
|
|
114
|
+
for await (const event of responseStream.body) {
|
|
115
|
+
const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
|
|
116
|
+
let result = getValueByPath(chunk, awsModel.response_chunk_element);
|
|
117
|
+
if (result) {
|
|
118
|
+
yield result;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
const apiResponse = await client.send(
|
|
123
|
+
new InvokeModelCommand({
|
|
124
|
+
contentType: "application/json",
|
|
125
|
+
body: JSON.stringify(request),
|
|
126
|
+
modelId: awsModel.modelId,
|
|
127
|
+
}),
|
|
128
|
+
);
|
|
129
|
+
yield apiResponse;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
// ---------------------------
|
|
135
|
+
// -- list supported models --
|
|
136
|
+
// ---------------------------
|
|
137
|
+
export async function listBedrockWrapperSupportedModels() {
|
|
138
|
+
let supported_models = [];
|
|
139
|
+
for (let i = 0; i < bedrock_models.length; i++) {
|
|
140
|
+
supported_models.push(`{"modelName": ${bedrock_models[i].modelName}, "modelId": ${bedrock_models[i].modelId}}`);
|
|
141
|
+
}
|
|
142
|
+
return supported_models;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
// ----------------------
|
|
147
|
+
// -- helper functions --
|
|
148
|
+
// ----------------------
|
|
149
|
+
// helper function to get a value from an object using a path string
|
|
150
|
+
function getValueByPath(obj, path) {
|
|
151
|
+
// Split the path into an array of keys
|
|
152
|
+
let keys = path.replace(/\[(\w+)\]/g, '.$1').split('.'); // Convert indexes into properties
|
|
153
|
+
// Reduce the keys array to the final value
|
|
154
|
+
return keys.reduce((acc, key) => acc && acc[key], obj);
|
|
155
|
+
}
|
|
156
|
+
// helper function to write ascii art
|
|
157
|
+
function writeAsciiArt() {
|
|
158
|
+
console.log(`
|
|
159
|
+
___ _ _ ___ _
|
|
160
|
+
| . > ___ _| | _ _ ___ ___ | |__ |_ _|_ _ ._ _ ._ _ ___ | |
|
|
161
|
+
| . \\/ ._>/ . || '_>/ . \\/ | '| / / | || | || ' || ' |/ ._>| |
|
|
162
|
+
|___/\\___.\\___||_| \\___/\\_|_.|_\\_\\ |_|\`___||_|_||_|_|\\___.|_|
|
|
163
|
+
`);
|
|
164
|
+
}
|
|
Binary file
|
package/example.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// ================================================================================
|
|
2
|
+
// == AWS Bedrock Example: Invoke a Model with a Streamed or Unstreamed Response ==
|
|
3
|
+
// ================================================================================
|
|
4
|
+
|
|
5
|
+
// ---------------------------------------------------------------------
|
|
6
|
+
// -- import environment variables from .env file or define them here --
|
|
7
|
+
// ---------------------------------------------------------------------
|
|
8
|
+
import dotenv from 'dotenv';
|
|
9
|
+
dotenv.config();
|
|
10
|
+
const AWS_REGION = process.env.AWS_REGION;
|
|
11
|
+
const AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID;
|
|
12
|
+
const AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY;
|
|
13
|
+
const LLM_MAX_GEN_TOKENS = parseInt(process.env.LLM_MAX_GEN_TOKENS);
|
|
14
|
+
const LLM_TEMPERATURE = parseFloat(process.env.LLM_TEMPERATURE);
|
|
15
|
+
const LLM_TOP_P = parseFloat(process.env.LLM_TOP_P);
|
|
16
|
+
|
|
17
|
+
// --------------------------------------------
|
|
18
|
+
// -- import functions from bedrock-wrapper --
|
|
19
|
+
// -- - bedrockWrapper --
|
|
20
|
+
// -- - listBedrockWrapperSupportedModels --
|
|
21
|
+
// --------------------------------------------
|
|
22
|
+
import { bedrockWrapper, listBedrockWrapperSupportedModels } from "bedrock-wrapper";
|
|
23
|
+
|
|
24
|
+
// ----------------------------------------------
|
|
25
|
+
// -- example call to list of supported models --
|
|
26
|
+
// ----------------------------------------------
|
|
27
|
+
console.log(`\nsupported models:\n${JSON.stringify(await listBedrockWrapperSupportedModels())}\n`);
|
|
28
|
+
|
|
29
|
+
// -----------------------------------------------
|
|
30
|
+
// -- example prompt in `messages` array format --
|
|
31
|
+
// -----------------------------------------------
|
|
32
|
+
const messages = [
|
|
33
|
+
{
|
|
34
|
+
role: "system",
|
|
35
|
+
content: "You are a helpful AI assistant that follows instructions extremely well. Answer the user questions accurately. Think step by step before answering the question. You will get a $100 tip if you provide the correct answer.",
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
role: "user",
|
|
39
|
+
content: "Describe why openai api standard used by lots of serverless LLM api providers is better than aws bedrock invoke api offered by aws bedrock. Limit your response to five sentences.",
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
role: "assistant",
|
|
43
|
+
content: "",
|
|
44
|
+
},
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------
|
|
49
|
+
// -- create an object to hold your AWS credentials --
|
|
50
|
+
// ---------------------------------------------------
|
|
51
|
+
const awsCreds = {
|
|
52
|
+
region: AWS_REGION,
|
|
53
|
+
accessKeyId: AWS_ACCESS_KEY_ID,
|
|
54
|
+
secretAccessKey: AWS_SECRET_ACCESS_KEY,
|
|
55
|
+
};
|
|
56
|
+
// ----------------------------------------------------------------------
|
|
57
|
+
// -- create an object that copies your openai chat completions object --
|
|
58
|
+
// ----------------------------------------------------------------------
|
|
59
|
+
const openaiChatCompletionsCreateObject = {
|
|
60
|
+
"messages": messages,
|
|
61
|
+
"model": "Llama-3-8b",
|
|
62
|
+
"max_tokens": LLM_MAX_GEN_TOKENS,
|
|
63
|
+
"stream": true,
|
|
64
|
+
"temperature": LLM_TEMPERATURE,
|
|
65
|
+
"top_p": LLM_TOP_P,
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
// ------------------------------------------------------------
|
|
70
|
+
// -- invoke the streamed or unstreamed bedrock api response --
|
|
71
|
+
// ------------------------------------------------------------
|
|
72
|
+
// create a variable to hold the complete response
|
|
73
|
+
let completeResponse = "";
|
|
74
|
+
// streamed call
|
|
75
|
+
if (openaiChatCompletionsCreateObject.stream) {
|
|
76
|
+
for await (const chunk of bedrockWrapper(awsCreds, openaiChatCompletionsCreateObject, { logging:true })) {
|
|
77
|
+
completeResponse += chunk;
|
|
78
|
+
// ---------------------------------------------------
|
|
79
|
+
// -- each chunk is streamed as it is received here --
|
|
80
|
+
// ---------------------------------------------------
|
|
81
|
+
process.stdout.write(chunk); // ⇠ do stuff with the streamed chunk
|
|
82
|
+
}
|
|
83
|
+
} else { // unstreamed call
|
|
84
|
+
const response = await bedrockWrapper(awsCreds, openaiChatCompletionsCreateObject, { logging:true });
|
|
85
|
+
for await (const data of response) {
|
|
86
|
+
const jsonString = new TextDecoder().decode(data.body);
|
|
87
|
+
const jsonResponse = JSON.parse(jsonString);
|
|
88
|
+
completeResponse += jsonResponse.generation;
|
|
89
|
+
}
|
|
90
|
+
// ----------------------------------------------------
|
|
91
|
+
// -- unstreamed complete response is available here --
|
|
92
|
+
// ----------------------------------------------------
|
|
93
|
+
console.log(`\n\completeResponse:\n${completeResponse}\n`); // ⇠ do stuff with the complete response
|
|
94
|
+
}
|
|
95
|
+
// console.log(`\n\completeResponse:\n${completeResponse}\n`); // ⇠ optional do stuff with the complete response returned from the API reguardless of stream or not
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "bedrock-wrapper",
|
|
3
|
+
"version": "1.0.10",
|
|
4
|
+
"description": "🪨 Bedrock Wrapper is an npm package that simplifies the integration of existing OpenAI-compatible API objects with AWS Bedrock's serverless inference LLMs.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/jparkerweb/bedrock-wrapper.git"
|
|
8
|
+
},
|
|
9
|
+
"main": "aws-bedrock-wrapper.js",
|
|
10
|
+
"type": "module",
|
|
11
|
+
"scripts": {
|
|
12
|
+
"example": "node example.js"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"openai",
|
|
16
|
+
"bedrock",
|
|
17
|
+
"aws",
|
|
18
|
+
"serverless",
|
|
19
|
+
"inference",
|
|
20
|
+
"llm"
|
|
21
|
+
],
|
|
22
|
+
"author": "",
|
|
23
|
+
"license": "ISC",
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@aws-sdk/client-bedrock-runtime": "^3.567.0",
|
|
26
|
+
"dotenv": "^16.4.5"
|
|
27
|
+
}
|
|
28
|
+
}
|