-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathinvoke_mistral_7b.js
More file actions
74 lines (64 loc) · 2.14 KB
/
invoke_mistral_7b.js
File metadata and controls
74 lines (64 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { fileURLToPath } from "node:url";
import { FoundationModels } from "../../config/foundation_models.js";
import {
BedrockRuntimeClient,
InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";
/**
* @typedef {Object} Output
* @property {string} text
*
* @typedef {Object} ResponseBody
* @property {Output[]} outputs
*/
/**
* Invokes a Mistral 7B Instruct model.
*
* @param {string} prompt - The input text prompt for the model to complete.
* @param {string} [modelId] - The ID of the model to use. Defaults to "mistral.mistral-7b-instruct-v0:2".
*/
export const invokeModel = async (
prompt,
modelId = "mistral.mistral-7b-instruct-v0:2",
) => {
// Create a new Bedrock Runtime client instance.
const client = new BedrockRuntimeClient({ region: "us-east-1" });
// Mistral instruct models provide optimal results when embedding
// the prompt into the following template:
const instruction = `<s>[INST] ${prompt} [/INST]`;
// Prepare the payload.
const payload = {
prompt: instruction,
max_tokens: 500,
temperature: 0.5,
};
// Invoke the model with the payload and wait for the response.
const command = new InvokeModelCommand({
contentType: "application/json",
body: JSON.stringify(payload),
modelId,
});
const apiResponse = await client.send(command);
// Decode and return the response.
const decodedResponseBody = new TextDecoder().decode(apiResponse.body);
/** @type {ResponseBody} */
const responseBody = JSON.parse(decodedResponseBody);
return responseBody.outputs[0].text;
};
// Invoke the function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const prompt =
'Complete the following in one sentence: "Once upon a time..."';
const modelId = FoundationModels.MISTRAL_7B.modelId;
console.log(`Prompt: ${prompt}`);
console.log(`Model ID: ${modelId}`);
try {
console.log("-".repeat(53));
const response = await invokeModel(prompt, modelId);
console.log(response);
} catch (err) {
console.log(err);
}
}