-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathfunction_calling.js
80 lines (67 loc) · 2.02 KB
/
function_calling.js
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
import OpenAI from "openai";
const openai = new OpenAI();
const USER_INPUT = "What is the weather in New York and Paris?";
const messages = [
{ role: "system", content: "You are a helpful assistant." },
{
role: "user",
content: USER_INPUT,
},
];
const tools = [
{
name: "get_weather",
description: "Get the weather for a given location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description:
"The location to get the weather for, in the format of: city, state (if applicable), country",
},
unit: {
type: "string",
description:
"The unit of measurement for the weather. If not specified, use the most common unit used at the provided location (e.g. celsius for Europe, fahrenheit for USA).",
enum: ["celsius", "fahrenheit"],
},
},
required: ["location", "unit"],
},
},
];
const getCompletion = async () => {
console.log(`User input: ${USER_INPUT}`);
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: messages,
tools: tools.map((tool) => ({ type: "function", function: tool })),
});
console.log(completion.choices[0].message);
for (const toolCall of completion.choices[0].message.tool_calls) {
const name = toolCall.function.name;
const args = JSON.parse(toolCall.function.arguments);
console.log(
`Calling function '${name}' with args: ${JSON.stringify(args)}`
);
const result = await callFunction(name, args);
console.log(result);
}
};
const callFunction = async (name, args) => {
if (name === "get_weather") {
return getWeather(args.location, args.unit);
}
};
// Mocking a weather API call
const getWeather = async (location, unit) => {
let unitSymbol = "C";
let temperature = 20;
if (unit === "fahrenheit") {
temperature = 68;
unitSymbol = "F";
}
return `The current weather in ${location} is ${temperature}°${unitSymbol}.`;
};
getCompletion();