Sentiment analysis using Gemini AI with ABAP SDK

1. Introduction

In this codelab, you'll use the Gemini Pro model to perform sentiment analysis on product reviews with ABAP SDK for Google Cloud. We will go through the steps to set up authentication to access Google Cloud Vertex AI API using tokens when your SAP system is hosted on a Compute Engine VM instance.

The list of services used are:

  • Compute Engine
  • Network Services
  • Cloud Shell
  • Vertex AI

What you'll build

You'll perform the following:

  • Configure the ABAP SDK installed on the SAP system to connect to Google APIs.
  • Create an example report program to call Gemini AI and perform sentiment analysis on product reviews.

2. Requirements

  • A browser, such as Chrome or Firefox.
  • A Google Cloud project with billing enabled or Create a 90-Day Free Trial account for Google Cloud Platform.
  • SAP GUI (Windows or Java) installed in your system. If SAP GUI is already installed on your system, connect to SAP using the VM external IP address as the Application Server IP. If you are on Mac then you can also install the SAP GUI for Java available in this link.

3. Before you begin

  • In the Google Cloud Console, on the project selector page, select or create a Google Cloud project (For example: abap-sdk-poc).
  • Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project. Skip this step if you are using the 90-Day Free Trial Account.
  • You will use Cloud Shell, a command-line environment running in Google Cloud. From the Cloud Console, click Activate Cloud Shell on the top right corner:
  • 6757b2fb50ddcc2d.png
  • Make sure all the necessary APIs (AM Service Account Credentials API, Vertex AI API) are enabled.
  • Run the following commands to authenticate for your account and set the default project to abap-sdk-poc. Zone us-west4-b is used as an example. If needed, please change the project and zone in the following commands based on your preference.
gcloud auth login
gcloud config set project abap-sdk-poc
gcloud config set compute/zone us-west4-b
PROJECT_NAME=abap-sdk-poc
REGION=us-west4
ZONE=us-west4-b

4. Create a service account and set Vertex AI user role

  1. Run the following command to create a service account (if not already created).
gcloud iam service-accounts create abap-sdk-dev \
    --description="ABAP SDK Dev Account" \
    --display-name="ABAP SDK Dev Account"
  1. Run the following command to set the Vertex AI User role.
gcloud projects add-iam-policy-binding $PROJECT_NAME \
    --member=serviceAccount:abap-sdk-codelabs@$PROJECT_NAME.iam.gserviceaccount.com \
    --role=roles/aiplatform.user

5. Configure client key

Log in to the SAP system. If you are using the system provisioned by codelab " Install ABAP Platform Trial on Google Cloud Platform and Install ABAP SDK", then use the default provisioned username and password to login.

  1. In the SAP GUI, enter transaction code SPRO.
  2. Click SAP Reference IMG.
  3. Click ABAP SDK for Google Cloud > Basic Settings > Configure Client Key.
  4. Click New Entries.
  5. Enter values for the following fields:

Field

Description

Google Cloud Key Name

ABAP_SDK_DEMO

Google Cloud Service Account Name

abap-sdk-dev@abap-sdk-poc.iam.gserviceaccount.com

Google Cloud Scope

https://www.googleapis.com/auth/cloud-platform

Google Cloud Project Identifier

abap-sdk-poc

Authorization Class

/GOOG/CL_AUTH_GOOGLE.

Leave the other fields blank

c72e71da6fd75b29.png

6. Create RFC destination

Create RFC destination for IAM credential and Vertex AI API using the transaction code SM59. If needed, please refer here for detailed steps on creating an RFC destination.

RFC destination name

Target host (API endpoint)

Notes

ZGOOG_IAMCREDENTIALS

  • Host: iamcredentials.googleapis.com
  • Path: Prefix: /v1/
  • Port: 443
  • SSL: Active

This RFC destination targets the IAM API.

ZGOOG_VERTEX_AI

  • Host: us-central1-aiplatform.googleapis.com
  • Port: 443
  • SSL: ACTIVE

This RFC destination targets Vertex AI API us-central1 endpoint.

  • Under the Technical Settings tab, enter the following details for the ZGOOG_IAMCREDENTIALS destination.

e670c6a91acba40f.png

  • Under the Technical Settings tab, enter the following details for the ZGOOG_VERTEX_AI destination.

5c584aaed5c110f2.png

  • For the SSL Certificate field, make sure that the option DEFAULT SSL Client (Standard) is selected for both the RFC destinations.

b6370d12bd332318.png

7. Configure service mapping

To configure the service mapping table for IAM API, and Vertex AI API, perform the following steps:

  1. In the SAP GUI, enter transaction code SPRO.
  2. Click SAP Reference IMG.
  3. Click ABAP SDK for Google Cloud > Basic Settings > Configure Service Mapping.
  4. Click New Entries for IAM Credential and Vertex AI API and update the RFC destinations as shown below.

e7cc1429a4fe3a04.png

8. Validate configuration

To validate the authentication configuration, perform the following steps:

  1. In the SAP GUI, enter transaction code SPRO.
  2. Click SAP Reference IMG.
  3. Click ABAP SDK for Google Cloud > Utilities > Validate Authentication Configuration.
  4. Enter the client key name as ABAP_SDK_DEMO.
  5. Click Execute to check if the overall flow is configured successfully.
  6. A green check in the Result column indicates that all configuration steps are completed successfully.

d7285e64e22c25b6.png

9. Study the product reviews data

The ABAP Platform Trial is pre-installed with the SAP Enterprise Procurement Model (EPM), an end-to-end application furnished by SAP for demonstration and testing purposes. The product reviews that will be utilized for sentiment analysis are stored in the table SNWD_REV_ITEM.

You can view the table data using Tcode: SE16. We will be using the sample text from the field "RATING_TEXT".

2bae72d437ea639.png

Optionally, you can also view the data by accessing the application "Manager Products" from the Fiori Launchpad (TCode: /UI2/FLP).

f9792a91ef9f0736.png

The following screenshot shows the list of products.

f822f9ab71d37a9.png

Click the product to view the product rating and example reviews.

69fe380d5ca7b276.png

In the next section, we will use these sample product reviews to analyze the sentiment using Google LLM.

10. Analyze sentiment using Vertex AI Studio

  1. Open the Vertex AI dashboard, select Language under Vertex AI studio.
  2. Create a new Text Prompt.

8ce4c928c75174d7.png

  1. Confirm the selection of the Gemini Pro model.
  2. In the editor, input the following prompt to instruct the model to analyze customer sentiment in the product review.
  3. Click on Submit to generate the response from the model.

Prompt:

What's the Customer sentiment in the below product review

Horrible! Unsatisfied in every way! The description is wrong. I sent it back. I want my money back! It is so horrible that I can't even believe it! Too expensive for what I received. I'd expect a little more durability. No instructions included for use or installation. I'm actually really surprised by the positive reviews, which I relied on when ordering. Called customer service..no answer. Looks better than it works. The Worst I have ever seen! Honestly I have no clue what you had in mind when choosing to offer this product. Not sure if I should even post one star.... It broke after 1 day. Poor Quality. Didn't work, that is why I cannot recommend this product.

fd245c204144484.png

The review data from the table "SNWD_REV_ITEM" can be utilized for testing the model with additional prompts.

11. Create a report program to call Gemini Pro model

In this step, we will call the Gemini Pro model from ABAP to perform the sentiment analysis of product reviews. For demo purposes the program will select up to 10 product reviews and use ABAP SDK to call the Gemini Pro model for determining the sentiment per review. Based on its analysis the model can return values like "Positive", "Negative", "Neutral" or "Mixed".

  1. Log in to your SAP System.
  2. Go to transaction code SE38 and create a Report Program with the name ZSENTIMENT_ANALYSIS.
  3. In the pop-up that opens up, provide details as shown below, and click Save.

a2158523ec8ef3c7.png

  1. In the next pop-up either select Local Object or provide a package name as appropriate.
REPORT zsentiment_analysis.

DATA lo_client          TYPE REF TO /goog/cl_aiplatform_v1.
DATA lv_p_projects_id   TYPE string.
DATA lv_p_locations_id  TYPE string.
DATA lv_p_publishers_id TYPE string.
DATA lv_p_models_id     TYPE string.
DATA ls_input           TYPE /goog/cl_aiplatform_v1=>ty_726.
DATA ls_output          TYPE /goog/cl_aiplatform_v1=>ty_727.
DATA lv_ret_code        TYPE i.
DATA lv_err_text        TYPE string.
DATA ls_err_resp        TYPE /goog/err_resp.
DATA lv_msg             TYPE string.
DATA lo_exception       TYPE REF TO /goog/cx_sdk.
DATA es_raw             TYPE string.


TYPES:
  BEGIN OF t_reviews,
    product_id  TYPE snwd_product_id,
    sentiment   TYPE string,
    rating_text TYPE snwd_rating_text,
  END OF t_reviews.

DATA lt_reviews TYPE STANDARD TABLE OF t_reviews WITH DEFAULT KEY.
FIELD-SYMBOLS <fs_review> TYPE t_reviews.

TRY.

    " Open HTTP Connection
    lo_client = NEW #( iv_key_name = 'ABAP_SDK_DEMO' ).

    " Populate relevant parameters
    lv_p_projects_id = lo_client->gv_project_id.
    lv_p_locations_id = 'us-central1'.
    lv_p_publishers_id = 'google'.
    lv_p_models_id = 'gemini-1.0-pro'.

    SELECT a~product_id AS product_id c~rating_text
      FROM ( ( snwd_pd AS a
      INNER JOIN snwd_rev_head AS b ON a~node_key = b~entity_key )
      INNER JOIN snwd_rev_item AS c ON b~node_key = c~parent_key )
      INTO CORRESPONDING FIELDS OF TABLE lt_reviews UP TO 10 ROWS.

    LOOP AT lt_reviews ASSIGNING <fs_review>.

      " Construct the prompt
      DATA(lv_prompt) = |DO NOT EXPLAIN and your response should not have more than one word.| &&
                        |Classify the overall sentiment of this product review as ONLY ONE of| &&
                        | the following: Positive, Negative, Neutral, or Mixed.| &&
                        cl_abap_char_utilities=>newline &&
                        <fs_review>-rating_text.

      " Set the Model Parameters and Prompt
      ls_input = VALUE #( generation_config = VALUE #( max_output_tokens = 10
                                                       temperature       = '0.2'
                                                       top_p             = '0.8'
                                                       top_k             = '40' )
                          contents          = VALUE #( ( role  = 'user'
                                                         parts = VALUE #( ( text = lv_prompt ) ) ) ) ).


      " Call Gemini Pro to identify sentiments.
      lo_client->generate_content_models( EXPORTING iv_p_projects_id   = lv_p_projects_id
                                                    iv_p_locations_id  = lv_p_locations_id
                                                    iv_p_publishers_id = lv_p_publishers_id
                                                    iv_p_models_id     = lv_p_models_id
                                                    is_input           = ls_input
                                          IMPORTING
                                                    es_output          = ls_output
                                                    ev_ret_code        = lv_ret_code
                                                    ev_err_text        = lv_err_text
                                                    es_err_resp        = ls_err_resp ).

      IF lo_client->is_success( lv_ret_code ) = abap_true.

        LOOP AT ls_output-candidates INTO DATA(ls_candidate).
          LOOP AT ls_candidate-content-parts INTO DATA(ls_part).
            <fs_review>-sentiment = ls_part-text.
            EXIT.
          ENDLOOP.
          EXIT.
        ENDLOOP.

      ELSE.
        MESSAGE lv_err_text TYPE 'E'.
      ENDIF.

    ENDLOOP.

    cl_demo_output=>display( lt_reviews ).

    " Close HTTP Connection
    lo_client->close( ).

  CATCH /goog/cx_sdk INTO lo_exception.
    lv_msg = lo_exception->get_text( ).
    MESSAGE lv_msg TYPE 'E'.
ENDTRY.

  1. Execute the program to see the sentiment analysis for the review text.

4d869f1b8436b9ca.png

12. Congratulations

Congratulations! You have successfully developed a sample program to perform sentiment analysis using Gemini Pro AI with ABAP SDK for Google Cloud.

13. Clean up

If you do not wish to continue with the additional codelabs related to ABAP SDK for Google Cloud, please proceed with the cleanup.

Delete the project

  • Delete the Google Cloud project:
gcloud projects delete abap-sdk-poc

Delete individual resources

  1. Delete the client key configuration entries by going into IMG > Google Cloud > Basic Settings > Configure Client Key.
  2. Delete the Service Mapping configuration entries by going into IMG > Google Cloud > Basic Settings > Configure Client Key.
  3. Delete the RFC destinations ZGOOG_IAMCREDENTIALS and ZGOOG_VERTEX_AI.
  4. Delete the report program ZSENTIMENT_ANALYSIS.
  5. Delete the service account.
gcloud iam service-accounts delete \
    abap-sdk-dev@abap-sdk-poc.iam.gserviceaccount.com