-
Notifications
You must be signed in to change notification settings - Fork 37
/
functions.js
77 lines (67 loc) · 1.7 KB
/
functions.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
import 'dotenv/config'
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: async ({ expression }) => {
return math.evaluate(expression)
},
}
const getCompletion = async (messages) => {
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo-0613',
messages,
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'],
},
},
],
temperature: 0,
})
return response
}
let response
while (true) {
response = await getCompletion(messages)
if (response.choices[0].finish_reason === 'stop') {
console.log(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
const functionToCall = functions[fnName]
const params = JSON.parse(args)
const result = functionToCall(params)
messages.push({
role: 'assistant',
content: null,
function_call: {
name: fnName,
arguments: args,
},
})
messages.push({
role: 'function',
name: fnName,
content: JSON.stringify({ result: result }),
})
}
}