How To Make Chatbot Using OPENAI

How To Make Chatbot Using OPENAI

As a developer, I prefer to access everything through the Terminal, As you already know we all depend on ChatGPT for almost all tasks and I don't want to jump again and again to the web browser to access it so I thought let's make a simple chatbot which I can access through the terminal. I think you got me as a developer we don't like to talk more so let's dive into the process.

Step - 1

First, you have to make an OpenAI account to get access to the API key

Step - 2

For this chatbot, I'm using JavaScript and Nodejs, So create a new folder and open it in your favorite code editor.

Now open the terminal and initialize Nodejs so you can install packages

npm init -y // write this command in terminal

Step -3

Open the package.json file and you have to make small changes

{
  "name": "chatbot",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Step - 4

Now you have to install the OpenAI and dotenv package

npm i openai dotenv

Step - 5

Create a new file called .env and paste your OpenAI API key

Step - 6

Create a new file called index.js and Let's write some code

// Load environment variables from a .env file
import "dotenv/config";

// Import the 'readline' module for handling user input
import readline from "node:readline";

// Import the OpenAI library
import OpenAI from "openai";

// Create a readline interface for reading user input
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// Initialize OpenAI with the API key from the environment variables
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// Function to send a new message to the OpenAI chat model
const newMessage = async (history, message) => {
  // Call the OpenAI API to generate a chat completion
  const chatCompletion = await openai.chat.completions.create({
    messages: [...history, message],
    model: "gpt-3.5-turbo",
  });

  // Return the content of the generated response
  return chatCompletion.choices[0].message;
};

// Function to format user input as a message object
const formatMessage = (userInput) => ({ role: "user", content: userInput });

// Main chat function
const chat = () => {
  // Initial conversation history with a system message
  const history = [
    {
      role: "system",
      content: `You are a helpful AI assistant. Answer the user's questions to the best of your ability.`,
    },
  ];

  // Function to start the conversation loop
  const start = () => {
    // Prompt the user for input
    rl.question("You: ", async (userInput) => {
      // Check if the user wants to exit the chat
      if (userInput.toLowerCase() === "exit") {
        rl.close();
        return;
      }

      // Format the user input as a message object
      const userMessage = formatMessage(userInput);

      // Get a response from the OpenAI chat model
      const response = await newMessage(history, userMessage);

      // Update the conversation history with user input and AI response
      history.push(userMessage, response);

      // Display the AI's response
      console.log(`\n\nAI: ${response.content}\n\n`);

      // Continue the conversation loop
      start();
    });
  };

  // Start the initial conversation
  start();
  console.log("\n\nAI: How can I help you today?\n\n");
};

// Display a message indicating that the chatbot is initialized
console.log("Chatbot initialized. Type 'exit' to end the chat.");

// Start the chat function
chat();

Finally, we have a chatbot Like ChatGPT whom we can talk on the terminal, Let's run it!!

npm start //run this command on your terminal and see the magic

If you want to learn more about OpenAI API you can prefer the official doc of OpenAI API

I hope this blog adds some value and if you like it share it with your friends also!!