In the digital landscape, getting access to actionable data, particularly specific insights about your customers, can put you well ahead of the competition.

Sentiment analysis has become a popular strategy since it generates reliable results. You can use it to programmatically identify people's views and perceptions of your product. You can discover other important data points that you can use to make key business decisions.

With tools like OpenAI's APIs, you can analyze and generate detailed and actionable insights about your customers. Read on to learn how to integrate its advanced tweet classifier API to analyze users' inputs.

An Introduction to GPT

OpenAI's Generative Pre-trained Transformer (GPT-3) is a large language model trained on huge amounts of text data, giving it the ability quickly generate responses to any query fed into it. It utilizes natural language processing techniques to understand and process the queries users' prompts.

OpenAI's GPT-3 Overview page

GPT-3 has gained popularity due to its ability to process user prompts and respond in a conversational format.

This model is particularly essential in sentiment analysis since you can use it to accurately assess and determine customers' sentiment towards products, your brand, and other key metrics.

Dive Into Sentiment Analysis Using GPT

Sentiment analysis is a natural language processing task that involves identifying and categorizing the sentiment expressed in textual data such as sentences and paragraphs.

GPT can process sequential data making it possible to analyze the sentiments. The entire analysis process involves training the model with large datasets of labeled text data that are categorized as either positive, negative, or neutral.

Robot hand illustration

You can then use a trained model to determine the sentiment of new text data. Essentially, the model learns to identify sentiments by analyzing patterns and structures of text. It then categorizes it and generates a response.

Furthermore, GPT can be fine-tuned to assess data from niche domains, such as social media or customer feedback. This helps improve its accuracy in specific contexts by training the model with sentiment expressions unique to that particular domain.

Integrated OpenAI Advanced Tweet Classifier

This API uses natural language processing techniques to analyze text data such as messages or tweets to determine if they have positive, negative, or neutral sentiments.

For example, if a text has a positive tone, the API will categorize it as "positive" otherwise, it'll be labeled as "negative" or "neutral".

Moreover, you can customize the categories and use more specific words to describe the sentiment. For instance, instead of simply labeling particular text data as "positive", you could choose a more descriptive category like "happy".

Configure the Advanced Tweet Classifier

To get started, head over to OpenAI's Developer Console, and sign up for an account. You will need your API key to interact with the advanced tweet classifier API from your React application.

On the overview page, click on the Profile button in the top right, and select View API keys.

OpenAI settings

Then click on Create new secret key to generate a new API key for your application. Make sure to take a copy of the key for use in the next step.

Create a React Client

Quickly bootstrap your React project locally. Next, in the root directory of your project folder, create a .env file to hold your API secret key.

        REACT_APP_OPEN_AI_API_KEY='your API key'
    

You can find this project's code in this GitHub repository.

Configure the App.js Component

Open the src/App.js file, delete the boilerplate React code, and replace it with the following:

  1. Make the following imports:
            import './App.css';
    import React, {useState} from 'react';
  2. Define the functional App component and the state variables to hold a user's message and its sentiment after the analysis.
            function App() {
      const [message, setMessage] = useState("");
      const [sentiment, setSentiment] = useState("");
  3. Create a handler function that will make asynchronous POST HTTP requests to the Advanced Tweet Classifier passing along the user's message and the API key in the request body to analyze the sentiments.
  4. The function will then await the response from the API, parse it as JSON, and extract the sentiment value in the choices array from the parsed data.
  5. Lastly, the handler function will trigger the setSentiment function to update its state with the sentiment value.
              const API_KEY = process.env.REACT_APP_OPEN_AI_API_KEY;

      const APIBODY ={
        'model': "text-davinci-003",
        'prompt': "What is the sentiment of this message?" + message,
        'max_tokens': 60,
        'top_p': 1.0,
        'frequency_penalty': 0.0,
        'presence_penalty': 0.0,
      }

      async function handleClick() {
        await fetch('https://api.openai.com/v1/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'authorization': `Bearer ${API_KEY}`
          },
          body: JSON.stringify(APIBODY)
        }).then(response => {
          return response.json()
        }).then((data) => {
          console.log(data);
          setSentiment(data.choices[0].text.trim());
        }).catch((error) => {
          console.error(error);
        });
      };

The request body contains a few parameters, these are:

  • model: specifies which OpenAI model to use; text-davinci-003 in this case.
  • prompt: the prompt that you'll use to analyze the sentiment of the given message.
  • max_tokens: specifies the maximum number of tokens fed into the model to prevent excessive or unnecessary usage of the model's computing power and improve its overall performance.
  • top_p, frequency_penalty, and presence_penalty: these parameters adjust the model's output.

Finally, return the message box and the submit button:

          return (
    <div className="App">
      <header className="App-header">
        <h2> Sentiment Analysis Application</h2>
        <div className="input">
          <p> Enter the message to classify </p>

          <textarea
            className="textArea"
            type="text"
            placeholder="Type your message..."
            cols={50}
            rows={10}
            onChange={(e) => setMessage(e.target.value)}
          />
        </div>

        <div className="Response">
          <button onClick={handleClick}> Get Message sentiment</button>
          {sentiment !== "" ? <p> The message is {sentiment} </p> : null}
        </div>
      </header>
    </div>
  );
}

export default App;

Create a User Prompt

You can optionally, create a prompt input field to allow you to define how to analyze the message.

For instance, instead of getting "positive" as the sentiment for a particular message, you can instruct the model to generate responses and rank them on a scale of one to ten, where one is extremely negative while ten is extremely positive.

Add this code to the App.js component. Define a state variable for the prompt:

          const [prompt, setPrompt] = useState("");
    

Modify the prompt on the APIBODY to use the prompt variable data:

          const APIBODY = {
    // ...
    'prompt': prompt + message,
    // ...
  }

Add a prompt input field, just above the message textarea:

          <input 
      className="prompt"
       type="text"
       placeholder="Enter prompt..."
       onChange={(e) => setPrompt(e.target.value)}
  />

Spin up the development server to update the changes made and head over to http://localhost:3000 to test out the functionality.

Sentiment Analysis Application

Sentiment Analysis Using AI Tools

Sentiment analysis is an essential business practice that can provide valuable insights into the experiences and opinions of your customers, enabling you to make informed decisions that can lead to improved customer experiences and increased revenue.

With the help of AI tools such as OpenAI APIs, you can streamline your analysis pipelines to get accurate and reliable customer sentiments in real time.