テキスト プロンプトを試す

Vertex AI を使用して、Google の PaLM 2 大規模言語モデル(LLM)にテキスト プロンプトを送信し、レスポンスを受信します。アプリケーションのニーズに合うよう、プロンプトをテストしてカスタマイズします。

始める前に

テキスト プロンプトを試す前に、次のことを行う必要があります。

  1. プロジェクトと開発環境を設定する。サンプルコードを実行するには、プロジェクト ID が必要です。
  2. サンプルコードを実行する前に置き換えが必要となるテキスト パラメータをよく理解してください。
  3. 作成するサンプルのタイプを特定するには、テキストのユースケースを確認してください。

テキスト プロンプトを使ってみる

タブを選択し、手順に沿ってサンプルを実行します。

REST

Vertex AI API を使用してテキスト プロンプトをテストするには、パブリッシャー モデル エンドポイントに POST リクエストを送信します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際のプロジェクト ID
  • PROMPT: プロンプトとは、レスポンスを受け取るために言語モデルに送信される自然言語リクエストです。プロンプトには、モデルを完了または続行するための質問、手順、コンテキスト情報、例、テキストを含めることができます(ここでは、プロンプトを引用符で囲まないでください)。
  • TEMPERATURE: 温度は、レスポンス生成時のサンプリングに使用されます。レスポンス生成は、topPtopK が適用された場合に発生します。温度は、トークン選択のランダム性の度合いを制御します。温度が低いほど、確定的で自由度や創造性を抑えたレスポンスが求められるプロンプトに適しています。一方、温度が高いと、より多様で創造的な結果を導くことができます。温度が 0 の場合、確率が最も高いトークンが常に選択されます。この場合、特定のプロンプトに対するレスポンスはほとんど確定的ですが、わずかに変動する可能性は残ります。

    モデルが返すレスポンスが一般的すぎたり、短すぎたり、フォールバック(代替)レスポンスが返ってきたりする場合は、Temperature を高くしてみてください。

  • MAX_OUTPUT_TOKENS: レスポンス内に生成できるトークンの最大数。1 トークンは約 4 文字です。100 トークンは約 60~80 語に相当します。

    レスポンスを短くしたい場合は小さい値を、長くしたい場合は大きい値を指定します。

  • TOP_P: トップ P は、モデルが出力用にトークンを選択する方法を変更します。トークンは、確率の合計がトップ P 値に等しくなるまで、確率の高いもの(トップ K を参照)から低いものへと選択されます。たとえば、トークン A、B、C の確率が 0.3、0.2、0.1 であり、トップ P 値が 0.5 であるとします。この場合、モデルは温度を使用して A または B を次のトークンとして選択し、C は候補から除外します。

    ランダムなレスポンスを減らしたい場合は小さい値を、ランダムなレスポンスを増やしたい場合は大きい値を指定します。

  • TOP_K: トップ K は、モデルが出力用にトークンを選択する方法を変更します。トップ K が 1 の場合、次に選択されるトークンは、モデルの語彙内のすべてのトークンで最も確率の高いものであることになります(グリーディ デコードとも呼ばれます)。トップ K が 3 の場合は、最も確率が高い上位 3 つのトークンから次のトークン選択されることになります(温度を使用します)。

    トークン選択のそれぞれのステップで、最も高い確率を持つトップ K のトークンがサンプリングされます。その後、トークンはトップ P に基づいてさらにフィルタリングされ、最終的なトークンは温度サンプリングを用いて選択されます。

    ランダムなレスポンスを減らしたい場合は小さい値を、ランダムなレスポンスを増やしたい場合は大きい値を指定します。

HTTP メソッドと URL:

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

リクエストの本文(JSON):

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$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

次のような JSON レスポンスが返されます。

Python

Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、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#

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある C# の設定手順を完了してください。詳細については、Vertex AI C# API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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

このサンプルを試す前に、Vertex AI クライアント ライブラリをインストールするにある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * 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

このサンプルを試す前に、Vertex AI クライアント ライブラリをインストールするにある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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);
    }
  }
}

コンソール

Google Cloud コンソールの Vertex AI Studio を使用してテキスト プロンプトを試すには、以下の手順に沿って操作してください。

  1. Google Cloud コンソールの [Vertex AI] セクションで、[Vertex AI Studio] ページに移動します。

    Vertex AI Studio に移動

  2. プロジェクトが選択されていない場合は、プロジェクトを選択します。
  3. [Get started] タブをクリックします。
  4. [Text Prompt] をクリックします。
  5. プロンプトの入力方法を以下から選択します。

    • Freeform: ゼロショット プロンプトまたは少数ショット プロンプトに対しておすすめします。
    • Structured: Vertex AI Studio で少数ショット プロンプトを設計する場合におすすめします。

    自由形式

    [Prompt] テキスト フィールドにプロンプトを入力します。

    構造化

    プロンプトの入力方法に [Structured] を選択した場合、プロンプトのコンポーネントが以下のようにさまざまなフィールドに分割されます。

    • Context: モデルを走行するタスクの手順を入力し、モデルが参照するコンテキスト情報を含めます。
    • Examples: 少数ショット プロンプトの場合は、モデルが模倣する動作パターンを示す入出力の例を追加します。入力や出力といった接頭辞の追加は任意です。省略可: 接頭辞を追加する場合は、すべての例で一貫したものにしてください。
    • Run: [Input] フィールドに、レスポンスの取得対象となるプロンプトの入力内容を入力します。テストの入出力に接頭辞を追加するかどうかは任意です。[Examples] に接頭辞を追加した場合、テストでも同じ接頭辞を使用する必要があります。
  6. モデルとパラメータを構成します。

  7. [Submit] をクリックします。
  8. 省略可: プロンプトを [My prompts] に保存するには、[Save] をクリックします。
  9. 省略可: プロンプトの Python コードまたは curl コマンドを取得するには、 [View code] をクリックします。

テキストモデルからのレスポンスをストリーミングする

REST API を使用してサンプルコードのリクエストとレスポンスを表示するには、REST API の使用例をご覧ください。

Vertex AI SDK for Python を使用してサンプルコードのリクエストとレスポンスを表示するには、Vertex AI SDK for Python の使用例をご覧ください。

次のステップ