Skip to content

How To Implement ChatGPT In NodeJS with axios

  • by

To implement ChatGPT in Node.js, you can use the OpenAI API to make requests to the GPT-3.5 model. In this tutorial, we will show very basic setup.

Implement ChatGPT In NodeJS example

1. Inside this new project folder create a new package.json file by using the npm command in the following way:

npm init -y

2. Install the axios package to make HTTP requests from Node.js:

npm install axios

3. Create a JavaScript file for your ChatGPT implementation and import the axios package:

const axios = require('axios');

4. Define a function that makes a request to the OpenAI API with your API key and a prompt:

async function getChatResponse(prompt) {
  const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
    prompt: prompt,
    max_tokens: 60,
    n: 1,
    stop: '\n',
  }, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY,
    },
  });
  return response.data;// .choices[0].text.trim()
}

5. Run code.

node app.js

Output:

How To Implement ChatGPT In NodeJS

Sign up or sign in for OpenAI API access and get your API key.

https://platform.openai.com/account/api-keys

OpenAI API access and get your API key.

You can customize the prompt, max_tokens, and stop parameters to generate different kinds of responses. You can also integrate the ChatGPT function with other parts of your Node.js application to create more complex behavior.

Comment if you have any doubts or suggestions on this Node Js CHAT GPT topic.

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