-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
97 lines (81 loc) · 2.81 KB
/
index.mjs
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { credentials } from "./credentials/index.mjs";
import OpenAI from "openai";
import { toolDefinitions } from "./tools/definitions.mjs";
import { getCurrentWeather } from "./tools/functions/weather.mjs";
import { systemPrompt } from "./prompts/system.mjs";
const { resource, deployment, apiVersion, azOaiKey } = credentials;
const openai = new OpenAI({
apiKey: azOaiKey,
baseURL: `https://${resource}.openai.azure.com/openai/deployments/${deployment}`,
defaultQuery: { "api-version": apiVersion },
defaultHeaders: { "api-key": azOaiKey },
maxRetries: 10,
timeout: 60 * 1000,
});
async function askAI(question) {
const messages = [
{
role: "system",
content: systemPrompt,
},
{
role: "user",
content: question,
},
];
const response = await openai.chat.completions.create({
model: deployment,
messages: messages,
tools: toolDefinitions,
tool_choice: "auto",
});
const responseMessage = response.choices[0].message;
const toolCalls = responseMessage.tool_calls;
if (responseMessage.tool_calls) {
const availableFunctions = {
get_current_weather: getCurrentWeather,
};
messages.push(responseMessage);
for (const toolCall of toolCalls) {
const functionName = toolCall.function.name;
const functionToCall = availableFunctions[functionName];
const functionArgs = JSON.parse(toolCall.function.arguments);
const functionResponse = functionToCall(
functionArgs.location,
functionArgs.unit
);
const functionExecutionObject = {
tool_call_id: toolCall.id,
role: "tool",
name: functionName,
content: functionResponse,
};
console.log("\n--------------<ToolCall>-----------------\n");
console.log("Running Function: ", functionName);
console.log("Function Args: ", functionArgs);
console.log("Output: ", functionResponse);
console.log("\n--------------</ToolCall>----------------\n");
messages.push(functionExecutionObject);
}
const secondResponse = await openai.chat.completions.create({
model: deployment,
messages: messages,
});
return secondResponse;
}
}
const theQuestion =
"What's the weather like in San Francisco, Tokyo, and Paris?";
askAI(theQuestion)
.then((res) => {
console.log("\n--------------<RawResponse>-----------------\n");
console.log(res);
console.log("\n--------------</RawResponse>-----------------\n");
console.log("\n--------------<Answer>-----------------\n");
console.log(res.choices[0].message.content);
console.log("\n--------------</Answer>-----------------\n");
console.log("\n--------------<Usage>-----------------\n");
console.table(res.usage);
console.log("\n--------------</Usage>-----------------\n");
})
.catch(console.error);