Building a Sentiment Analysis API with OpenAI and Express

Joshua Agbomeikhe
5 min readFeb 11, 2023

--

Full code on Github

Welcome to the world of sentiment analysis, where we decode emotions and feelings from text just like a psychic decodes secret messages!

Gone are the days when businesses had to rely on a team of mind readers to understand the emotions of their customers. With the power of AI, we can now do that with just a few lines of code! In this article, we’ll be showcasing how you can build your very own sentiment analysis AI using OpenAI and Express.js. Just imagine, with this AI by your side, you’ll be able to sense the mood of your customers with a single glance!

So go ahead, give it a try, and let us know how your AI did. Who knows, it might just become the next big thing in the world of sentiment analysis!

Setting up the Environment

Before we start building our AI, we need to set up our environment. To do this, we’ll use Node.js and npm. If you don’t have Node.js and npm installed, you can download them from the official Node.js website.

Next, we’ll create a new project folder and navigate to it in the terminal. We’ll then run the following command to create a new Node.js project:

npm init

This will create a package.json file in our project folder. This file contains information about our project and its dependencies.

Installing Dependencies
We’ll need to install the following dependencies to build our sentiment analysis AI:

Express.js: A fast, unopinionated, minimalist web framework for Node.js.
Body-Parser: A Node.js body parsing middleware.
OpenAI: A JavaScript client for the OpenAI API.
Dotenv: A zero-dependency module that loads environment variables from a .env file.
To install these dependencies, run the following command in the terminal:

npm install express body-parser openai dotenv

Setting up OpenAI
To use the OpenAI API, we need to sign up for an API key. You can sign up for a free API key on the OpenAI website. Once you have your API key, create a .env file in the root of your project and add the following line to it:

OPENAI_API_KEY=your_api_key_here

Writing the Code

Now that our environment is set up, we can start writing the code for our sentiment analysis AI. In our index.js, We’ll start by importing the necessary modules and setting up the Express app:

const express = require("express");

// Import the dotenv module for accessing environment variables
const dotenv = require("dotenv");
dotenv.config();

// Import the body-parser module for parsing incoming request bodies
const bp = require("body-parser");

// Create a new Express app
const app = express();

// Use the body-parser middleware to parse incoming request bodies as JSON and URL encoded data
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));

Next, we’ll set up the OpenAI API client:

// Import and set up the OpenAI API client
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

Now, we’ll define a sentiment analysis prompt that we’ll use to analyze the sentiment of the text:

// Define a sentiment analysis prompt
const sentimentAnalysisPrompt = "Please classify the sentiment expressed in the following sentence as positive, neutral or negative. More information should be provided on the mood and tone: ";

Finally, we’ll define an endpoint to handle incoming requests and call the OpenAI API to analyze the sentiment of the text and then start the Express app:

// Define an endpoint to handle incoming requests
app.post("/sentiment", (req, res) => {
// Extract the text from the request body
const text = req.body.text;

// Call the OpenAI API to analyze the sentiment of the text
openai
.createCompletion({
model: "text-davinci-003",
prompt: sentimentAnalysisPrompt + text + ".",
temperature: 0,
max_tokens: 60,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
.then((response) => {
// Parse the sentiment from the API response
const sentiment = response.data.choices[0]["text"];

// Send the sentiment back to the client
res.send({ sentiment });
});
});

// Start the Express app and listen on port 3000
app.listen(3000, () => {
console.log("Sentiment analysis AI listening on port 3000");
});

And with that, our sentiment analysis AI is ready to go! Just start the Express app and watch as your AI decodes emotions from text like a min reader!

Your index.js should now look like this:

const express = require("express");

// Import the dotenv module for accessing environment variables
const dotenv = require("dotenv");
dotenv.config();

// Import the body-parser module for parsing incoming request bodies
const bp = require("body-parser");

// Create a new Express app
const app = express();

// Use the body-parser middleware to parse incoming request bodies as JSON and URL encoded data
app.use(bp.json());
app.use(bp.urlencoded({ extended: true }));

// Import and set up the OpenAI API client
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

// Define a sentiment analysis prompt
const sentimentAnalysisPrompt = "Please classify the sentiment expressed in the following sentence as positive, neutral or negative. More information should be provided on the mood and tone: ";

// Define an endpoint to handle incoming requests
app.post("/sentiment", (req, res) => {
// Extract the text from the request body
const text = req.body.text;

// Call the OpenAI API to analyze the sentiment of the text
openai
.createCompletion({
model: "text-davinci-003",
prompt: sentimentAnalysisPrompt + text + ".",
temperature: 0,
max_tokens: 60,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
.then((response) => {
// Parse the sentiment from the API response
const sentiment = response.data.choices[0]["text"];

// Send the sentiment back to the client
res.send({ sentiment });
});
});

// Start the Express app and listen on port 3000
app.listen(3000, () => {
console.log("Sentiment analysis AI listening on port 3000");
});

Usage & Testing

Start the app by running the following command in the terminal:

node index.js

You can now make a POST request to the /sentiment endpoint with a text field in the request body to get the sentiment analysis. For example, you can use Postman or cURL to make a request like this:

curl -X POST http://localhost:3000/sentiment -H 'Content-Type: application/json' -d '{"text": "This is an amazing day!"}'

The API will return the sentiment analysis of the text in the response body, like this:

{"sentiment": "positive"}

So go ahead, give it a try, and let us know how your AI did. Who knows, it might just become the next big thing in the world of sentiment analysis!

--

--

Joshua Agbomeikhe
Joshua Agbomeikhe

Written by Joshua Agbomeikhe

Just a Node.js Chef and an AI enthusiast, nothing more!

No responses yet