安全性属性を構成する

Vertex AI Gemini API は、安全性属性と構成済みのブロックしきい値のリストに基づいて、安全でないコンテンツをブロックします。このページでは、安全性に関する重要なコンセプトの概要と、安全性属性のブロックしきい値を構成してプロンプトとレスポンスのブロック頻度を制御する方法について説明します。

安全性属性の信頼度スコア

Vertex AI Gemini API で処理されたコンテンツは、「有害なカテゴリ」や機密情報とみなされるトピックなど、安全性属性のリストと照らし合わせて評価されます。次の表に、安全性属性を示します。

安全性属性の定義

安全性属性 定義
ヘイトスピーチ ID や保護されている属性をターゲットとする否定的なコメントや有害なコメント。
嫌がらせ 他人をターゲットにした悪口、威圧表現、いじめ、虐待的な内容を含むコメント
性的に露骨な表現 性行為やわいせつな内容に関する情報が含まれるコンテンツ。
危険なコンテンツ 有害な商品、サービス、アクティビティへのアクセスを促進または可能にするコンテンツ。

安全性属性の確率

安全性属性には、入力またはレスポンスが特定のカテゴリに属する可能性を示す信頼スコア(0.0~1.0、小数点第 2 位を四捨五入)が関連付けられています。

次の表に示す信頼スコアが、安全性の信頼レベルと一緒に返されます。

確率 説明
最小 コンテンツが安全でない確率はごくわずかである。
コンテンツが安全でない確率は低い。
コンテンツが安全でない確率は中程度である。
コンテンツが安全でない確率が高い。

安全性属性の重大度

4 つの安全性属性には、それぞれ安全性評価(重大度レベル)と重大度スコア(0.0~1.0、小数点第 2 位を四捨五入)が割り当てられます。次の表の評価とスコアは、特定のカテゴリに属するコンテンツの重大度の予測を反映しています。

重大度 説明
最小 Google の安全性ポリシーの観点から、コンテンツの重大度が「無視できる」と予測される場合。
Google の安全性ポリシーの観点から、コンテンツの重大度が「低」と予測される場合。
Google の安全性ポリシーの観点から、コンテンツの重大度が「中」と予測される場合。
Google の安全性ポリシーの観点から、コンテンツの重大度が「高」と予測される場合。

安全性設定

安全性設定は、API サービスに送信するリクエストの一部です。API に送信するリクエストごとに調整できます。次の表に、カテゴリごとに調整できるブロック設定を示します。たとえば、「危険なコンテンツ」カテゴリのブロック設定を [少量をブロック] に設定した場合、危険なコンテンツである確率が高いものはすべてブロックされますが、その確率の低いものは許可されます。設定しない場合、デフォルトのブロック設定は [一部をブロック] です。

しきい値(Studio) しきい値(API) しきい値(説明)
BLOCK_NONE(制限付き) 安全でないコンテンツの確率に関係なく、常に表示されます。
少量をブロック BLOCK_ONLY_HIGH 安全でないコンテンツである確率が高い場合にブロックします。
一部をブロック(デフォルト) BLOCK_MEDIUM_AND_ABOVE(デフォルト) 安全でないコンテンツの確率が中程度または高い場合にブロックします。
ほとんどをブロック BLOCK_LOW_AND_ABOVE 安全でないコンテンツの確率が中程度または高い場合にブロックします。
HARM_BLOCK_THRESHOLD_UNSPECIFIED しきい値が指定されていません。デフォルトのしきい値を使用してブロックします。

この設定は、テキスト サービスに対するリクエストごとに変更できます。詳細については、HarmBlockThreshold API リファレンスをご覧ください。

一部の安全性属性に対する自動レスポンスのブロックを解除する方法

安全性設定が BLOCK_NONE の場合、(「安全性設定」で説明されている安全性属性の)自動レスポンスのブロックが解除され、返されたスコアを使用して独自の安全性ガイドラインを構成できます。BLOCK_NONE 設定にアクセスするには、次の 2 つの方法があります。

(1)Gemini 安全フィルタの許可リストフォームから許可リストを申請する。

(2)GCP 請求書発行リファレンスを使用して、アカウントの種類を毎月の請求書発行に切り替える。

Gemini と他のモデル ファミリーの主な違い

Gemini と PaLM には同じ安全性分類が適用されますが、API で返される安全性属性の数はモデル ファミリーによって異なる場合があります。ブロック ロジック(信頼度のしきい値)は、モデルに対する厳格な評価に基づいています。そのため、あるモデルに適用された安全性設定が、別のモデルに適用された安全性設定の動作と完全に一致しない場合があります。このことが懸念される場合は、未加工の重大度スコアと未加工の信頼スコアを使用して独自のブロック ロジックを構成し、モデル間で同じスコアしきい値を適用することをおすすめします。

しきい値を構成する

Python

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

from vertexai import generative_models

def generate_text(project_id: str, location: str, image: str) -> str:
    # Initialize Vertex AI
    vertexai.init(project=project_id, location=location)

    # Load the model
    model = generative_models.GenerativeModel("gemini-1.0-pro-vision")

    # Generation config
    config = generative_models.GenerationConfig(
        max_output_tokens=2048, temperature=0.4, top_p=1, top_k=32
    )

    # Safety config
    safety_config = {
        generative_models.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: generative_models.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
        generative_models.HarmCategory.HARM_CATEGORY_HARASSMENT: generative_models.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    }

    # Generate content
    responses = model.generate_content(
        [image, "Add your prompt here"],
        generation_config=config,
        stream=True,
        safety_settings=safety_config,
    )

    text_responses = []
    for response in responses:
        print(response.text)
        text_responses.append(response.text)
    return "".join(text_responses)

Node.js

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

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

const {
  VertexAI,
  HarmCategory,
  HarmBlockThreshold,
} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function setSafetySettings(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.0-pro'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
    // The following parameters are optional
    // They can also be passed to individual content generation requests
    safety_settings: [
      {
        category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
      },
    ],
    generation_config: {max_output_tokens: 256},
  });

  const request = {
    contents: [{role: 'user', parts: [{text: 'Tell me something dangerous.'}]}],
  };

  console.log('Prompt:');
  console.log(request.contents[0].parts[0].text);
  console.log('Streaming Response Text:');

  // Create the response stream
  const responseStream = await generativeModel.generateContentStream(request);

  // Log the text response as it streams
  for await (const item of responseStream.stream) {
    if (item.candidates[0].finishReason === 'SAFETY') {
      console.log('This response stream terminated due to safety concerns.');
      break;
    } else {
      process.stdout.write(item.candidates[0].content.parts[0].text);
    }
  }
}

Java

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

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

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Candidate;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.GenerationConfig;
import com.google.cloud.vertexai.api.HarmCategory;
import com.google.cloud.vertexai.api.SafetySetting;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import java.util.Arrays;
import java.util.List;

public class WithSafetySettings {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.0-pro-vision";
    String textPrompt = "your-text-here";

    String output = safetyCheck(projectId, location, modelName, textPrompt);
    System.out.println(output);
  }

  // Use safety settings to avoid harmful questions and content generation.
  public static String safetyCheck(String projectId, String location, String modelName,
      String textPrompt) throws Exception {
    // 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 (VertexAI vertexAI = new VertexAI(projectId, location)) {
      StringBuilder output = new StringBuilder();

      GenerationConfig generationConfig =
          GenerationConfig.newBuilder()
              .setMaxOutputTokens(2048)
              .setTemperature(0.4F)
              .setTopK(32)
              .setTopP(1)
              .build();

      GenerativeModel model = new GenerativeModel(modelName, generationConfig, vertexAI);

      List<SafetySetting> safetySettings = Arrays.asList(
          SafetySetting.newBuilder()
              .setCategory(HarmCategory.HARM_CATEGORY_HATE_SPEECH)
              .setThreshold(SafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE)
              .build(),
          SafetySetting.newBuilder()
              .setCategory(HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT)
              .setThreshold(SafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE)
              .build()
      );

      GenerateContentResponse response = model.generateContent(
          textPrompt,
          safetySettings
      );
      output.append(response).append("\n");

      // Verifies if the above content has been blocked for safety reasons.
      boolean blockedForSafetyReason = response.getCandidatesList()
          .stream()
          .anyMatch(candidate -> candidate.getFinishReason() == Candidate.FinishReason.SAFETY);
      output.append("Blocked for safety reasons?: ").append(blockedForSafetyReason);

      return output.toString();
    }
  }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"mime"
	"path/filepath"

	"cloud.google.com/go/vertexai/genai"
)

// generateMultimodalContent generates a response into w, based upon the prompt
// and image provided.
func generateMultimodalContent(w io.Writer, prompt, image, projectID, location, modelName string) error {
	// prompt := "describe this image."
	// location := "us-central1"
	// model := "gemini-1.0-pro-vision"
	// image := "gs://cloud-samples-data/generative-ai/image/320px-Felis_catus-cat_on_snow.jpg"
	ctx := context.Background()

	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %v", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)
	model.SetTemperature(0.4)
	// configure the safety settings thresholds
	model.SafetySettings = []*genai.SafetySetting{
		{
			Category:  genai.HarmCategoryHarassment,
			Threshold: genai.HarmBlockLowAndAbove,
		},
		{
			Category:  genai.HarmCategoryDangerousContent,
			Threshold: genai.HarmBlockLowAndAbove,
		},
	}

	// Given an image file URL, prepare image file as genai.Part
	img := genai.FileData{
		MIMEType: mime.TypeByExtension(filepath.Ext(image)),
		FileURI:  image,
	}

	res, err := model.GenerateContent(ctx, img, genai.Text(prompt))
	if err != nil {
		return fmt.Errorf("unable to generate contents: %w", err)
	}

	fmt.Fprintf(w, "generated response: %s\n", res.Candidates[0].Content.Parts[0])
	return nil
}

C#

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

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


using Google.Api.Gax.Grpc;
using Google.Cloud.AIPlatform.V1;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using static Google.Cloud.AIPlatform.V1.SafetySetting.Types;

public class WithSafetySettings
{
    public async Task<string> GenerateContent(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.0-pro-vision"
    )
    {
        // Create client
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        // Prompt
        string prompt = "Hello!";

        // Initialize request argument(s)
        var content = new Content
        {
            Role = "USER"
        };
        content.Parts.AddRange(new List<Part>()
        {
            new()
            {
                Text = prompt
            }
        });

        var safetySettings = new List<SafetySetting>()
        {
            new()
            {
                Category = HarmCategory.HateSpeech,
                Threshold = HarmBlockThreshold.BlockLowAndAbove
            },
            new()
            {
                Category = HarmCategory.DangerousContent,
                Threshold = HarmBlockThreshold.BlockMediumAndAbove
            }
        };

        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0.4f,
                TopP = 1,
                TopK = 32,
                MaxOutputTokens = 2048
            },
        };
        generateContentRequest.Contents.Add(content);
        generateContentRequest.SafetySettings.AddRange(safetySettings);

        // Make the request, returning a streaming response
        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

        StringBuilder fullText = new();

        // Read streaming responses from server until complete
        AsyncResponseStream<GenerateContentResponse> responseStream = response.GetResponseStream();
        await foreach (GenerateContentResponse responseItem in responseStream)
        {
            // Check if the content has been blocked for safety reasons.
            bool blockForSafetyReason = responseItem.Candidates[0].FinishReason == Candidate.Types.FinishReason.Safety;
            if (blockForSafetyReason)
            {
                fullText.Append("Blocked for safety reasons");
            }
            else
            {
                fullText.Append(responseItem.Candidates[0].Content.Parts[0].Text);
            }
        }

        return fullText.ToString();
    }
}

REST

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

  • LOCATION: リクエストを処理するリージョン。使用できる選択肢は以下のとおりです。

    クリックして利用可能なリージョンを開く

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID: 実際のプロジェクト ID
  • MODEL_ID: 使用するマルチモーダル モデルのモデル ID。次のオプションがあります。
    • gemini-1.0-pro
    • gemini-1.0-pro-vision
  • ROLE: コンテンツに関連付けられた会話におけるロール。単一ターンのユースケースでも、ロールの指定が必要です。指定できる値は以下のとおりです。
    • USER: 送信するコンテンツを指定します。
    • MODEL: モデルのレスポンスを指定します。
  • TEXT: プロンプトに含める指示のテキスト。
  • SAFETY_CATEGORY: しきい値を構成する安全性カテゴリ。指定できる値は以下のとおりです。

    クリックして安全性カテゴリを開く

    • HARM_CATEGORY_SEXUALLY_EXPLICIT
    • HARM_CATEGORY_HATE_SPEECH
    • HARM_CATEGORY_HARASSMENT
    • HARM_CATEGORY_DANGEROUS_CONTENT
  • THRESHOLD: 確率に基づいて、指定された安全性カテゴリに属する可能性のあるレスポンスをブロックするためのしきい値。指定できる値は以下のとおりです。

    クリックしてブロックしきい値を開く

    • BLOCK_NONE
    • BLOCK_ONLY_HIGH
    • BLOCK_MEDIUM_AND_ABOVE(デフォルト)
    • BLOCK_LOW_AND_ABOVE
    BLOCK_LOW_AND_ABOVE はブロック対象が最も多く、BLOCK_ONLY_HIGH はブロック対象が最も少なくなります。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent

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

{
  "contents": {
    "role": "ROLE",
    "parts": { "text": "TEXT" }
  },
  "safety_settings": {
    "category": "SAFETY_CATEGORY",
    "threshold": "THRESHOLD"
  },
}

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

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent"

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://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent" | Select-Object -Expand Content

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

curl コマンドの例

LOCATION="us-central1"
MODEL_ID="gemini-1.0-pro"
PROJECT_ID="test-project"

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:streamGenerateContent -d \
$'{
  "contents": {
    "role": "user",
    "parts": { "text": "Hello!" }
  },
  "safety_settings": [
    {
      "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
      "threshold": "BLOCK_NONE"
    },
    {
      "category": "HARM_CATEGORY_HATE_SPEECH",
      "threshold": "BLOCK_LOW_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_HARASSMENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_ONLY_HIGH"
    }
  ]
}'

コンソール

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

    Vertex AI Studio に移動

  2. [プロンプトを新規作成] でいずれかのボタンをクリックしてプロンプト デザインページを開きます。

  3. [安全性設定] をクリックします。

    [安全性設定] ダイアログ ウィンドウが開きます。

  4. 安全性属性ごとに目的のしきい値を構成します。

  5. [保存] をクリックします。

次のステップ