Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sentiment Analysis using OpenAI API

Introduction

Sentiment analysis with the OpenAI API allows you to determine the sentiment of a given text, whether it's positive, negative, or neutral. This tutorial covers how to use the sentiment analysis endpoint effectively, its parameters, and examples in JavaScript and Python.

Endpoint Overview

The sentiment analysis endpoint leverages advanced AI models to analyze the sentiment of a given piece of text.

Using the Sentiment Analysis Endpoint

API Request

To analyze the sentiment, send a POST request to the endpoint URL with your API key and the text.

POST /v1/engines/text-davinci-003/completions HTTP/1.1
Host: api.openai.com
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
    "prompt": "Analyze the sentiment of the following text: 'I am extremely happy with the service.'",
    "max_tokens": 10
}
                    

In this example, a sentiment analysis is performed on the text: "I am extremely happy with the service."

API Response

The API responds with the sentiment analysis result.

HTTP/1.1 200 OK
Content-Type: application/json

{
    "choices": [
        {
            "text": "\nSentiment: Positive",
            "index": 0,
            "logprobs": null,
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 20,
        "completion_tokens": 10,
        "total_tokens": 30
    }
}
                    

The response includes the sentiment analysis result, indicating whether the sentiment is positive, negative, or neutral.

Parameters

Here are some common parameters you can use with the sentiment analysis endpoint:

  • prompt: The text for which you want to analyze the sentiment.
  • max_tokens: The maximum number of tokens to generate in the response.

Examples in JavaScript

Here's how you can use the sentiment analysis endpoint in JavaScript:

const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const endpoint = 'https://api.openai.com/v1/engines/text-davinci-003/completions';

async function analyzeSentiment(text) {
    try {
        const response = await axios.post(endpoint, {
            prompt: `Analyze the sentiment of the following text: '${text}'`,
            max_tokens: 10
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            }
        });

        console.log(response.data.choices[0].text.trim());
    } catch (error) {
        console.error('Error:', error);
    }
}

analyzeSentiment('I am extremely happy with the service.');
                

Examples in Python

Here's how you can use the sentiment analysis endpoint in Python:

import requests
import json

api_key = 'YOUR_API_KEY'
endpoint = 'https://api.openai.com/v1/engines/text-davinci-003/completions'

def analyze_sentiment(text):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    data = {
        'prompt': f"Analyze the sentiment of the following text: '{text}'",
        'max_tokens': 10
    }

    response = requests.post(endpoint, headers=headers, data=json.dumps(data))
    if response.status_code == 200:
        sentiment = response.json()['choices'][0]['text'].strip()
        print(sentiment)
    else:
        print(f"Error: {response.status_code}, {response.text}")

analyze_sentiment('I am extremely happy with the service.');
                

Conclusion

The sentiment analysis endpoint in the OpenAI API provides a powerful tool to analyze the sentiment of a given text. By understanding its usage, parameters, and seeing examples in JavaScript and Python, you can integrate sentiment analysis seamlessly into various applications for better understanding of user feedback and sentiment.