Mencoba perintah teks

Gunakan Vertex AI untuk mengirim permintaan embedding teks ke Model Bahasa Besar (LLM) PaLM 2 Google dan menerima respons. Uji dan sesuaikan perintah untuk memenuhi kebutuhan aplikasi Anda.

Sebelum memulai

Sebelum dapat mencoba perintah chat, Anda harus melakukan hal berikut:

  1. Menyiapkan project dan lingkungan pengembangan. ID project diperlukan untuk menjalankan kode contoh.
  2. Mempelajari parameter teks yang harus Anda ganti sebelum menjalankan kode contoh.
  3. Meninjau kasus penggunaan teks untuk membantu Anda mengidentifikasi jenis sampel yang akan dibuat.

Mencoba perintah teks

Pilih tab, lalu ikuti petunjuk untuk menjalankan contoh.

REST

Untuk menguji prompt teks menggunakan Vertex AI API, kirim permintaan POST ke endpoint model penayang.

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • PROJECT_ID: Project ID Anda.
  • PROMPT: Perintah adalah permintaan natural language yang dikirimkan ke model bahasa untuk menerima respons balik. Perintah dapat berisi pertanyaan, instruksi, informasi kontekstual, contoh, dan teks untuk diselesaikan atau dilanjutkan oleh model. (Jangan tambahkan tanda kutip di sekitar perintah di sini.)
  • TEMPERATURE: Suhu digunakan untuk pengambilan sampel selama pembuatan respons, yang terjadi saat topP dan topK diterapkan. Suhu mengontrol tingkat keacakan dalam pemilihan token. Suhu yang lebih rendah cocok untuk perintah yang memerlukan respons yang kurang terbuka atau kreatif, sedangkan suhu yang lebih tinggi dapat memberikan hasil yang lebih beragam atau kreatif. Suhu 0 berarti token probabilitas tertinggi selalu dipilih. Dalam hal ini, respons untuk permintaan tertentu sebagian besar deterministik, tetapi sedikit variasi masih dapat dilakukan.

    Jika model menampilkan respons yang terlalu umum, terlalu pendek, atau model memberikan respons penggantian, coba tingkatkan suhu.

  • MAX_OUTPUT_TOKENS: Jumlah maksimum token yang dapat dibuat dalam respons. Token terdiri dari sekitar empat karakter. 100 token setara dengan sekitar 60-80 kata.

    Tentukan nilai yang lebih rendah untuk respons yang lebih pendek dan nilai yang lebih tinggi untuk respons yang berpotensi lebih lama.

  • TOP_P: Top-P mengubah cara model memilih token untuk output. Token dipilih dari yang paling mungkin (lihat top-K) hingga yang paling tidak mungkin sampai jumlah probabilitasnya sama dengan nilai top-P. Misalnya, jika token A, B, dan C memiliki probabilitas 0,3, 0,2, dan 0,1 dengan nilai top-P adalah 0.5, model akan memilih A atau B sebagai token berikutnya dengan menggunakan suhu dan mengecualikan C sebagai kandidat.

    Tentukan nilai yang lebih rendah untuk respons acak yang lebih sedikit dan nilai yang lebih tinggi untuk respons acak yang lebih banyak.

  • TOP_K: Top-K mengubah cara model memilih token untuk output. Top-K dari 1 berarti token yang dipilih berikutnya adalah yang paling mungkin di antara semua token dalam kosakata model (juga disebut decoding greedy), sedangkan nilai top-K dari 3 berarti token berikutnya dipilih di antara tiga token yang paling mungkin menggunakan suhu.

    Untuk setiap langkah pemilihan token, token top-K dengan probabilitas tertinggi akan diambil sampelnya. Kemudian token akan difilter lebih lanjut berdasarkan top-P dengan token akhir yang dipilih menggunakan pengambilan sampel suhu.

    Tentukan nilai yang lebih rendah untuk respons acak yang lebih sedikit dan nilai yang lebih tinggi untuk respons acak yang lebih banyak.

Metode HTTP dan URL:

POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict

Isi JSON permintaan:

{
  "instances": [
    { "prompt": "PROMPT"}
  ],
  "parameters": {
    "temperature": TEMPERATURE,
    "maxOutputTokens": MAX_OUTPUT_TOKENS,
    "topP": TOP_P,
    "topK": TOP_K
  }
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict"

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/text-bison:predict" | Select-Object -Expand Content

Anda akan melihat respons JSON yang mirip seperti berikut:

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Python API.

import vertexai
from vertexai.language_models import TextGenerationModel

def interview(
    temperature: float,
    project_id: str,
    location: str,
) -> str:
    """Ideation example with a Large Language Model"""

    vertexai.init(project=project_id, location=location)
    # TODO developer - override these parameters as needed:
    parameters = {
        "temperature": temperature,  # Temperature controls the degree of randomness in token selection.
        "max_output_tokens": 256,  # Token limit determines the maximum amount of text output.
        "top_p": 0.8,  # Tokens are selected from most probable to least until the sum of their probabilities equals the top_p value.
        "top_k": 40,  # 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(
        "Give me ten interview questions for the role of program manager.",
        **parameters,
    )
    print(f"Response from Model: {response.text}")

    return response.text

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API C# Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

public class PredictTextPromptSample
{
    public string PredictTextPrompt(
        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 prompt = "Give me ten interview questions for the role of program manager.";

        var instanceValue = Value.ForStruct(new()
        {
            Fields =
            {
                ["prompt"] = Value.ForString(prompt)
            }
        });

        var instances = new List<Value>
        {
            instanceValue
        };

        var parameters = Value.ForStruct(new()
        {
            Fields =
            {
                { "temperature", new Value { NumberValue = 0.2 } },
                { "maxOutputTokens", new Value { NumberValue = 256 } },
                { "topP", new Value { NumberValue = 0.95 } },
                { "topK", new Value { NumberValue = 40 } }
            }
        });

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

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

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Node.js Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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 prompt = {
    prompt:
      'Give me ten interview questions for the role of program manager.',
  };
  const instanceValue = helpers.toValue(prompt);
  const instances = [instanceValue];

  const parameter = {
    temperature: 0.2,
    maxOutputTokens: 256,
    topP: 0.95,
    topK: 40,
  };
  const parameters = helpers.toValue(parameter);

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

  // Predict request
  const response = await predictionServiceClient.predict(request);
  console.log('Get text prompt response');
  console.log(response);
}

callPredict();

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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;

public class PredictTextPromptSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // Details of designing text prompts for supported large language models:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/text/text-overview
    String instance =
        "{ \"prompt\": " + "\"Give me ten interview questions for the role of program manager.\"}";
    String parameters =
        "{\n"
            + "  \"temperature\": 0.2,\n"
            + "  \"maxOutputTokens\": 256,\n"
            + "  \"topP\": 0.95,\n"
            + "  \"topK\": 40\n"
            + "}";
    String project = "YOUR_PROJECT_ID";
    String location = "us-central1";
    String publisher = "google";
    String model = "text-bison@001";

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

  // Get a text prompt from a supported text model
  public static void predictTextPrompt(
      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);

      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      Value.Builder instanceValue = Value.newBuilder();
      JsonFormat.parser().merge(instance, instanceValue);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue.build());

      // Use Value.Builder to convert instance 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);
    }
  }
}

Konsol

Untuk mencoba prompt teks menggunakan Vertex AI Studio di Konsol Google Cloud, lakukan langkah-langkah berikut:

  1. Di bagian Vertex AI pada Konsol Google Cloud, buka halaman Vertex AI Studio.

    Buka Vertex AI Studio

  2. Jika project Anda belum dipilih, pilih project Anda.
  3. Klik tab Get started.
  4. Klik Text Prompt.
  5. Pilih metode untuk memasukkan perintah Anda:

    • Bentuk bebas direkomendasikan untuk perintah zero-shot atau memasukkan perintah beberapa kali.
    • Structured direkomendasikan untuk mendesain prompt few-shot di Vertex AI Studio.

    Bentuk bebas

    Masukkan perintah Anda di kolom teks Prompt.

    Terstruktur

    Metode terstruktur untuk memasukkan perintah memisahkan komponen perintah ke dalam kolom yang berbeda:

    • Context: Masukkan petunjuk untuk tugas yang Anda ingin model menjalankannya, dan sertakan informasi kontekstual apa pun untuk direferensikan model.
    • Contoh: Untuk perintah few-shot, tambahkan contoh input-output yang menunjukkan pola perilaku yang akan ditiru oleh model. Menambahkan awalan seperti input atau output bersifat opsional. Opsional: Jika Anda memilih untuk menambahkan awalan, buat awalan tersebut konsisten di semua contoh.
    • Run: Di kolom Input, masukkan input perintah yang ingin Anda dapatkan responsnya. Menambahkan awalan untuk input dan output pengujian bersifat opsional. Jika contoh Anda memiliki awalan, pengujian harus memiliki awalan yang sama.
  6. Konfigurasikan model dan parameter.

  7. Klik Submit.
  8. Opsional: Untuk menyimpan prompt Anda ke My prompts, klik Save.
  9. Opsional: Untuk mendapatkan kode Python atau perintah curl untuk perintah Anda, klik View code.

Streaming respons dari model teks

Untuk melihat contoh permintaan dan respons kode menggunakan REST API, lihat Contoh penggunaan REST API.

Untuk melihat contoh permintaan dan respons kode menggunakan Vertex AI SDK untuk Python, lihat Contoh penggunaan Vertex AI SDK untuk Python.

Langkah selanjutnya