Imports and Setup:
import 'dotenv/config'
import { openai } from './openai.js'
import math from 'advanced-calculator'
const QUESTION = process.argv[2] || 'hi'
dotenv/config
is imported to load environment variables (e.g., API keys) from a .env
file.openai
module is imported, which likely contains functions to interact with the OpenAI API.advanced-calculator
module is imported as math
, providing math calculation capabilities.QUESTION
is set to the first command-line argument, or defaults to 'hi' if none is provided.Messages and Functions:
const messages = [
{
role: 'user',
content: QUESTION,
},
]
const functions = {
calculate: async ({ expression }) => {
return math.evaluate(expression)
},
}
messages
: Initializes an array with the user's question.functions
: Defines an object where the keys are function names, and the values are the corresponding functions. Here, there's only one function, calculate
, which evaluates a mathematical expression.Get Completion Function:
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
}
calculate
to evaluate math expressions.Main Loop:
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 }),
})
}
}
finish_reason
of 'stop', it prints the response and exits the loop.