Let’s write some code!

We’re going to build a simple chat app that you can use in the terminal.


  1. Imports:
import 'dotenv/config'
import readline from 'node:readline'
import OpenAI from 'openai'

  1. Initialize OpenAI API:
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
})
  1. Setting up User Interface:
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
})

  1. Message Handling:
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
}

  1. Formatting User Message:
const formatMessage = (userInput) => ({ role: 'user', content: userInput })

  1. Main Chat Function:
const chat = () => {
  //...
}