We’re going to build a simple chat app that you can use in the terminal.
import 'dotenv/config'
import readline from 'node:readline'
import OpenAI from 'openai'
dotenv/config
: This loads environment variables from a .env
file.readline
: Provides an interface for reading data from a readable stream.openai
: The SDK for interacting with the OpenAI API.const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
readline
is set up to read input from the terminal (stdin
) and output back to it (stdout
).const newMessage = async (history, message) => {
const chatCompletion = await openai.chat.completions.create({
messages: [...history, message],
model: 'gpt-3.5-turbo',
})
return chatCompletion.choices[0].message
}
const formatMessage = (userInput) => ({ role: 'user', content: userInput })
const chat = () => {
//...
}