-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction-calling.js
More file actions
102 lines (92 loc) · 2.42 KB
/
Copy pathfunction-calling.js
File metadata and controls
102 lines (92 loc) · 2.42 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import openAI from './openai.js';
import math from 'advanced-calculator';
const QUESTION = process.argv[2] || 'hi';
const messages = [
{
role: 'user',
content: QUESTION,
},
];
const functions = {
calculate({ expression }) {
console.log('expression', expression);
return math.evaluate(expression);
},
async generateImage({ prompt }) {
const result = await openAI.images.generate({ prompt });
console.log('Image', result);
return (
result.data[0].url ??
result.data[0].b64_json ??
result.data[0].revised_prompt
);
},
};
const getCompletion = messages => {
return openAI.chat.completions.create({
messages,
model: 'gpt-3.5-turbo',
temperature: 0,
functions: [
{
name: 'calculate',
description: 'Run a math expression',
parameters: {
type: 'object',
properties: {
expression: {
type: 'string',
description:
'Then math expression to evaluate like "2 * 3 + (21 / 2) ^ 2"',
},
},
required: ['expression'],
},
},
{
name: 'generateImage',
description: 'Create or generate image',
parameters: {
type: 'object',
properties: {
prompt: {
type: 'string',
description: 'The description of the image to generate',
},
},
required: ['prompt'],
},
},
],
});
};
let response;
while (true) {
response = await getCompletion(messages);
console.log('Response Reason', response.choices[0].finish_reason);
if (response.choices[0].finish_reason == 'stop') {
console.log('Finish Reason', response.choices[0].message.content);
break;
} else if (response.choices[0].finish_reason == 'function_call') {
const fnName = response.choices[0].message.function_call.name;
const args = response.choices[0].message.function_call.arguments;
console.log('FnName', fnName);
console.log('args', args);
const funcToCall = functions[fnName];
const params = JSON.parse(args);
const result = await funcToCall(params);
messages.push({
role: 'assistant',
content: null,
function_call: {
name: fnName,
arguments: args,
},
});
messages.push({
role: 'function',
name: fnName,
content: JSON.stringify({ result }),
});
}
}