Skip to content

Implement ChatGPT in NodeJS with openai-api

  • by

To implement ChatGPT in NodeJS, you can use the OpenAI API to connect to the GPT-3.5 model and send requests to generate text.

This code snippet uses the openai-api package to connect to the OpenAI API using your API key. To implement ChatGPT in NodeJS with OpenAI API, you will need to follow the below steps:

1. Install NodeJS and npm (Node Package Manager) on your computer.

Read this tutorial: NodeJs Hello World

2. Create a new directory for your project and navigate to it in the terminal.

3. Use npm to initialize a new NodeJS project:

npm init

4. Install the openai package by running the following command:

npm install openai
npm install openai-api

5. Create an OpenAI API key from the OpenAI dashboard. : https://platform.openai.com/account/api-keys

OpenAI API key

6. Create a new file called chat.js (or whatever you want to call it) in your project directory.

7. Initialize the OpenAI API client in your NodeJS application using the following code:

const openai = require('openai-api');

// Set your OpenAI API key
const OPENAI_API_KEY = 'ADD_YOUR';
const client = new openai(OPENAI_API_KEY);

8. Now, you can use the client object to interact with the OpenAI API. For example, to generate text using the GPT-3 model, you can use the complete method is shown below:

Here is Compete code.

const openai = require('openai-api');

// Set your OpenAI API key
const OPENAI_API_KEY = 'ADD_YOUR';
const client = new openai(OPENAI_API_KEY);

// Set the model to use
const model = 'text-davinci-002';

// Set the prompt to start the conversation
const prompt = 'Hello, how can I assist you today?';

// Set the temperature of the response (0 = deterministic, 1 = very creative)
const temperature = 0.5;

// Create a function to send a message to the model and receive a response
async function sendMessage(message) {
  const promptWithMessage = prompt + '\nUser: ' + message + '\nAI:';

  const response = await client.complete({
    engine: model,
    prompt: promptWithMessage,
    maxTokens: 1024,
    temperature: temperature,
  });

  const answer = response.data.choices[0].text;
  return answer;
}

// Example conversation loop
(async () => {
  let message = '';
  while (message.toLowerCase() !== 'exit') {
    message = await askQuestion();
    if (message.toLowerCase() !== 'exit') {
      const response = await sendMessage(message);
      console.log('AI: ' + response);
    }
  }
})();

// Create a function to get user input from the console
function askQuestion() {
  const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  return new Promise((resolve, reject) => {
    readline.question('You: ', (message) => {
      readline.close();
      resolve(message);
    });
  });
}

This code is a Node.js script that demonstrates how to use the OpenAI API to create a simple chatbot that can hold a conversation with a user via the console.

9. Run the app.js file with NodeJS:

Node app.js

Output: Here is the command line chat screenshot.

Implement ChatGPT in NodeJS with openai-api

Video tutorial

This is the basic code of node js and chatbot, do comment if you have any doubts or suggestions on this.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading