Clasifica opiniones en texto (IA generativa)

Clasifica la opinión que se transmite en texto en forma positiva o negativa.

Muestra de código

C#

Antes de probar este ejemplo, sigue las instrucciones de configuración para C# incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI C#.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


using Google.Cloud.AIPlatform.V1;
using System;
using System.Collections.Generic;
using System.Linq;
using Value = Google.Protobuf.WellKnownTypes.Value;

// Text sentiment analysis with a Large Language Model
public class PredictTextSentimentSample
{
    public string PredictTextSentiment(
        string projectId = "your-project-id",
        string locationId = "us-central1",
        string publisher = "google",
        string model = "text-bison@001")
    {
        // Initialize client that will be used to send requests.
        // This client only needs to be created once,
        // and can be reused for multiple requests.
        var client = new PredictionServiceClientBuilder
        {
            Endpoint = $"{locationId}-aiplatform.googleapis.com"
        }.Build();

        // Configure the parent resource.
        var endpoint = EndpointName.FromProjectLocationPublisherModel(projectId, locationId, publisher, model);

        // Initialize request argument(s).
        var content = @"I had to compare two versions of Hamlet for my Shakespeare
class and unfortunately I picked this version. Everything from the acting
(the actors deliver most of their lines directly to the camera) to the camera
shots (all medium or close up shots...no scenery shots and very little back
ground in the shots) were absolutely terrible. I watched this over my spring
break and it is very safe to say that I feel that I was gypped out of 114
minutes of my vacation. Not recommended by any stretch of the imagination.
Classify the sentiment of the message: negative

Something surprised me about this movie - it was actually original. It was
not the same old recycled crap that comes out of Hollywood every month. I saw
this movie on video because I did not even know about it before I saw it at my
local video store. If you see this movie available - rent it - you will not
regret it.
Classify the sentiment of the message: positive

My family has watched Arthur Bach stumble and stammer since the movie first
came out. We have most lines memorized. I watched it two weeks ago and still
get tickled at the simple humor and view-at-life that Dudley Moore portrays.
Liza Minelli did a wonderful job as the side kick - though I'm not her
biggest fan. This movie makes me just enjoy watching movies. My favorite scene
is when Arthur is visiting his fiancée's house. His conversation with the
butler and Susan's father is side-spitting. The line from the butler,
""Would you care to wait in the Library"" followed by Arthur's reply,
""Yes I would, the bathroom is out of the question"" is my NEWMAIL
notification on my computer.
Classify the sentiment of the message: positive

This Charles outing is decent but this is a pretty low-key performance. Marlon
Brando stands out. There's a subplot with Mira Sorvino and Donald Sutherland
that forgets to develop and it hurts the film a little. I'm still trying to
figure out why Charlie want to change his name.
Classify the sentiment of the message: negative

Tweet: The Pixel 7 Pro, is too big to fit in my jeans pocket, so I bought new
jeans.
Classify the sentiment of the message: ";

        var instances = new List<Value>
        {
            Value.ForStruct(new()
            {
                Fields =
                {
                    ["content"] = Value.ForString(content),
                }
            })
        };

        var parameters = Value.ForStruct(new()
        {
            Fields =
            {
                { "temperature", new Value { NumberValue = 0 } },
                { "maxDecodeSteps", new Value { NumberValue = 5 } },
                { "topP", new Value { NumberValue = 0 } },
                { "topK", new Value { NumberValue = 1 } }
            }
        });

        // Make the request.
        var response = client.Predict(endpoint, instances, parameters);

        // Parse and return the content.
        var responseContent = response.Predictions.First().StructValue.Fields["content"].StringValue;
        Console.WriteLine($"Content: {responseContent}");
        return responseContent;
    }
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración para Java incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Java.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.aiplatform.v1beta1.EndpointName;
import com.google.cloud.aiplatform.v1beta1.PredictResponse;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceSettings;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

// Text sentiment analysis with a Large Language Model
public class PredictTextSentimentSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // The details of designing text prompts for supported large language models:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/text/text-overview
    String instance =
        "{ \"content\": \"I had to compare two versions of Hamlet for my Shakespeare \n"
            + "class and unfortunately I picked this version. Everything from the acting \n"
            + "(the actors deliver most of their lines directly to the camera) to the camera \n"
            + "shots (all medium or close up shots...no scenery shots and very little back \n"
            + "ground in the shots) were absolutely terrible. I watched this over my spring \n"
            + "break and it is very safe to say that I feel that I was gypped out of 114 \n"
            + "minutes of my vacation. Not recommended by any stretch of the imagination.\n"
            + "Classify the sentiment of the message: negative\n"
            + "\n"
            + "Something surprised me about this movie - it was actually original. It was \n"
            + "not the same old recycled crap that comes out of Hollywood every month. I saw \n"
            + "this movie on video because I did not even know about it before I saw it at my \n"
            + "local video store. If you see this movie available - rent it - you will not \n"
            + "regret it.\n"
            + "Classify the sentiment of the message: positive\n"
            + "\n"
            + "My family has watched Arthur Bach stumble and stammer since the movie first \n"
            + "came out. We have most lines memorized. I watched it two weeks ago and still \n"
            + "get tickled at the simple humor and view-at-life that Dudley Moore portrays. \n"
            + "Liza Minelli did a wonderful job as the side kick - though I'm not her \n"
            + "biggest fan. This movie makes me just enjoy watching movies. My favorite scene \n"
            + "is when Arthur is visiting his fiancée's house. His conversation with the \n"
            + "butler and Susan's father is side-spitting. The line from the butler, \n"
            + "\\\"Would you care to wait in the Library\\\" followed by Arthur's reply, \n"
            + "\\\"Yes I would, the bathroom is out of the question\\\", is my NEWMAIL \n"
            + "notification on my computer.\n"
            + "Classify the sentiment of the message: positive\n"
            + "\n"
            + "This Charles outing is decent but this is a pretty low-key performance. Marlon \n"
            + "Brando stands out. There's a subplot with Mira Sorvino and Donald Sutherland \n"
            + "that forgets to develop and it hurts the film a little. I'm still trying to \n"
            + "figure out why Charlie want to change his name.\n"
            + "Classify the sentiment of the message: negative\n"
            + "\n"
            + "Tweet: The Pixel 7 Pro, is too big to fit in my jeans pocket, so I bought new \n"
            + "jeans.\n"
            + "Classify the sentiment of the message: \"}";
    String parameters =
        "{\n"
            + "  \"temperature\": 0,\n"
            + "  \"maxDecodeSteps\": 5,\n"
            + "  \"topP\": 0,\n"
            + "  \"topK\": 1\n"
            + "}";
    String project = "YOUR_PROJECT_ID";
    String location = "us-central1";
    String publisher = "google";
    String model = "text-bison@001";

    predictTextSentiment(instance, parameters, project, location, publisher, model);
  }

  static void predictTextSentiment(
      String instance,
      String parameters,
      String project,
      String location,
      String publisher,
      String model)
      throws IOException {
    String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      final EndpointName endpointName =
          EndpointName.ofProjectLocationPublisherModelName(project, location, publisher, model);

      // Use Value.Builder to convert instance to a dynamically typed value that can be
      // processed by the service.
      Value.Builder instanceValue = Value.newBuilder();
      JsonFormat.parser().merge(instance, instanceValue);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue.build());

      // Use Value.Builder to convert parameter to a dynamically typed value that can be
      // processed by the service.
      Value.Builder parameterValueBuilder = Value.newBuilder();
      JsonFormat.parser().merge(parameters, parameterValueBuilder);
      Value parameterValue = parameterValueBuilder.build();

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, parameterValue);
      System.out.println("Predict Response");
      System.out.println(predictResponse);
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';

const aiplatform = require('@google-cloud/aiplatform');

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = aiplatform;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

const publisher = 'google';
const model = 'text-bison@001';

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function callPredict() {
  // Configure the parent resource
  const endpoint = `projects/${project}/locations/${location}/publishers/${publisher}/models/${model}`;

  const instance = {
    content: `I had to compare two versions of Hamlet for my Shakespeare class and \
  unfortunately I picked this version. Everything from the acting (the actors \
  deliver most of their lines directly to the camera) to the camera shots (all \
  medium or close up shots...no scenery shots and very little back ground in the \
  shots) were absolutely terrible. I watched this over my spring break and it is \
  very safe to say that I feel that I was gypped out of 114 minutes of my \
  vacation. Not recommended by any stretch of the imagination.
  Classify the sentiment of the message: negative

  Something surprised me about this movie - it was actually original. It was not \
  the same old recycled crap that comes out of Hollywood every month. I saw this \
  movie on video because I did not even know about it before I saw it at my \
  local video store. If you see this movie available - rent it - you will not \
  regret it.
  Classify the sentiment of the message: positive

  My family has watched Arthur Bach stumble and stammer since the movie first \
  came out. We have most lines memorized. I watched it two weeks ago and still \
  get tickled at the simple humor and view-at-life. \
  This movie makes me just enjoy watching movies. My favorite scene \
  is when Arthur is visiting his fiancée's house. His conversation with the \
  butler and Susan's father is side-spitting. The line from the butler, \
  "Would you care to wait in the Library" followed by Arthur's reply, \
  "Yes I would, the bathroom is out of the question", is my NEWMAIL \
  notification on my computer.
  Classify the sentiment of the message: positive


  Tweet: The Pixel 7 Pro, is too big to fit in my jeans pocket, so I bought \
  new jeans.
  Classify the sentiment of the message: 
  `,
  };
  const instanceValue = helpers.toValue(instance);
  const instances = [instanceValue];

  const parameter = {
    temperature: 0.2,
    maxOutputTokens: 5,
    topP: 0,
    topK: 1,
  };
  const parameters = helpers.toValue(parameter);

  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const [response] = await predictionServiceClient.predict(request);
  console.log('Get text sentiment response');
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const prediction of predictions) {
    console.log(`\t\tPrediction : ${JSON.stringify(prediction)}`);
  }
}

callPredict();

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración para Python incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Python.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    import vertexai

    from vertexai.language_models import TextGenerationModel

    # TODO(developer): update project_id, location & temperature
    vertexai.init(project=PROJECT_ID, location="us-central1")
    parameters = {
        "temperature": 0,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 5,  # Token limit determines the maximum amount of text output.
        "top_p": 0,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
        "top_k": 1,  # A top_k of 1 means the selected token is the most probable among all tokens.
    }

    model = TextGenerationModel.from_pretrained("text-bison@002")
    response = model.predict(
        """I had to compare two versions of Hamlet for my Shakespeare class and \
unfortunately I picked this version. Everything from the acting (the actors \
deliver most of their lines directly to the camera) to the camera shots (all \
medium or close up shots...no scenery shots and very little back ground in the \
shots) were absolutely terrible. I watched this over my spring break and it is \
very safe to say that I feel that I was gypped out of 114 minutes of my \
vacation. Not recommended by any stretch of the imagination.
Classify the sentiment of the message: negative

Something surprised me about this movie - it was actually original. It was not \
the same old recycled crap that comes out of Hollywood every month. I saw this \
movie on video because I did not even know about it before I saw it at my \
local video store. If you see this movie available - rent it - you will not \
regret it.
Classify the sentiment of the message: positive

My family has watched Arthur Bach stumble and stammer since the movie first \
came out. We have most lines memorized. I watched it two weeks ago and still \
get tickled at the simple humor and view-at-life that Dudley Moore portrays. \
Liza Minelli did a wonderful job as the side kick - though I\'m not her \
biggest fan. This movie makes me just enjoy watching movies. My favorite scene \
is when Arthur is visiting his fiancée\'s house. His conversation with the \
butler and Susan\'s father is side-spitting. The line from the butler, \
"Would you care to wait in the Library" followed by Arthur\'s reply, \
"Yes I would, the bathroom is out of the question", is my NEWMAIL \
notification on my computer.
Classify the sentiment of the message: positive

This Charles outing is decent but this is a pretty low-key performance. Marlon \
Brando stands out. There\'s a subplot with Mira Sorvino and Donald Sutherland \
that forgets to develop and it hurts the film a little. I\'m still trying to \
figure out why Charlie want to change his name.
Classify the sentiment of the message: negative

Tweet: The Pixel 7 Pro, is too big to fit in my jeans pocket, so I bought \
new jeans.
Classify the sentiment of the message: """,
        **parameters,
    )
    print(f"Response from Model: {response.text}")

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.