テキスト チャット

チャット用 PaLM 2(chat-bison)基盤モデルは、言語理解、言語生成、会話に非常に適した大規模言語モデル(LLM)です。このチャットモデルは、マルチターンの会話を自然に行えるようにファインチューニングされており、コードについてやり取りが必要なテキストタスクに最適です。

1 回の API レスポンスで完了できるテキストタスクの場合(継続的な会話を必要としない場合)は、テキストモデルを使用します。

コンソールでこのモデルを確認するには、Model Garden のチャット用の PaLM 2 のモデルカードをご覧ください。
Model Garden に移動

ユースケース

  • カスタマー サービス: カスタマー サービスの担当者として、会社の商品についてのみ応答するようにモデルに指示します。

  • テクニカル サポート: コールセンターの担当者として、対応方法と禁止内容に関する特定のパラメータを使用してお客様とやり取りするようにモデルに指示します。

  • ペルソナとキャラクター: 特定の人物のスタイルで応答するようにモデルに指示します(たとえば「シェイクスピアのスタイルで」)

  • ウェブサイト コンパニオン: ショッピングや旅行などのユースケース向けの会話アシスタントを作成します。

詳細については、テキスト プロンプトを設計するをご覧ください。

HTTP リクエスト

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

詳細については、predict メソッドをご覧ください。

モデル バージョン

モデルの最新バージョンを使用するには、バージョン番号なしでモデル名を指定します(例: chat-bison)。

モデルの安定版を使用する場合は、モデルのバージョン番号を指定します(例: chat-bison@002)。安定版は、後続の安定版のリリース日から 6 か月間利用できます。

次の表に、利用可能なモデルの安定版を示します。

chat-bison モデル リリース日 廃止日
chat-bison@002 2023 年 12 月 6 日 2024 年 10 月 9 日
chat-bison@001 2023 年 7 月 10 日 2024 年 7 月 6 日

詳細については、モデルのバージョンとライフサイクルをご覧ください。

リクエストの本文

{
  "instances": [
    {
      "context":  string,
      "examples": [
        {
          "input": { "content": string },
          "output": { "content": string }
        }
      ],
      "messages": [
        {
          "author": string,
          "content": string,
        }
      ],
    }
  ],
  "parameters": {
    "temperature": number,
    "maxOutputTokens": integer,
    "topP": number,
    "topK": integer,
    "groundingConfig": string,
    "stopSequences": [ string ],
    "candidateCount": integer
    "logprobs": integer,
    "presencePenalty": float,
    "frequencyPenalty": float,
    "seed": integer
  }
}

チャット API 呼び出しの場合、contextexamplesmessages を組み合わせてプロンプトを形成します。次の表に、テキスト用の Vertex AI PaLM API に構成する必要があるパラメータを示します。

パラメータ 説明 使用できる値

context

(省略可)

コンテキストは、会話の全体を通してモデルがどう応答するかを方向付けます。たとえば、コンテキストを使用して、モデルが使用できる言葉や使用できない言葉、沿うべきトピックや避けるべきトピック、応答の形式やスタイルを指定できます。 テキスト

examples

(省略可)

会話への応答方法を学習するためのモデルの例。

[{
  "input": {"content": "provide content"},
  "output": {"content": "provide content"}
}]

messages

(必須)

構造化された形式でモデルに提供される会話の履歴。メッセージは古い順、新しい順に表示されます。メッセージの履歴のために入力が最大文字数を超えると、プロンプト全体が上限内に収まるまで最も古いメッセーが削除されます。

[{
  "author": "user",
  "content": "user message"
}]

temperature

温度は、レスポンス生成時のサンプリングに使用されます。レスポンス生成は、topPtopK が適用された場合に発生します。温度は、トークン選択のランダム性の度合いを制御します。温度が低いほど、確定的で自由度や創造性を抑えたレスポンスが求められるプロンプトに適しています。一方、温度が高いと、より多様で創造的な結果を導くことができます。温度が 0 の場合、確率が最も高いトークンが常に選択されます。この場合、特定のプロンプトに対するレスポンスはほとんど確定的ですが、わずかに変動する可能性は残ります。

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

0.0–1.0

Default: 0.0

maxOutputTokens

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

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

1–2048

Default: 1024

topK

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

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

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

1–40

Default: 40

topP

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

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

0.0–1.0

Default: 0.95

stopSequences

レスポンスでいずれかの文字列が検出された場合に、テキストの生成を停止するようモデルに指示する文字列のリストを指定します。レスポンスで文字列が複数回出現する場合、レスポンスでは最初に見つかった箇所が切り捨てられます。文字列では大文字と小文字が区別されます。

たとえば、stopSequences が指定されていない場合に、次のレスポンスが返されたとします。

public static string reverse(string myString)

この場合に、stopSequences["Str", "reverse"] に設定されている次のようなレスポンスが返されます。

public static string

default: []

groundingConfig

根拠付けにより、言語モデルを使用するときに特定のデータを参照できます。モデルを根拠付けると、そのモデルはリポジトリから内部データ、社外秘データなどの特定のデータを参照し、そのデータをレスポンスに含めることができます。Vertex AI Search のデータストアのみがサポートされています。

パスは projects/{project_id}/locations/global/collections/{collection_name}/dataStores/{DATA_STORE_ID} の形式にする必要があります

candidateCount

返すレスポンス バリエーションの数。

1–4

Default: 1

logprobs

各生成ステップで、最上位 logprobs の最も可能性の高い候補トークンとそのログ確率を返します。各ステップで選択したトークンとそのログ確率は常に返されます。選択したトークンは、最上位 logprobs の最も可能性の高い候補に含まれる場合もあれば、含まれない場合もあります。

0-5

frequencyPenalty

値が正の場合は、生成されたテキストに繰り返し出現するトークンにペナルティが課されるため、コンテンツが繰り返される確率は低下します。有効な値は -2.02.0 です。

Minimum value: -2.0

Maximum value: 2.0

presencePenalty

値が正の場合は、生成されたテキスト内の既存のトークンにペナルティが課されるため、より多様なコンテンツが生成される確率は高くなります。有効な値は -2.02.0 です。

Minimum value: -2.0

Maximum value: 2.0

seed

デコーダは、擬似乱数生成ツールを使用してランダムなノイズを生成します。サンプリングを行う前に、温度 * ノイズをロジットに追加します。疑似乱数生成ツール(prng)は、シードを入力として受け取り、同じシードを使用して同じ出力を生成します。

シードが設定されていない場合、デコーダで使用されるシードが決定的ではないため、生成されたランダムノイズは変動する可能性があります。シードが設定されている場合、生成されるランダムノイズは決定的です。

Optional

リクエストの例

REST

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

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

他のフィールドについては、リクエストの本文の表をご覧ください。

HTTP メソッドと URL:

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

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

{
  "instances": [{
      "context":  "CONTEXT",
      "examples": [
       {
          "input": {"content": "EXAMPLE_INPUT"},
          "output": {"content": "EXAMPLE_OUTPUT"}
       }],
      "messages": [
       {
          "author": "AUTHOR",
          "content": "CONTENT",
       }],
   }],
  "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/chat-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/chat-bison:predict" | Select-Object -Expand Content

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

Python

Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Python API リファレンス ドキュメントをご覧ください。

from vertexai.language_models import ChatModel, InputOutputTextPair

def science_tutoring(temperature: float = 0.2) -> None:
    chat_model = ChatModel.from_pretrained("chat-bison@001")

    # 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.95,  # 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.
    }

    chat = chat_model.start_chat(
        context="My name is Miles. You are an astronomer, knowledgeable about the solar system.",
        examples=[
            InputOutputTextPair(
                input_text="How many moons does Mars have?",
                output_text="The planet Mars has two moons, Phobos and Deimos.",
            ),
        ],
    )

    response = chat.send_message(
        "How many planets are there in the solar system?", **parameters
    )
    print(f"Response from Model: {response.text}")

    return response

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 = 'chat-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 = {
    context:
      'My name is Miles. You are an astronomer, knowledgeable about the solar system.',
    examples: [
      {
        input: {content: 'How many moons does Mars have?'},
        output: {
          content: 'The planet Mars has two moons, Phobos and Deimos.',
        },
      },
    ],
    messages: [
      {
        author: 'user',
        content: 'How many planets are there in the solar system?',
      },
    ],
  };
  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 chat prompt response');
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const prediction of predictions) {
    console.log(`\t\tPrediction : ${JSON.stringify(prediction)}`);
  }
}

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;

// Send a Predict request to a large language model to test a chat prompt
public class PredictChatPromptSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String instance =
        "{\n"
            + "   \"context\":  \"My name is Ned. You are my personal assistant. My favorite movies"
            + " are Lord of the Rings and Hobbit.\",\n"
            + "   \"examples\": [ { \n"
            + "       \"input\": {\"content\": \"Who do you work for?\"},\n"
            + "       \"output\": {\"content\": \"I work for Ned.\"}\n"
            + "    },\n"
            + "    { \n"
            + "       \"input\": {\"content\": \"What do I like?\"},\n"
            + "       \"output\": {\"content\": \"Ned likes watching movies.\"}\n"
            + "    }],\n"
            + "   \"messages\": [\n"
            + "    { \n"
            + "       \"author\": \"user\",\n"
            + "       \"content\": \"Are my favorite movies based on a book series?\"\n"
            + "    }]\n"
            + "}";
    String parameters =
        "{\n"
            + "  \"temperature\": 0.3,\n"
            + "  \"maxDecodeSteps\": 200,\n"
            + "  \"topP\": 0.8,\n"
            + "  \"topK\": 40\n"
            + "}";
    String project = "YOUR_PROJECT_ID";
    String publisher = "google";
    String model = "chat-bison@001";

    predictChatPrompt(instance, parameters, project, publisher, model);
  }

  static void predictChatPrompt(
      String instance, String parameters, String project, String publisher, String model)
      throws IOException {
    PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .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)) {
      String location = "us-central1";
      final EndpointName endpointName =
          EndpointName.ofProjectLocationPublisherModelName(project, location, publisher, model);

      Value.Builder instanceValue = Value.newBuilder();
      JsonFormat.parser().merge(instance, instanceValue);
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue.build());

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

レスポンスの本文

{
  "predictions": [
    {
      "candidates": [
        {
          "author": string,
          "content": string
        }
      ],
      "citationMetadata": {
        "citations": [
          {
            "startIndex": integer,
            "endIndex": integer,
            "url": string,
            "title": string,
            "license": string,
            "publicationDate": string
          }
        ]
      },
      "logprobs": {
        "tokenLogProbs": [ float ],
        "tokens": [ string ],
        "topLogProbs": [ { map<string, float> } ]
      },
      "safetyAttributes": {
        "categories": [ string ],
        "blocked": false,
        "scores": [ float ],
        "errors": [ int ]
      }
    }
  ],
  "metadata": {
    "tokenMetadata": {
      "input_token_count": {
        "total_tokens": integer,
        "total_billable_characters": integer
      },
      "output_token_count": {
        "total_tokens": integer,
        "total_billable_characters": integer
      }
    }
  }
}
レスポンス要素 説明
content チャット メッセージのテキスト コンテンツ。
candidates 指定したメッセージから生成されたチャットの結果。
categories 生成されたコンテンツに関連付けられた安全性属性カテゴリの表示名。順序はスコア順になります。
author ターンの作成者タグ。
scores 各カテゴリの信頼スコア。値が大きいほど、信頼度が高くなります。
blocked モデルの入力または出力がブロックされたかどうかを示すフラグ。
startIndex 引用が開始される予測出力のインデックス(両端を含む)。0 以上、end_index 未満にする必要があります。
endIndex 引用が終了する予測出力のインデックス(終了箇所は含まない)。start_index より大きく、かつ len(output) より小さくする必要があります。
url この引用に関連付けられている URL。この URL が存在する場合は、この引用元のウェブページにリンクします。考えられる URL には、ニュース ウェブサイトや GitHub リポジトリなどがあります。
title この引用に関連付けられているタイトル。存在する場合は、この引用のソースのタイトルを指します。考えられるタイトルには、ニュース タイトルや書籍名などがあります。
license この引用に関連付けられているライセンス。存在する場合は、この引用元のライセンスを指します。考えられるライセンスの例としては、Mit ライセンスなど、コード ライセンスが挙げられます。
publicationDate この引用に関連付けられている公開日。存在する場合は、この引用の出典が公開された日付を指します。使用できる形式は、YYYY、YYYY-MM、YYYY-MM-DD です。
safetyAttributes カテゴリとそれに関連付けられた信頼スコアのコレクション。candidates への 1 対 1 のマッピング。
input_token_count 入力トークンの数。これは、すべてのメッセージ、例、コンテキストにわたるトークンの総数です。
output_token_count 出力トークンの数。これは、レスポンス内のすべての候補における content 内のトークンの合計数です。
tokens サンプリングされたトークン。
tokenLogProbs サンプリングされたトークンのログ確率。
topLogProb 各ステップで最も可能性の高い候補トークンとそのログ確率。
logprobs logprobs パラメータの結果。candidates に対する 1 対 1 のマッピング。

レスポンスの例

{
  "predictions": [
    {
      "citationMetadata": {
        "citations": []
      },
      "safetyAttributes": {
        "scores": [
          0.1
        ],
        "categories": [
          "Finance"
        ],
        "blocked": false
      },
      "candidates": [
        {
          "author": "AUTHOR",
          "content": "RESPONSE"
        }
      ]
    }
  ]
}

生成 AI モデルからのレスポンスをストリーミングする

API に対するストリーミング リクエストと非ストリーミング リクエストでパラメータは同じです。

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

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