Quickstart: Sentiment analysis and opinion mining

Reference documentation | More samples | Package (NuGet) | Library source code

Use this quickstart to create a sentiment analysis application with the client library for .NET. In the following example, you create a C# application that can identify the sentiment(s) expressed in a text sample, and perform aspect-based sentiment analysis.

Prerequisites

Setting up

Create an Azure resource

To use the code sample below, you'll need to deploy an Azure resource. This resource will contain a key and endpoint you'll use to authenticate the API calls you send to the Language service.

  1. Use the following link to create a language resource using the Azure portal. You will need to sign in using your Azure subscription.

  2. On the Select additional features screen that appears, select Continue to create your resource.

    A screenshot showing additional feature options in the Azure portal.

  3. In the Create language screen, provide the following information:

    Detail Description
    Subscription The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.
    Resource group A resource group is a container that stores the resources you create. Select Create new to create a new resource group.
    Region The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose East US.
    Name The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.
    Pricing tier The pricing tier for your Language resource. You can use the Free F0 tier to try the service and upgrade later to a paid tier for production.

    A screenshot showing resource creation details in the Azure portal.

  4. Make sure the Responsible AI Notice checkbox is checked.

  5. Select Review + Create at the bottom of the page.

  6. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select Create.

Get your key and endpoint

Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After the Language resource deploys successfully, click the Go to Resource button under Next Steps.

    A screenshot showing the next steps after a resource has deployed.

  2. On the screen for your resource, select Keys and endpoint on the left navigation menu. You will use one of your keys and your endpoint in the steps below.

    A screenshot showing the keys and endpoint section for a resource.

Create environment variables

Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  • To set the LANGUAGE_KEY environment variable, replace your-key with one of the keys for your resource.
  • To set the LANGUAGE_ENDPOINT environment variable, replace your-endpoint with the endpoint for your resource.

Important

If you use an API key, store it securely somewhere else, such as in Azure Key Vault. Don't include the API key directly in your code, and never post it publicly.

For more information about AI services security, see Authenticate requests to Azure AI services.

setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

If you only need to access the environment variables in the current running console, you can set the environment variable with set instead of setx.

After you add the environment variables, you may need to restart any running programs that will need to read the environment variables, including the console window. For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

Create a new .NET Core application

Using the Visual Studio IDE, create a new .NET Core console app. This creates a "Hello World" project with a single C# source file: program.cs.

Install the client library by right-clicking on the solution in the Solution Explorer and selecting Manage NuGet Packages. In the package manager that opens select Browse and search for Azure.AI.TextAnalytics. Select version 5.2.0, and then Install. You can also use the Package Manager Console.

Code example

Copy the following code into your program.cs file and run the code.

using Azure;
using System;
using Azure.AI.TextAnalytics;
using System.Collections.Generic;

namespace Example
{
    class Program
    {
        // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
        static string languageKey = Environment.GetEnvironmentVariable("LANGUAGE_KEY");
        static string languageEndpoint = Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT");

        private static readonly AzureKeyCredential credentials = new AzureKeyCredential(languageKey);
        private static readonly Uri endpoint = new Uri(languageEndpoint);

        // Example method for detecting opinions text. 
        static void SentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
        {
            var documents = new List<string>
            {
                "The food and service were unacceptable. The concierge was nice, however."
            };

            AnalyzeSentimentResultCollection reviews = client.AnalyzeSentimentBatch(documents, options: new AnalyzeSentimentOptions()
            {
                IncludeOpinionMining = true
            });

            foreach (AnalyzeSentimentResult review in reviews)
            {
                Console.WriteLine($"Document sentiment: {review.DocumentSentiment.Sentiment}\n");
                Console.WriteLine($"\tPositive score: {review.DocumentSentiment.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {review.DocumentSentiment.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {review.DocumentSentiment.ConfidenceScores.Neutral:0.00}\n");
                foreach (SentenceSentiment sentence in review.DocumentSentiment.Sentences)
                {
                    Console.WriteLine($"\tText: \"{sentence.Text}\"");
                    Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                    Console.WriteLine($"\tSentence positive score: {sentence.ConfidenceScores.Positive:0.00}");
                    Console.WriteLine($"\tSentence negative score: {sentence.ConfidenceScores.Negative:0.00}");
                    Console.WriteLine($"\tSentence neutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");

                    foreach (SentenceOpinion sentenceOpinion in sentence.Opinions)
                    {
                        Console.WriteLine($"\tTarget: {sentenceOpinion.Target.Text}, Value: {sentenceOpinion.Target.Sentiment}");
                        Console.WriteLine($"\tTarget positive score: {sentenceOpinion.Target.ConfidenceScores.Positive:0.00}");
                        Console.WriteLine($"\tTarget negative score: {sentenceOpinion.Target.ConfidenceScores.Negative:0.00}");
                        foreach (AssessmentSentiment assessment in sentenceOpinion.Assessments)
                        {
                            Console.WriteLine($"\t\tRelated Assessment: {assessment.Text}, Value: {assessment.Sentiment}");
                            Console.WriteLine($"\t\tRelated Assessment positive score: {assessment.ConfidenceScores.Positive:0.00}");
                            Console.WriteLine($"\t\tRelated Assessment negative score: {assessment.ConfidenceScores.Negative:0.00}");
                        }
                    }
                }
                Console.WriteLine($"\n");
            }
        }

        static void Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            SentimentAnalysisWithOpinionMiningExample(client);

            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }

    }
}

Output

Document sentiment: Mixed

    Positive score: 0.47
    Negative score: 0.52
    Neutral score: 0.00

    Text: "The food and service were unacceptable. "
    Sentence sentiment: Negative
    Sentence positive score: 0.00
    Sentence negative score: 0.99
    Sentence neutral score: 0.00

    Target: food, Value: Negative
    Target positive score: 0.00
    Target negative score: 1.00
            Related Assessment: unacceptable, Value: Negative
            Related Assessment positive score: 0.00
            Related Assessment negative score: 1.00
    Target: service, Value: Negative
    Target positive score: 0.00
    Target negative score: 1.00
            Related Assessment: unacceptable, Value: Negative
            Related Assessment positive score: 0.00
            Related Assessment negative score: 1.00
    Text: "The concierge was nice, however."
    Sentence sentiment: Positive
    Sentence positive score: 0.94
    Sentence negative score: 0.05
    Sentence neutral score: 0.01

    Target: concierge, Value: Positive
    Target positive score: 1.00
    Target negative score: 0.00
            Related Assessment: nice, Value: Positive
            Related Assessment positive score: 1.00
            Related Assessment negative score: 0.00

Clean up resources

If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Use the following commands to delete the environment variables you created for this quickstart.

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

Next steps

Reference documentation | Additional samples | Package (Maven) | Library source code

Use this quickstart to create a sentiment analysis application with the client library for Java. In the following example, you will create a Java application that can identify the sentiment(s) expressed in a text sample, and perform aspect-based sentiment analysis.

Prerequisites

Setting up

Create an Azure resource

To use the code sample below, you'll need to deploy an Azure resource. This resource will contain a key and endpoint you'll use to authenticate the API calls you send to the Language service.

  1. Use the following link to create a language resource using the Azure portal. You will need to sign in using your Azure subscription.

  2. On the Select additional features screen that appears, select Continue to create your resource.

    A screenshot showing additional feature options in the Azure portal.

  3. In the Create language screen, provide the following information:

    Detail Description
    Subscription The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.
    Resource group A resource group is a container that stores the resources you create. Select Create new to create a new resource group.
    Region The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose East US.
    Name The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.
    Pricing tier The pricing tier for your Language resource. You can use the Free F0 tier to try the service and upgrade later to a paid tier for production.

    A screenshot showing resource creation details in the Azure portal.

  4. Make sure the Responsible AI Notice checkbox is checked.

  5. Select Review + Create at the bottom of the page.

  6. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select Create.

Get your key and endpoint

Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After the Language resource deploys successfully, click the Go to Resource button under Next Steps.

    A screenshot showing the next steps after a resource has deployed.

  2. On the screen for your resource, select Keys and endpoint on the left navigation menu. You will use one of your keys and your endpoint in the steps below.

    A screenshot showing the keys and endpoint section for a resource.

Create environment variables

Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  • To set the LANGUAGE_KEY environment variable, replace your-key with one of the keys for your resource.
  • To set the LANGUAGE_ENDPOINT environment variable, replace your-endpoint with the endpoint for your resource.

Important

If you use an API key, store it securely somewhere else, such as in Azure Key Vault. Don't include the API key directly in your code, and never post it publicly.

For more information about AI services security, see Authenticate requests to Azure AI services.

setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

If you only need to access the environment variables in the current running console, you can set the environment variable with set instead of setx.

After you add the environment variables, you may need to restart any running programs that will need to read the environment variables, including the console window. For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

Add the client library

Create a Maven project in your preferred IDE or development environment. Then add the following dependency to your project's pom.xml file. You can find the implementation syntax for other build tools online.

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

Code example

Create a Java file named Example.java. Open the file and copy the below code. Then run the code.

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;

public class Example {
    
    // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
    private static String languageKey = System.getenv("LANGUAGE_KEY");
    private static String languageEndpoint = System.getenv("LANGUAGE_ENDPOINT");

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(languageKey, languageEndpoint);
        sentimentAnalysisWithOpinionMiningExample(client);
    }
    // Method to authenticate the client object with your key and endpoint.
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }
    // Example method for detecting sentiment and opinions in text.
    static void sentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
    {
        // The document that needs be analyzed.
        String document = "The food and service were unacceptable. The concierge was nice, however.";

        System.out.printf("Document = %s%n", document);

        AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true);
        final DocumentSentiment documentSentiment = client.analyzeSentiment(document, "en", options);
        SentimentConfidenceScores scores = documentSentiment.getConfidenceScores();
        System.out.printf(
                "Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n",
                documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative());


        documentSentiment.getSentences().forEach(sentenceSentiment -> {
            SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores();
            System.out.printf("\tSentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n",
                    sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative());
            sentenceSentiment.getOpinions().forEach(opinion -> {
                TargetSentiment targetSentiment = opinion.getTarget();
                System.out.printf("\t\tTarget sentiment: %s, target text: %s%n", targetSentiment.getSentiment(),
                        targetSentiment.getText());
                for (AssessmentSentiment assessmentSentiment : opinion.getAssessments()) {
                    System.out.printf("\t\t\t'%s' assessment sentiment because of \"%s\". Is the assessment negated: %s.%n",
                            assessmentSentiment.getSentiment(), assessmentSentiment.getText(), assessmentSentiment.isNegated());
                }
            });
        });
    }
}

Output

Document = The food and service were unacceptable. The concierge was nice, however.
Recognized document sentiment: mixed, positive score: 0.470000, neutral score: 0.000000, negative score: 0.520000.
	Sentence sentiment: negative, positive score: 0.000000, neutral score: 0.000000, negative score: 0.990000.
		Target sentiment: negative, target text: food
			'negative' assessment sentiment because of "unacceptable". Is the assessment negated: false.
		Target sentiment: negative, target text: service
			'negative' assessment sentiment because of "unacceptable". Is the assessment negated: false.
	Sentence sentiment: positive, positive score: 0.940000, neutral score: 0.010000, negative score: 0.050000.
		Target sentiment: positive, target text: concierge
			'positive' assessment sentiment because of "nice". Is the assessment negated: false.

Clean up resources

If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Use the following commands to delete the environment variables you created for this quickstart.

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

Next steps

Reference documentation | Additional samples | Package (npm) | Library source code

Use this quickstart to create a sentiment analysis application with the client library for Node.js. In the following example, you will create a JavaScript application that can identify the sentiment(s) expressed in a text sample, and perform aspect-based sentiment analysis.

Prerequisites

Setting up

Create an Azure resource

To use the code sample below, you'll need to deploy an Azure resource. This resource will contain a key and endpoint you'll use to authenticate the API calls you send to the Language service.

  1. Use the following link to create a language resource using the Azure portal. You will need to sign in using your Azure subscription.

  2. On the Select additional features screen that appears, select Continue to create your resource.

    A screenshot showing additional feature options in the Azure portal.

  3. In the Create language screen, provide the following information:

    Detail Description
    Subscription The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.
    Resource group A resource group is a container that stores the resources you create. Select Create new to create a new resource group.
    Region The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose East US.
    Name The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.
    Pricing tier The pricing tier for your Language resource. You can use the Free F0 tier to try the service and upgrade later to a paid tier for production.

    A screenshot showing resource creation details in the Azure portal.

  4. Make sure the Responsible AI Notice checkbox is checked.

  5. Select Review + Create at the bottom of the page.

  6. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select Create.

Get your key and endpoint

Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After the Language resource deploys successfully, click the Go to Resource button under Next Steps.

    A screenshot showing the next steps after a resource has deployed.

  2. On the screen for your resource, select Keys and endpoint on the left navigation menu. You will use one of your keys and your endpoint in the steps below.

    A screenshot showing the keys and endpoint section for a resource.

Create environment variables

Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  • To set the LANGUAGE_KEY environment variable, replace your-key with one of the keys for your resource.
  • To set the LANGUAGE_ENDPOINT environment variable, replace your-endpoint with the endpoint for your resource.

Important

If you use an API key, store it securely somewhere else, such as in Azure Key Vault. Don't include the API key directly in your code, and never post it publicly.

For more information about AI services security, see Authenticate requests to Azure AI services.

setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

If you only need to access the environment variables in the current running console, you can set the environment variable with set instead of setx.

After you add the environment variables, you may need to restart any running programs that will need to read the environment variables, including the console window. For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

Create a new Node.js application

In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp 

cd myapp

Run the npm init command to create a node application with a package.json file.

npm init

Install the client library

Install the npm packages:

npm install @azure/ai-language-text

Code example

Open the file and copy the below code. Then run the code.

"use strict";

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

// This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
const key = process.env.LANGUAGE_KEY;
const endpoint = process.env.LANGUAGE_ENDPOINT;


//an example document for sentiment analysis and opinion mining
const documents = [{
    text: "The food and service were unacceptable. The concierge was nice, however.",
    id: "0",
    language: "en"
  }];
  
async function main() {
  console.log("=== Sentiment analysis and opinion mining sample ===");

  const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(key));

  const results = await client.analyze("SentimentAnalysis", documents, {
    includeOpinionMining: true,
  });

  for (let i = 0; i < results.length; i++) {
    const result = results[i];
    console.log(`- Document ${result.id}`);
    if (!result.error) {
      console.log(`\tDocument text: ${documents[i].text}`);
      console.log(`\tOverall Sentiment: ${result.sentiment}`);
      console.log("\tSentiment confidence scores:", result.confidenceScores);
      console.log("\tSentences");
      for (const { sentiment, confidenceScores, opinions } of result.sentences) {
        console.log(`\t- Sentence sentiment: ${sentiment}`);
        console.log("\t  Confidence scores:", confidenceScores);
        console.log("\t  Mined opinions");
        for (const { target, assessments } of opinions) {
          console.log(`\t\t- Target text: ${target.text}`);
          console.log(`\t\t  Target sentiment: ${target.sentiment}`);
          console.log("\t\t  Target confidence scores:", target.confidenceScores);
          console.log("\t\t  Target assessments");
          for (const { text, sentiment } of assessments) {
            console.log(`\t\t\t- Text: ${text}`);
            console.log(`\t\t\t  Sentiment: ${sentiment}`);
          }
        }
      }
    } else {
      console.error(`\tError: ${result.error}`);
    }
  }
}
  
main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Output

=== Sentiment analysis and opinion mining sample ===
- Document 0
    Document text: The food and service were unacceptable. The concierge was nice, however.
    Overall Sentiment: mixed
    Sentiment confidence scores: { positive: 0.49, neutral: 0, negative: 0.5 }
    Sentences
    - Sentence sentiment: negative
      Confidence scores: { positive: 0, neutral: 0, negative: 1 }
      Mined opinions
            - Target text: food
              Target sentiment: negative
              Target confidence scores: { positive: 0.01, negative: 0.99 }
              Target assessments
                    - Text: unacceptable
                      Sentiment: negative
            - Target text: service
              Target sentiment: negative
              Target confidence scores: { positive: 0.01, negative: 0.99 }
              Target assessments
                    - Text: unacceptable
                      Sentiment: negative
    - Sentence sentiment: positive
      Confidence scores: { positive: 0.98, neutral: 0.01, negative: 0.01 }
      Mined opinions
            - Target text: concierge
              Target sentiment: positive
              Target confidence scores: { positive: 1, negative: 0 }
              Target assessments
                    - Text: nice
                      Sentiment: positive

Clean up resources

If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Use the following commands to delete the environment variables you created for this quickstart.

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

Next steps

Reference documentation | Additional samples | Package (PyPi) | Library source code

Use this quickstart to create a sentiment analysis application with the client library for Python. In the following example, you will create a Python application that can identify the sentiment(s) expressed in a text sample, and perform aspect-based sentiment analysis.

Prerequisites

Setting up

Create an Azure resource

To use the code sample below, you'll need to deploy an Azure resource. This resource will contain a key and endpoint you'll use to authenticate the API calls you send to the Language service.

  1. Use the following link to create a language resource using the Azure portal. You will need to sign in using your Azure subscription.

  2. On the Select additional features screen that appears, select Continue to create your resource.

    A screenshot showing additional feature options in the Azure portal.

  3. In the Create language screen, provide the following information:

    Detail Description
    Subscription The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.
    Resource group A resource group is a container that stores the resources you create. Select Create new to create a new resource group.
    Region The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose East US.
    Name The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.
    Pricing tier The pricing tier for your Language resource. You can use the Free F0 tier to try the service and upgrade later to a paid tier for production.

    A screenshot showing resource creation details in the Azure portal.

  4. Make sure the Responsible AI Notice checkbox is checked.

  5. Select Review + Create at the bottom of the page.

  6. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select Create.

Get your key and endpoint

Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After the Language resource deploys successfully, click the Go to Resource button under Next Steps.

    A screenshot showing the next steps after a resource has deployed.

  2. On the screen for your resource, select Keys and endpoint on the left navigation menu. You will use one of your keys and your endpoint in the steps below.

    A screenshot showing the keys and endpoint section for a resource.

Create environment variables

Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  • To set the LANGUAGE_KEY environment variable, replace your-key with one of the keys for your resource.
  • To set the LANGUAGE_ENDPOINT environment variable, replace your-endpoint with the endpoint for your resource.

Important

If you use an API key, store it securely somewhere else, such as in Azure Key Vault. Don't include the API key directly in your code, and never post it publicly.

For more information about AI services security, see Authenticate requests to Azure AI services.

setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

If you only need to access the environment variables in the current running console, you can set the environment variable with set instead of setx.

After you add the environment variables, you may need to restart any running programs that will need to read the environment variables, including the console window. For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

Install the client library

After installing Python, you can install the client library with:

pip install azure-ai-textanalytics==5.2.0

Code example

Create a new Python file and copy the below code. Then run the code

# This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
language_key = os.environ.get('LANGUAGE_KEY')
language_endpoint = os.environ.get('LANGUAGE_ENDPOINT')

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(language_key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=language_endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for detecting sentiment and opinions in text 
def sentiment_analysis_with_opinion_mining_example(client):

    documents = [
        "The food and service were unacceptable. The concierge was nice, however."
    ]

    result = client.analyze_sentiment(documents, show_opinion_mining=True)
    doc_result = [doc for doc in result if not doc.is_error]

    positive_reviews = [doc for doc in doc_result if doc.sentiment == "positive"]
    negative_reviews = [doc for doc in doc_result if doc.sentiment == "negative"]

    positive_mined_opinions = []
    mixed_mined_opinions = []
    negative_mined_opinions = []

    for document in doc_result:
        print("Document Sentiment: {}".format(document.sentiment))
        print("Overall scores: positive={0:.2f}; neutral={1:.2f}; negative={2:.2f} \n".format(
            document.confidence_scores.positive,
            document.confidence_scores.neutral,
            document.confidence_scores.negative,
        ))
        for sentence in document.sentences:
            print("Sentence: {}".format(sentence.text))
            print("Sentence sentiment: {}".format(sentence.sentiment))
            print("Sentence score:\nPositive={0:.2f}\nNeutral={1:.2f}\nNegative={2:.2f}\n".format(
                sentence.confidence_scores.positive,
                sentence.confidence_scores.neutral,
                sentence.confidence_scores.negative,
            ))
            for mined_opinion in sentence.mined_opinions:
                target = mined_opinion.target
                print("......'{}' target '{}'".format(target.sentiment, target.text))
                print("......Target score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
                    target.confidence_scores.positive,
                    target.confidence_scores.negative,
                ))
                for assessment in mined_opinion.assessments:
                    print("......'{}' assessment '{}'".format(assessment.sentiment, assessment.text))
                    print("......Assessment score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
                        assessment.confidence_scores.positive,
                        assessment.confidence_scores.negative,
                    ))
            print("\n")
        print("\n")
          
sentiment_analysis_with_opinion_mining_example(client)

Output

Document Sentiment: mixed
Overall scores: positive=0.47; neutral=0.00; negative=0.52

Sentence: The food and service were unacceptable.
Sentence sentiment: negative
Sentence score:
Positive=0.00
Neutral=0.00
Negative=0.99

......'negative' target 'food'
......Target score:
......Positive=0.00
......Negative=1.00

......'negative' assessment 'unacceptable'
......Assessment score:
......Positive=0.00
......Negative=1.00

......'negative' target 'service'
......Target score:
......Positive=0.00
......Negative=1.00

......'negative' assessment 'unacceptable'
......Assessment score:
......Positive=0.00
......Negative=1.00



Sentence: The concierge was nice, however.
Sentence sentiment: positive
Sentence score:
Positive=0.94
Neutral=0.01
Negative=0.05

......'positive' target 'concierge'
......Target score:
......Positive=1.00
......Negative=0.00

......'positive' assessment 'nice'
......Assessment score:
......Positive=1.00
......Negative=0.00

Clean up resources

If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Use the following commands to delete the environment variables you created for this quickstart.

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

Next steps

Reference documentation

Use this quickstart to send sentiment analysis requests using the REST API. In the following example, you'll use cURL to identify the sentiment(s) expressed in a text sample, and perform aspect-based sentiment analysis.

Prerequisites

Setting up

Create an Azure resource

To use the code sample below, you'll need to deploy an Azure resource. This resource will contain a key and endpoint you'll use to authenticate the API calls you send to the Language service.

  1. Use the following link to create a language resource using the Azure portal. You will need to sign in using your Azure subscription.

  2. On the Select additional features screen that appears, select Continue to create your resource.

    A screenshot showing additional feature options in the Azure portal.

  3. In the Create language screen, provide the following information:

    Detail Description
    Subscription The subscription account that your resource will be associated with. Select your Azure subscription from the drop-down menu.
    Resource group A resource group is a container that stores the resources you create. Select Create new to create a new resource group.
    Region The location of your Language resource. Different regions may introduce latency depending on your physical location, but have no impact on the runtime availability of your resource. For this quickstart, either select an available region near you, or choose East US.
    Name The name for your Language resource. This name will also be used to create an endpoint URL that your applications will use to send API requests.
    Pricing tier The pricing tier for your Language resource. You can use the Free F0 tier to try the service and upgrade later to a paid tier for production.

    A screenshot showing resource creation details in the Azure portal.

  4. Make sure the Responsible AI Notice checkbox is checked.

  5. Select Review + Create at the bottom of the page.

  6. In the screen that appears, make sure the validation has passed, and that you entered your information correctly. Then select Create.

Get your key and endpoint

Next you will need the key and endpoint from the resource to connect your application to the API. You'll paste your key and endpoint into the code later in the quickstart.

  1. After the Language resource deploys successfully, click the Go to Resource button under Next Steps.

    A screenshot showing the next steps after a resource has deployed.

  2. On the screen for your resource, select Keys and endpoint on the left navigation menu. You will use one of your keys and your endpoint in the steps below.

    A screenshot showing the keys and endpoint section for a resource.

Create environment variables

Your application must be authenticated to send API requests. For production, use a secure way of storing and accessing your credentials. In this example, you will write your credentials to environment variables on the local machine running the application.

To set the environment variable for your Language resource key, open a console window, and follow the instructions for your operating system and development environment.

  • To set the LANGUAGE_KEY environment variable, replace your-key with one of the keys for your resource.
  • To set the LANGUAGE_ENDPOINT environment variable, replace your-endpoint with the endpoint for your resource.

Important

If you use an API key, store it securely somewhere else, such as in Azure Key Vault. Don't include the API key directly in your code, and never post it publicly.

For more information about AI services security, see Authenticate requests to Azure AI services.

setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

If you only need to access the environment variables in the current running console, you can set the environment variable with set instead of setx.

After you add the environment variables, you may need to restart any running programs that will need to read the environment variables, including the console window. For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

Create a JSON file with the example request body

In a code editor, create a new file named test_sentiment_payload.json and copy the following JSON example. This example request will be sent to the API in the next step.

{
	"kind": "SentimentAnalysis",
	"parameters": {
		"modelVersion": "latest",
		"opinionMining": "True"
	},
	"analysisInput":{
		"documents":[
			{
				"id":"1",
				"language":"en",
				"text": "The food and service were unacceptable. The concierge was nice, however."
			}
		]
	}
} 

Save test_sentiment_payload.json somewhere on your computer. For example, your desktop.

Send a sentiment analysis and opinion mining API request

Note

The below examples include a request for the opinion mining feature of sentiment analysis, which provides granular information about assessments (adjectives) related to targets (nouns) in the text.

Use the following commands to send the API request using the program you're using. Copy the command into your terminal, and run it.

parameter Description
-X POST <endpoint> Specifies your endpoint for accessing the API.
-H Content-Type: application/json The content type for sending JSON data.
-H "Ocp-Apim-Subscription-Key:<key> Specifies the key for accessing the API.
-d <documents> The JSON file containing the documents you want to send.

Replace C:\Users\<myaccount>\Desktop\test_sentiment_payload.json with the location of the example JSON request file you created in the previous step.

Command prompt

curl -X POST "%LANGUAGE_ENDPOINT%/language/:analyze-text?api-version=2023-04-15-preview" ^
-H "Content-Type: application/json" ^
-H "Ocp-Apim-Subscription-Key: %LANGUAGE_KEY%" ^
-d "@C:\Users\<myaccount>\Desktop\test_sentiment_payload.json"

PowerShell

curl.exe -X POST $env:LANGUAGE_ENDPOINT/language/:analyze-text?api-version=2023-04-15-preview `
-H "Content-Type: application/json" `
-H "Ocp-Apim-Subscription-Key: $env:LANGUAGE_KEY" `
-d "@C:\Users\<myaccount>\Desktop\test_sentiment_payload.json"

JSON response

{
	"kind": "SentimentAnalysisResults",
	"results": {
		"documents": [{
			"id": "1",
			"sentiment": "mixed",
			"confidenceScores": {
				"positive": 0.47,
				"neutral": 0.0,
				"negative": 0.52
			},
			"sentences": [{
				"sentiment": "negative",
				"confidenceScores": {
					"positive": 0.0,
					"neutral": 0.0,
					"negative": 0.99
				},
				"offset": 0,
				"length": 40,
				"text": "The food and service were unacceptable. ",
				"targets": [{
					"sentiment": "negative",
					"confidenceScores": {
						"positive": 0.0,
						"negative": 1.0
					},
					"offset": 4,
					"length": 4,
					"text": "food",
					"relations": [{
						"relationType": "assessment",
						"ref": "#/documents/0/sentences/0/assessments/0"
					}]
				}, {
					"sentiment": "negative",
					"confidenceScores": {
						"positive": 0.0,
						"negative": 1.0
					},
					"offset": 13,
					"length": 7,
					"text": "service",
					"relations": [{
						"relationType": "assessment",
						"ref": "#/documents/0/sentences/0/assessments/0"
					}]
				}],
				"assessments": [{
					"sentiment": "negative",
					"confidenceScores": {
						"positive": 0.0,
						"negative": 1.0
					},
					"offset": 26,
					"length": 12,
					"text": "unacceptable",
					"isNegated": false
				}]
			}, {
				"sentiment": "positive",
				"confidenceScores": {
					"positive": 0.94,
					"neutral": 0.01,
					"negative": 0.05
				},
				"offset": 40,
				"length": 32,
				"text": "The concierge was nice, however.",
				"targets": [{
					"sentiment": "positive",
					"confidenceScores": {
						"positive": 1.0,
						"negative": 0.0
					},
					"offset": 44,
					"length": 9,
					"text": "concierge",
					"relations": [{
						"relationType": "assessment",
						"ref": "#/documents/0/sentences/1/assessments/0"
					}]
				}],
				"assessments": [{
					"sentiment": "positive",
					"confidenceScores": {
						"positive": 1.0,
						"negative": 0.0
					},
					"offset": 58,
					"length": 4,
					"text": "nice",
					"isNegated": false
				}]
			}],
			"warnings": []
		}],
		"errors": [],
		"modelVersion": "2022-06-01"
	}
}

Clean up resources

If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Use the following commands to delete the environment variables you created for this quickstart.

reg delete "HKCU\Environment" /v LANGUAGE_KEY /f
reg delete "HKCU\Environment" /v LANGUAGE_ENDPOINT /f

Next steps