Building a Node.js Application with OpenAI API Integration

ChatGpt Integration with Nodejs using openai

Rohit Lingayat
2 min readMay 9, 2023

OpenAI API is a powerful tool for building applications that can perform natural language processing tasks like language generation, sentiment analysis, and question answering. In this tutorial, we will explore how to integrate the OpenAI API with a Node.js application.

Prerequisites

Before we start, you will need to install following things:

  • Node.js
  • NPM (Node Package Manager)
  • An OpenAI API key

Getting Started

To get started, create a new Node.js project using NPM. Open your terminal and run the following command:

npm init

This will create a new package.json file in your project directory. Next, install the required packages:

npm install express dotenv openai

We are installing express to create a web server, dotenv to load environment variables, and openai to use the OpenAI API.

Configuring Environment Variables

To keep sensitive information like API keys out of the codebase, we will use environment variables. Create a .env file in the root directory of your project and add the following line:

OPENAI_API_KEY=<your-api-key>

Replace <your-api-key> with your actual OpenAI API key.

Creating the Server

Create a new file index.js in the root directory of your project and add the following code:

import express from 'express';
import { config } from 'dotenv';
import { Configuration, OpenAIApi } from 'openai';

// Load environment variables
config();

// Create a web server
const app = express();
const port = process.env.PORT || 3034;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

// Initialize OpenAI API
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

// Define a route to handle questions
app.get('/ask-me', async (req, res) => {
// Call the OpenAI API to generate an answer
const completion = await openai.createCompletion({
model: 'text-davinci-003',
prompt: req.query.question,
});
res.send(completion.data.choices[0].text);
});

Let’s go through this code step by step:

  • We import the necessary packages, including express, dotenv, and openai.
  • We load the environment variables from the .env file using dotenv.
  • We create a new web server using express and listen on the port defined in the environment variable PORT or 3034 if not defined.
  • We initialise the OpenAI API with the API key loaded from the environment variable OPENAI_API_KEY.
  • We define a route /ask-me that accepts a query parameter question. When this route is called, we use the OpenAI API to generate an answer to the given question and return it as a response.

This will start the server and output Server running on port 3034. Now open your browser and go to http://localhost:3034/ask-me?question=capital of kinda?. You should see the answer "The capital of India is New Delhi." displayed in the browser.

Congratulations, you have successfully integrated the OpenAI API with a Node.js application! 🍻

References

--

--

Rohit Lingayat

Ruby on Rails | React | AWS | Solr | JQuery | Nodejs | Typescript