配置安全属性

Vertex AI Gemini API 会根据安全属性列表及其配置的屏蔽阈值来屏蔽不安全的内容。本页面概述了关键的安全概念,并向您展示如何配置每个安全属性的屏蔽阈值以控制提示和响应的屏蔽频率。

安全属性置信度评分

通过 Vertex AI Gemini API 处理的内容会根据安全属性列表进行评估,其中包括“有害类别”和可能被视为敏感的主题。这些安全属性在下表中表示:

安全属性评分

安全属性 定义
仇恨言论 针对身份和/或受保护属性的负面或有害评论。
骚扰内容 针对其他人的恶意、恐吓、欺凌或辱骂性评论。
露骨色情 包含对性行为或其他淫秽内容的引用。
危险内容 宣传或允许访问有害商品、服务和活动。

安全属性概率

每个安全属性的关联置信度分数介于 0.0 到 1.0 之间,四舍五入到小数点后一位。置信度分数反映了输入或响应属于给定类别的可能性。

下表中的置信度分数会以安全置信度级别返回:

概率 说明
NEGLIGIBLE 内容不安全的概率可忽略不计。
LOW 内容不安全的概率较低。
MEDIUM 内容不安全的概率为中等。
HIGH 内容不安全的概率较高。

安全属性严重级别

以下四个安全属性均分配有安全评级(严重级别)和严重级别分数(范围介于 0.0 到 1.0 之间),四舍五入到小数点后一位。下表中的评分和分数反映了属于给定类别的内容的预测严重级别:

严重级别 说明
NEGLIGIBLE 根据 Google 的安全政策,内容严重级别预测为可以忽略不计。
LOW 根据 Google 的安全政策,内容严重级别预测为低。
MEDIUM 根据 Google 的安全政策,内容严重级别预测为中等。
HIGH 根据 Google 的安全政策,内容严重级别预测为高。

概率分数与严重程度分数的对比

安全得分有两种类型:

  • 基于不安全概率得出的安全得分
  • 基于有害内容严重程度的安全得分

概率安全属性反映了输入或模型响应与相应安全属性相关联的可能性。严重程序安全属性反映了输入或模型响应可能的危害程度。

内容可能具有较低的概率分数和较高的严重性分数,或者可能具有高概率分数和低严重程度分数。例如,请考虑以下两个句子:

  1. 机器人打了我一拳。
  2. 机器人把我砍伤了。

第一句可能导致不安全的可能性更高,而第二句在暴力方面的严重性可能更高。因此,仔细测试并考虑支持关键用例所需的适当屏蔽级别以及最大限度地减少对最终用户的伤害非常重要。

安全设置

安全设置是您向 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 设置,您可以执行以下操作:

  1. 通过 Gemini 安全过滤器许可名单表单申请列入许可名单,或者

  2. 使用 Google Cloud 账单结算参考文档将账号类型更改为按月账单结算。

Gemini 与其他模型系列之间的主要区别

虽然 Gemini 和 PaLM 应用了相同的安全分类器,但 API 中返回的安全属性数量可能因不同模型系列而异。屏蔽逻辑(即置信度阈值)基于对每个模型的严格评估。因此,应用于一个模型的安全设置与应用于其他模型的安全设置的行为并不完全匹配。如果担心这种情况,我们建议您使用原始严重程度分数和原始置信度分数配置自己的屏蔽逻辑,并对模型应用相同的分数阈值。

配置阈值

Python

如需了解如何安装或更新 Python 版 Vertex AI SDK,请参阅安装 Python 版 Vertex AI SDK。 如需了解详情,请参阅 Python API 参考文档

import vertexai

from vertexai import generative_models

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"

vertexai.init(project=project_id, location="us-central1")

model = generative_models.GenerativeModel(model_name="gemini-1.0-pro-vision-001")

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

# Safety config
safety_config = [
    generative_models.SafetySetting(
        category=generative_models.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
        threshold=generative_models.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    ),
    generative_models.SafetySetting(
        category=generative_models.HarmCategory.HARM_CATEGORY_HARASSMENT,
        threshold=generative_models.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    ),
]

image_file = Part.from_uri(
    "gs://cloud-samples-data/generative-ai/image/scones.jpg", "image/jpeg"
)

# Generate content
responses = model.generate_content(
    [image_file, "What is in this image?"],
    generation_config=generation_config,
    safety_settings=safety_config,
    stream=True,
)

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

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.5-flash-001'
) {
  // 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,
      temperature: 0.4,
      top_p: 1,
      top_k: 16,
    },
  });

  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);
    }
  }
  console.log('This response stream terminated due to safety concerns.');
}

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-001";
    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();

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

      GenerativeModel model = new GenerativeModel(modelName, vertexAI)
          .withGenerationConfig(generationConfig)
          .withSafetySettings(safetySettings);

      GenerateContentResponse response = model.generateContent(textPrompt);
      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-001"
	// 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.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"
    )
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();


        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { Text = "Hello!" }
                    }
                }
            },
            SafetySettings =
            {
                new SafetySetting
                {
                    Category = HarmCategory.HateSpeech,
                    Threshold = HarmBlockThreshold.BlockLowAndAbove
                },
                new SafetySetting
                {
                    Category = HarmCategory.DangerousContent,
                    Threshold = HarmBlockThreshold.BlockMediumAndAbove
                }
            }
        };

        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

        StringBuilder fullText = new();

        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 方法和网址:

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. 点击保存

后续步骤