AM|FM

Building a NodeJS + ChatGPT AI Chatbot

Feel free to crib from my implementation — check out the repository at https://github.com/csdear/ai_chatbot.


A Recent Experience with AI Chatbots

In a recent interview, one of the "nice-to-have" requirements was experience with AI chatbots. That got me thinking: Could I throw something together the morning before the interview to impress my interviewers?

Turns out, it wasn’t too difficult. But I did run into a couple of hurdles that weren't mentioned in the resources I followed:


  1. This costs money. $$$. If you're not prepared, you’ll get the dreaded Error code 429: "You have exceeded your current quota, please check your plan and billing details." Huh, funny how the resource failed to mention this... Maybe there’s a free option, but I couldn’t find it. So, I pumped $10 USD into OpenAI to raise my quota, regenerated my API key, and then I was able to get AI responses from my questions.

  1. The implementation instructions had changed. It had only been a month since the resource was published, yet many of the referenced libraries were refactored out of existence, causing countless errors when my project tried to reference the modules in the node_modules folder. I had to dig into the dreaded documentation to wire things up. An old tech lead’s words of wisdom rang in my ears: RTFM. So I did, and I can confidently say that as of 10/22/2024, this project works with openai version 4.67.3 and Node version v20.11.0.

    Here are some helpful "RTFM" links:



My Recipe for Creating a Node.js Chatbot

Here’s how to create a Node.js app — hopefully as painlessly as possible:


  1. Create the GitHub repo with a README and .gitignore. Copy the clone URL.

  1. Open the project in VSCode and in the terminal, navigate to the root folder where you keep your repositories, and run:
    git clone <clone_url>
    

  1. Run npm init to create the package.json file.

  1. Create the index.js file by running touch index.js if you’re using a Unix-based system, or manually create the file in your project folder.

  1. Edit package.json:
    • Replace the scripts block to enable running the project via npm start:
      "scripts": {
          "start": "node index.js"
      }
      
    • Add the "type" field to use ES modules instead of CommonJS, allowing you to use import/export instead of require:
      "type": "module",
      

  1. Install necessary packages: dotenv for storing access keys, readline-sync for user input, and colors for styled console output:
    npm install dotenv readline-sync colors --save-dev
    

  1. Run your application:
    node index.js
    

  1. Push your initial changes to GitHub.

  1. Get an OpenAI API key by logging in to OpenAI/ChatGPT and going to https://platform.openai.com/api-keys. Click the "+ Create new secret key" button, and save your key somewhere safe.

  1. Set up your .env file (if it doesn't already exist) to store your API key:
    OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
    

  1. Create a /config folder in your project's root. Inside this folder, create a open-ai.js file. In it, you'll import the OpenAI module, load the environment variables, instantiate the OpenAI client, and export it:
    import OpenAI from "openai";
    import dotenv from 'dotenv';
    dotenv.config();
    
    const openai = new OpenAI({
        apiKey: process.env.OPENAI_API_KEY,
    });
    
    export default openai;
    

  1. Import the necessary modules in your main app file (index.js):
    import openai from './config/open-ai.js';
    import readlineSync from 'readline-sync';
    import colors from 'colors';
    

  1. Create an asynchronous main() function that optionally greets the user:
    async function main() {
        console.log(colors.bold.green('Welcome to a NodeJS ChatGPT Program!'));
        const userName = readlineSync.question('Your name? ');
        console.log(`Hello ${userName}`);
    }
    

  1. Create a chat loop: In a while loop, prompt the user for input (styled in yellow) and run the chatbot interaction until the user types "exit":
    while (true) {
        const userInput = readlineSync.question(colors.yellow('You: '));
        if (userInput.toLowerCase() === 'exit') return;
    }
    

  1. Add a try/catch block to handle the OpenAI API call, and log the bot's response (styled in green):
    try {
        const chatCompletion = await openai.chat.completions.create({
            messages: [{ role: "user", content: userInput }],
            model: "gpt-4o-mini",
        });
        const completionText = chatCompletion.choices[0].message.content;
        console.log(colors.green('Bot: ') + completionText);
    } catch (error) {
        console.error(colors.red(error));
    }
    

  1. Run the main() function:
    main();
    


Wouldn't it be funny if chatGPT responded to the last question with 12?



Wrap-Up

That’s it! You now have a functional Node.js chatbot using OpenAI's API. Feel free to expand on it or make it your own.

If you have any questions, comments, or corrections, feel free to reach out at csdear138@gmail.com. I’m human, all too human
— happy hunting! (Too soon, ChatGPT?)