配置 Model Armor 的下限设置

本文档介绍了如何查看和更新 Model Armor 下限设置,并提供了一个下限设置违规示例。

Model Armor 下限设置可定义规则,以规定在 Google Cloud 资源层次结构的特定点(即在组织、文件夹或项目级别)创建的所有 Model Armor 模板的最低要求。如果存在多个相互冲突的下限设置,则资源层次结构中较低级别的设置优先。例如,如果在文件夹和项目级别都创建了下限设置政策,则会应用项目级政策。此行为仅适用于位于该特定文件夹内的项目。

例如,假设您已在特定文件夹中设置文件夹级政策,为其中的所有内容启用恶意 URI 过滤器。然后,在同一文件夹中,您有一个特定项目。在此项目中,您已配置更具体的项目级政策。此项目级政策要求将提示注入和越狱检测的置信度阈值设置为“中等”。

结果如下:

  • 在此特定项目中创建的任何 Model Armor 模板都必须包含提示注入和越狱检测过滤条件,并至少将置信度阈值设置为“中等”。这是因为项目级政策为相应项目中的所有模板设置了最低要求。

  • 在此项目父文件夹之外创建的模板不受该特定文件夹政策的影响。因此,如果您在其他文件夹中或在根级别创建模板,系统不会自动要求使用为此特定文件夹设置的恶意 URI 过滤条件。这表明,这些政策仅适用于其特定的层次级别,除非在更高级别、更广泛的组织级别设置,否则不会全局应用。

下限设置可帮助 CISO 和安全架构师在其组织的所有 Model Armor 模板中强制执行最低安全状况。这些设置有助于防止开发者降低安全标准。如果您使用的是 Security Command Center 的高级或 Enterprise 服务层级,则违反下限设置会触发发现结果。如果在下限设置之前创建了设置限制性较低的模板,Security Command Center 会显示一个发现结果。这些设置有助于您识别和修复安全性较低的 Model Armor 模板。下限设置无法强制执行 Sensitive Data Protection。

准备工作

在开始之前,请完成以下任务。

获取所需的权限

如需获得管理 Model Armor 地板设置所需的权限,请让您的管理员为您授予 Model Armor 地板设置的 Model Armor Floor Setting Admin (roles/modelarmor.floorSettingsAdmin) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

启用 API

您必须先启用 Model Armor API,然后才能使用 Model Armor。

控制台

  1. Enable the Model Armor API.

    Enable the API

  2. 选择要启用 Model Armor 的项目。

gcloud

在开始之前,请使用 Google Cloud CLI 和 Model Armor API 按照以下步骤操作:

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 运行以下命令,为 Model Armor 服务设置 API 端点。

    gcloud config set api_endpoint_overrides/modelarmor "https://modelarmor.LOCATION.rep.googleapis.com/"

    LOCATION 替换为您要使用 Model Armor 的区域。

  3. 运行以下命令以启用 Model Armor。

      gcloud services enable modelarmor.googleapis.com --project=PROJECT_ID
       

    PROJECT_ID 替换为相应项目的 ID。

    与 Vertex AI 的集成

    Model Armor 与 Vertex AI 相集成,可根据您定义的下限设置来过滤 Gemini 模型请求和回答。您需要启用 Cloud Logging 才能查看提示和回答。如需了解详情,请参阅 Model Armor 与 Vertex AI 相集成

    配置下限设置

    您可以使用下限设置来配置 Model Armor 模板的最低检测阈值。这些设置用于验证所有新模板和修改后的模板是否符合特定要求。如需配置下限设置,请执行以下操作:

    控制台

    1. 在 Google Cloud 控制台中,前往 Model Armor 页面。

      前往 Model Armor

    2. 选择一个项目。
    3. Model Armor 页面上,前往下限设置标签页,然后点击配置下限设置
    4. 配置下限设置页面上,选择配置选项
    5. 检测部分,配置检测设置
    6. 可选:如果您选择 Sensitive Data Protection 检测,则需要配置 Sensitive Data Protection 设置
    7. Responsible AI 部分中,为每种内容过滤器设置置信度

    8. 服务部分,选择要应用这些下限设置的服务

    9. 日志部分,选择启用 Cloud Logging 以记录所有用户提示、模型回答和下限设置检测器结果。

    10. 选择启用多语言支持以使用多语言检测设置

    11. 点击保存下限设置

    REST

    curl -X PATCH \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -d '{"filterConfig" : {}, "integratedServices": "AI_PLATFORM", "aiPlatformFloorSetting":{"inspect_only":true, "enableCloudLogging":true}}' \
        "https://modelarmor.googleapis.com/v1/projects/PROJECT_ID/locations/global/floorSetting"

    PROJECT_ID 替换为楼层设置的项目 ID。

    定义下限设置的继承方式

    配置下限设置时,请选择配置选项。

    • 继承父级的下限设置:继承资源层次结构中更高级别的下限设置。点击保存下限设置,然后跳过后续步骤。如需查看继承的设置,请前往下限设置标签页。

    • 自定义:为此项目定义下限设置。您为项目定义的自定义设置会替换任何继承的下限设置。

    • 停用:停用所有继承的下限设置,这意味着不会将任何检测规则应用于 Model Armor 模板以及您的 Gemini 工作负载所用的 Vertex AI。点击保存下限设置,然后跳过后续步骤。在下限设置标签页中查看停用状态。

    定义下限设置的应用范围

    选择以下任一服务,以应用配置的下限设置。

    • Model Armor - 模板创建和更新:系统会检查项目中的每个新 Model Armor 模板和修改后的 Model Armor 模板,确保它们具有根据下限设置指定的最低设置。
    • Vertex AI:过滤发送给 Gemini 模型的请求,并记录或屏蔽符合下限设置阈值的请求。

      如果您选择 Vertex AI,系统会显示 Vertex AI 部分,您可以在其中选择如何执行下限设置。

      • 仅检查:检测不符合下限设置的请求,但不屏蔽这些请求。
      • 检查并屏蔽违规请求:检测并屏蔽不符合下限设置的请求。

    查看 Model Armor 下限设置

    您可以查看 Model Armor 下限设置,以验证现有设置、确定 AI 应用的最低要求,或在模板未按预期运行时排查问题。

    运行以下命令以查看 Model Armor 下限设置。

    控制台

    1. 在 Google Cloud 控制台中,前往 Model Armor 页面。

      前往 Model Armor

    2. 确认您正在查看的是已启用 Model Armor 的项目。

    3. Model Armor 页面上,前往下限设置标签页。如果在组织级设置了下限设置,则可以在该标签页查看这些设置。如果未定义任何下限设置,则必须先进行配置。如需了解详情,请参阅配置下限设置

    gcloud

    • 查看指定项目的 Model Armor 下限设置。

        gcloud model-armor floorsettings describe \
            --full-uri='projects/PROJECT_ID/locations/global/floorSetting'
    • 查看指定组织的 Model Armor 下限设置。

        gcloud model-armor floorsettings describe \
            --full-uri='organizations/ORGANIZATION_ID/locations/global/floorSetting'
    • 查看指定文件夹的 Model Armor 下限设置。

         gcloud model-armor floorsettings describe \
             --full-uri='folders/FOLDER_ID/locations/global/floorSetting'

      替换以下内容:

      • PROJECT_ID:楼层设置所对应的项目 ID。
      • FOLDER_ID:楼层设置所对应的文件夹的 ID。
      • ORGANIZATION_ID:相应楼层设置所对应的组织的 ID。

    REST

    • 查看指定项目的 Model Armor 下限设置。

      curl -X GET \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://modelarmor.googleapis.com/v1/projects/PROJECT_ID/locations/global/floorSetting"
    • 查看指定文件夹的 Model Armor 下限设置。

      curl -X GET \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://modelarmor.googleapis.com/v1/folders/FOLDER_ID/locations/global/floorSetting"
    • 查看指定组织的 Model Armor 下限设置。

      curl -X GET \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: application/json" \
        "https://modelarmor.googleapis.com/v1/organizations/ORGANIZATION_ID/locations/global/floorSetting"

    替换以下内容:

    • PROJECT_ID:楼层设置所对应的项目 ID。
    • FOLDER_ID:楼层设置所对应的文件夹的 ID。
    • ORGANIZATION_ID:相应楼层设置所对应的组织的 ID。

    Go

    如需运行此代码,请先设置 Go 开发环境安装 Model Armor Go SDK

    • 查看指定项目的 Model Armor 下限设置。

      
      import (
      	"context"
      	"fmt"
      	"io"
      
      	modelarmor "cloud.google.com/go/modelarmor/apiv1"
      	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
      )
      
      // getProjectFloorSettings gets details of a single floor setting of a project.
      //
      // This method retrieves the details of a single floor setting of a project.
      //
      // w io.Writer: The writer to use for logging.
      // projectID string: The ID of the project.
      func getProjectFloorSettings(w io.Writer, projectID string) error {
      	ctx := context.Background()
      
      	// Create the Model Armor client.
      	client, err := modelarmor.NewClient(ctx)
      	if err != nil {
      		return fmt.Errorf("failed to create client: %w", err)
      	}
      	defer client.Close()
      
      	floorSettingsName := fmt.Sprintf("projects/%s/locations/global/floorSetting", projectID)
      
      	// Get the project floor setting.
      	req := &modelarmorpb.GetFloorSettingRequest{
      		Name: floorSettingsName,
      	}
      
      	response, err := client.GetFloorSetting(ctx, req)
      	if err != nil {
      		return fmt.Errorf("failed to get floor setting: %w", err)
      	}
      
      	// Print the retrieved floor setting using fmt.Fprintf with the io.Writer.
      	fmt.Fprintf(w, "Retrieved floor setting: %v\n", response)
      
      	return nil
      }
      
    • 查看指定文件夹的 Model Armor 下限设置。

      
      import (
      	"context"
      	"fmt"
      	"io"
      
      	modelarmor "cloud.google.com/go/modelarmor/apiv1"
      	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
      )
      
      // getFolderFloorSettings gets details of a single floor setting of a folder.
      //
      // This method retrieves the details of a single floor setting of a folder.
      //
      // w io.Writer: The writer to use for logging.
      // folderID string: The ID of the folder.
      func getFolderFloorSettings(w io.Writer, folderID string) error {
      	ctx := context.Background()
      
      	// Create the Model Armor client.
      	client, err := modelarmor.NewClient(ctx)
      	if err != nil {
      		return fmt.Errorf("failed to create client: %w", err)
      	}
      	defer client.Close()
      
      	// Prepare folder floor setting path/name
      	floorSettingsName := fmt.Sprintf("folders/%s/locations/global/floorSetting", folderID)
      
      	// Get the folder floor setting.
      	req := &modelarmorpb.GetFloorSettingRequest{
      		Name: floorSettingsName,
      	}
      
      	response, err := client.GetFloorSetting(ctx, req)
      	if err != nil {
      		return fmt.Errorf("failed to get floor setting: %w", err)
      	}
      
      	// Print the retrieved floor setting using fmt.Fprintf with the io.Writer.
      	fmt.Fprintf(w, "Retrieved folder floor setting: %v\n", response)
      
      	return nil
      }
      
    • 查看指定组织的 Model Armor 下限设置。

      
      import (
      	"context"
      	"fmt"
      	"io"
      
      	modelarmor "cloud.google.com/go/modelarmor/apiv1"
      	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
      )
      
      // getOrganizationFloorSettings gets details of a single floor setting of an organization.
      //
      // This method retrieves the details of a single floor setting of an organization.
      //
      // w io.Writer: The writer to use for logging.
      // organizationID string: The ID of the organization.
      func getOrganizationFloorSettings(w io.Writer, organizationID string) error {
      	ctx := context.Background()
      
      	// Create the Model Armor client.
      	client, err := modelarmor.NewClient(ctx)
      	if err != nil {
      		return fmt.Errorf("failed to create client: %w", err)
      	}
      	defer client.Close()
      
      	floorSettingsName := fmt.Sprintf("organizations/%s/locations/global/floorSetting", organizationID)
      
      	// Get the organization floor setting.
      	req := &modelarmorpb.GetFloorSettingRequest{
      		Name: floorSettingsName,
      	}
      
      	response, err := client.GetFloorSetting(ctx, req)
      	if err != nil {
      		return fmt.Errorf("failed to get floor setting: %w", err)
      	}
      
      	// Print the retrieved floor setting using fmt.Fprintf with the io.Writer.
      	fmt.Fprintf(w, "Retrieved org floor setting: %v\n", response)
      
      	return nil
      }
      

    Java

    如需运行此代码,请先设置 Java 开发环境安装 Model Armor Java SDK

    • 查看指定项目的 Model Armor 下限设置。

      
      import com.google.cloud.modelarmor.v1.FloorSetting;
      import com.google.cloud.modelarmor.v1.FloorSettingName;
      import com.google.cloud.modelarmor.v1.GetFloorSettingRequest;
      import com.google.cloud.modelarmor.v1.ModelArmorClient;
      import java.io.IOException;
      
      public class GetProjectFloorSetting {
      
        public static void main(String[] args) throws IOException {
          // TODO(developer): Replace these variables before running the sample.
          String projectId = "your-project-id";
      
          getProjectFloorSetting(projectId);
        }
      
        public static FloorSetting getProjectFloorSetting(String projectId) throws IOException {
      
          // 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 (ModelArmorClient client = ModelArmorClient.create()) {
            String name = FloorSettingName.of(projectId, "global").toString();
      
            GetFloorSettingRequest request = GetFloorSettingRequest.newBuilder().setName(name).build();
      
            FloorSetting floorSetting = client.getFloorSetting(request);
            System.out.println("Fetched floor setting for project: " + projectId);
      
            return floorSetting;
          }
        }
      }
    • 查看指定文件夹的 Model Armor 下限设置。

      
      import com.google.cloud.modelarmor.v1.FloorSetting;
      import com.google.cloud.modelarmor.v1.FloorSettingName;
      import com.google.cloud.modelarmor.v1.GetFloorSettingRequest;
      import com.google.cloud.modelarmor.v1.ModelArmorClient;
      import java.io.IOException;
      
      public class GetFolderFloorSetting {
      
        public static void main(String[] args) throws IOException {
          // TODO(developer): Replace these variables before running the sample.
          String folderId = "your-folder-id";
      
          getFolderFloorSetting(folderId);
        }
      
        public static FloorSetting getFolderFloorSetting(String folderId) throws IOException {
      
          // 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 (ModelArmorClient client = ModelArmorClient.create()) {
            String name = FloorSettingName.ofFolderLocationName(folderId, "global").toString();
      
            GetFloorSettingRequest request = GetFloorSettingRequest.newBuilder().setName(name).build();
      
            FloorSetting floorSetting = client.getFloorSetting(request);
            System.out.println("Fetched floor setting for folder: " + folderId);
      
            return floorSetting;
          }
        }
      }
    • 查看指定组织的 Model Armor 下限设置。

      
      import com.google.cloud.modelarmor.v1.FloorSetting;
      import com.google.cloud.modelarmor.v1.FloorSettingName;
      import com.google.cloud.modelarmor.v1.GetFloorSettingRequest;
      import com.google.cloud.modelarmor.v1.ModelArmorClient;
      import java.io.IOException;
      
      public class GetOrganizationFloorSetting {
      
        public static void main(String[] args) throws IOException {
          // TODO(developer): Replace these variables before running the sample.
          String organizationId = "your-organization-id";
      
          getOrganizationFloorSetting(organizationId);
        }
      
        public static FloorSetting getOrganizationFloorSetting(String organizationId) throws IOException {
      
          // 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 (ModelArmorClient client = ModelArmorClient.create()) {
            String name = FloorSettingName.ofOrganizationLocationName(organizationId, "global")
                .toString();
      
            GetFloorSettingRequest request = GetFloorSettingRequest.newBuilder().setName(name).build();
      
            FloorSetting floorSetting = client.getFloorSetting(request);
            System.out.println("Fetched floor setting for organization: " + organizationId);
      
            return floorSetting;
          }
        }
      }

    Node.js

    如需运行此代码,请先设置 Node.js 开发环境安装 Model Armor Node.js SDK

    • 查看指定项目的 Model Armor 下限设置。

      /**
       * TODO(developer): Uncomment these variables before running the sample.
       */
      // const projectId = 'your-project-id';
      
      const name = `projects/${projectId}/locations/global/floorSetting`;
      
      // Imports the Modelarmor library
      const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
      
      // Instantiates a client
      const modelarmorClient = new ModelArmorClient();
      
      async function getProjectFloorSettings() {
        // Construct request
        const request = {
          name,
        };
      
        // Run request
        const [response] = await modelarmorClient.getFloorSetting(request);
        return response;
      }
      
      return await getProjectFloorSettings();
    • 查看指定文件夹的 Model Armor 下限设置。

      /**
       * TODO(developer): Uncomment these variables before running the sample.
       */
      // const folderId = 'your-folder-id';
      
      const name = `folders/${folderId}/locations/global/floorSetting`;
      
      // Imports the Modelarmor library
      const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
      
      // Instantiates a client
      const modelarmorClient = new ModelArmorClient();
      
      async function getFolderFloorSettings() {
        // Construct request
        const request = {
          name,
        };
      
        const [response] = await modelarmorClient.getFloorSetting(request);
        return response;
      }
      
      return await getFolderFloorSettings();
    • 查看指定组织的 Model Armor 下限设置。

      /**
       * TODO(developer): Uncomment these variables before running the sample.
       */
      // const organizationId = 'your-organization-id';
      const name = `organizations/${organizationId}/locations/global/floorSetting`;
      
      // Imports the Modelarmor library
      const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;
      
      // Instantiates a client
      const modelarmorClient = new ModelArmorClient();
      
      async function getOrganizationFloorSettings() {
        // Construct request
        const request = {
          name,
        };
      
        // Run request
        const [response] = await modelarmorClient.getFloorSetting(request);
        return response;
      }
      
      return await getOrganizationFloorSettings();

    PHP

    如需运行此代码,请先设置 PHP 开发环境安装 Model Armor PHP SDK

    • 查看指定项目的 Model Armor 下限设置。

      use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
      use Google\Cloud\ModelArmor\V1\GetFloorSettingRequest;
      
      /**
       * Gets the floor settings for a given project.
       *
       * @param string $projectId The project Id for which the floor settings is to be retrieved.
       *
       */
      function get_project_floor_settings(string $projectId): void
      {
          $client = new ModelArmorClient();
      
          $floorSettingsName = sprintf('projects/%s/locations/global/floorSetting', $projectId);
      
          $response = $client->getFloorSetting((new GetFloorSettingRequest())->setName($floorSettingsName));
      
          printf("Floor settings retrieved successfully: %s\n", $response->serializeToJsonString());
      }
    • 查看指定文件夹的 Model Armor 下限设置。

      use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
      use Google\Cloud\ModelArmor\V1\GetFloorSettingRequest;
      
      /**
       * Gets the floor settings for a given folder.
       *
       * @param string $folderId The folder Id for which the floor settings is to be retrieved.
       *
       */
      function get_folder_floor_settings(string $folderId): void
      {
          $client = new ModelArmorClient();
      
          $floorSettingsName = sprintf('folders/%s/locations/global/floorSetting', $folderId);
      
          $response = $client->getFloorSetting((new GetFloorSettingRequest())->setName($floorSettingsName));
      
          printf("Floor settings retrieved successfully: %s\n", $response->serializeToJsonString());
      }
    • 查看指定组织的 Model Armor 下限设置。

      use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
      use Google\Cloud\ModelArmor\V1\GetFloorSettingRequest;
      
      /**
       * Gets the floor settings for a given organization.
       *
       * @param string $organizationId The organization Id for which the floor settings is to be retrieved.
       *
       */
      function get_organization_floor_settings(string $organizationId): void
      {
          $client = new ModelArmorClient();
      
          $floorSettingsName = sprintf('organizations/%s/locations/global/floorSetting', $organizationId);
      
          $response = $client->getFloorSetting((new GetFloorSettingRequest())->setName($floorSettingsName));
      
          printf("Floor settings retrieved successfully: %s\n", $response->serializeToJsonString());
      }

    Python

    如需运行此代码,请先设置 Python 开发环境安装 Model Armor Python SDK

    • 查看指定项目的 Model Armor 下限设置。

      
      from google.cloud import modelarmor_v1
      
      # Create the Model Armor client.
      client = modelarmor_v1.ModelArmorClient(transport="rest")
      
      # TODO(Developer): Uncomment below variable.
      # project_id = "YOUR_PROJECT_ID"
      
      floor_settings_name = f"projects/{project_id}/locations/global/floorSetting"
      
      # Get the project floor setting.
      response = client.get_floor_setting(
          request=modelarmor_v1.GetFloorSettingRequest(name=floor_settings_name)
      )
      
      # Print the retrieved floor setting.
      print(response)
      
    • 查看指定文件夹的 Model Armor 下限设置。

      
      from google.cloud import modelarmor_v1
      
      # Create the Model Armor client.
      client = modelarmor_v1.ModelArmorClient(transport="rest")
      
      # TODO(Developer): Uncomment below variable.
      # folder_id = "YOUR_FOLDER_ID"
      
      # Prepare folder floor setting path/name
      floor_settings_name = f"folders/{folder_id}/locations/global/floorSetting"
      
      # Get the folder floor setting.
      response = client.get_floor_setting(
          request=modelarmor_v1.GetFloorSettingRequest(name=floor_settings_name)
      )
      
      # Print the retrieved floor setting.
      print(response)
      
    • 查看指定组织的 Model Armor 下限设置。

      
      from google.cloud import modelarmor_v1
      
      # Create the Model Armor client.
      client = modelarmor_v1.ModelArmorClient(transport="rest")
      
      # TODO(Developer): Uncomment below variable.
      # organization_id = "YOUR_ORGANIZATION_ID"
      
      floor_settings_name = (
          f"organizations/{organization_id}/locations/global/floorSetting"
      )
      
      # Get the organization floor setting.
      response = client.get_floor_setting(
          request=modelarmor_v1.GetFloorSettingRequest(name=floor_settings_name)
      )
      
      # Print the retrieved floor setting.
      print(response)
      

    更新 Model Armor 下限设置

    更新 Model Armor 下限设置,以更改模板的最低要求,从而反映安全政策的变化、更正错误配置或解决下限设置之间的冲突。

    运行以下命令以更新 Model Armor 下限设置。

    控制台

    1. 在 Google Cloud 控制台中,前往 Model Armor 页面。

      前往 Model Armor

    2. 确认您正在查看的是已启用 Model Armor 的项目。

    3. Model Armor 页面上,前往下限设置标签页,然后点击配置下限设置

    4. 更新必填字段,然后点击保存下限设置

    gcloud

       gcloud model-armor floorsettings update --full-uri=<full-uri-of-the-floorsetting>
    

    示例命令:

           gcloud model-armor floorsettings update \
               --malicious-uri-filter-settings-enforcement=ENABLED \
               --pi-and-jailbreak-filter-settings-enforcement=DISABLED \
               --pi-and-jailbreak-filter-settings-confidence-level=LOW_AND_ABOVE \
               --basic-config-filter-enforcement=ENABLED \
               --add-rai-settings-filters='[{"confidenceLevel": "low_and_above", "filterType": "HARASSMENT"}, {"confidenceLevel": "high", "filterType": "SEXUALLY_EXPLICIT"}]'
               --full-uri='folders/FOLDER_ID/locations/global/floorSetting' \
               --enable-floor-setting-enforcement=true
    

    FOLDER_ID 替换为楼层设置的文件夹 ID。

    REST

    • 更新给定项目的 Model Armor 下限设置。

      curl -X PATCH -d '{"filterConfig" :{"piAndJailbreakFilterSettings": { "filterEnforcement": "ENABLED"}, "maliciousUriFilterSettings": { "filterEnforcement": "ENABLED" }, "rai_settings":{"rai_filters":{"filter_type":"DANGEROUS", "confidence_level":"LOW_AND_ABOVE" }, \
      "rai_filters":{"filter_type":"HATE_SPEECH", "confidence_level":"LOW_AND_ABOVE" }, "rai_filters":{"filter_type":"HARASSMENT", "confidence_level":"LOW_AND_ABOVE" }, "rai_filters":{"filter_type":"SEXUALLY_EXPLICIT", "confidence_level":"LOW_AND_ABOVE" }}},"enableFloorSettingEnforcement":"true"}' -H "Content-Type: application/json" -H "Authorization: Bearer $(gcloud auth print-access-token) "https://modelarmor.googleapis.com/v1/projects/PROJECT_ID/locations/global/floorSetting"
    • 更新给定文件夹的 Model Armor 下限设置。

      curl -X PATCH \
        -d '{"filterConfig" :{"piAndJailbreakFilterSettings": { "filterEnforcement": "ENABLED"}, "maliciousUriFilterSettings": { "filterEnforcement": "ENABLED" }},"enableFloorSettingEnforcement":"true"}' \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        "https://modelarmor.googleapis.com/v1/folders/FOLDER_ID/locations/global/floorSetting"
    • 更新给定组织的 Model Armor 下限设置。

      curl -X PATCH \
        -d '{"filterConfig" :{"piAndJailbreakFilterSettings": { "filterEnforcement": "ENABLED"}, "maliciousUriFilterSettings": {
            "filterEnforcement": "ENABLED" }},"enableFloorSettingEnforcement":"true"}' \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
            "https://modelarmor.googleapis.com/v1/organizations/ORGANIZATION_ID/locations/global/floorSetting"

      替换以下内容:

      • PROJECT_ID:楼层设置所对应的项目 ID。
      • FOLDER_ID:楼层设置所对应的文件夹的 ID。
      • ORGANIZATION_ID:相应楼层设置所对应的组织的 ID。

      该更新命令会返回以下响应:

      {
      "name": "projects/PROJECT_ID/locations/global/floorSetting",
      "updateTime": "2024-12-19T15:36:21.318191Z",
      "filterConfig": {
      "piAndJailbreakFilterSettings": {
        "filterEnforcement": "ENABLED"
      },
      "maliciousUriFilterSettings": {
      "filterEnforcement": "ENABLED"
      }
      }
      }

    Go

    如需运行此代码,请先设置 Go 开发环境安装 Model Armor Go SDK

    • 更新给定项目的 Model Armor 下限设置。

      
      import (
      	"context"
      	"fmt"
      	"io"
      
      	modelarmor "cloud.google.com/go/modelarmor/apiv1"
      	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
      	"google.golang.org/api/option"
      )
      
      // updateProjectFloorSettings updates the floor settings of a project.
      //
      // This method updates the floor settings of a project.
      //
      // w io.Writer: The writer to use for logging.
      // projectID string: The ID of the project.
      // locationID string: The ID of the location.
      func updateProjectFloorSettings(w io.Writer, projectID, locationID string) error {
      	ctx := context.Background()
      
      	// Create options for Model Armor client.
      	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
      	// Create the Model Armor client.
      	client, err := modelarmor.NewClient(ctx, opts)
      	if err != nil {
      		return fmt.Errorf("failed to create client: %w", err)
      	}
      	defer client.Close()
      
      	// Prepare project floor setting path/name
      	floorSettingsName := fmt.Sprintf("projects/%s/locations/global/floorSetting", projectID)
      
      	// Update the project floor setting
      	// For more details on filters, please refer to the following doc:
      	// [https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
      	enableEnforcement := true
      	req := &modelarmorpb.UpdateFloorSettingRequest{
      		FloorSetting: &modelarmorpb.FloorSetting{
      			Name: floorSettingsName,
      			FilterConfig: &modelarmorpb.FilterConfig{
      				RaiSettings: &modelarmorpb.RaiFilterSettings{
      					RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
      						{
      							FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
      							ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
      						},
      					},
      				},
      			},
      			EnableFloorSettingEnforcement: &enableEnforcement,
      		},
      	}
      
      	response, err := client.UpdateFloorSetting(ctx, req)
      	if err != nil {
      		return fmt.Errorf("failed to update floor setting: %w", err)
      	}
      
      	// Print the updated config
      	fmt.Fprintf(w, "Updated project floor setting: %+v\n", response)
      
      	return nil
      }
      
    • 更新给定文件夹的 Model Armor 下限设置。

      
      import (
      	"context"
      	"fmt"
      	"io"
      
      	modelarmor "cloud.google.com/go/modelarmor/apiv1"
      	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
      	"google.golang.org/api/option"
      )
      
      // updateFolderFloorSettings updates floor settings of a folder.
      //
      // This method updates the floor settings of a folder.
      //
      // w io.Writer: The writer to use for logging.
      // folderID string: The ID of the folder.
      // locationID string: The ID of the location.
      func updateFolderFloorSettings(w io.Writer, folderID, locationID string) error {
      	ctx := context.Background()
      
      	// Create the Model Armor client.
      	client, err := modelarmor.NewClient(ctx,
      		option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)),
      	)
      	if err != nil {
      		return fmt.Errorf("failed to create client: %w", err)
      	}
      	defer client.Close()
      
      	// Prepare folder floor settings path/name
      	floorSettingsName := fmt.Sprintf("folders/%s/locations/global/floorSetting", folderID)
      
      	// Prepare the floor setting update
      	enableEnforcement := true
      	floorSetting := &modelarmorpb.FloorSetting{
      		Name: floorSettingsName,
      		FilterConfig: &modelarmorpb.FilterConfig{
      			RaiSettings: &modelarmorpb.RaiFilterSettings{
      				RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
      					{
      						FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
      						ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
      					},
      				},
      			},
      		},
      		EnableFloorSettingEnforcement: &enableEnforcement,
      	}
      
      	// Prepare request for updating the floor setting.
      	req := &modelarmorpb.UpdateFloorSettingRequest{
      		FloorSetting: floorSetting,
      	}
      
      	// Update the floor setting.
      	response, err := client.UpdateFloorSetting(ctx, req)
      	if err != nil {
      		return fmt.Errorf("failed to update floor setting: %w", err)
      	}
      
      	// Print the updated config
      	fmt.Fprintf(w, "Updated folder floor setting: %v\n", response)
      
      	return nil
      
      }
      
    • 更新给定组织的 Model Armor 下限设置。

      
      import (
      	"context"
      	"fmt"
      	"io"
      
      	modelarmor "cloud.google.com/go/modelarmor/apiv1"
      	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
      	"google.golang.org/api/option"
      )
      
      // updateOrganizationFloorSettings updates floor settings of an organization.
      //
      // This method updates the floor settings of an organization.
      //
      // w io.Writer: The writer to use for logging.
      // organizationID string: The ID of the organization.
      // locationID string: The ID of the location.
      func updateOrganizationFloorSettings(w io.Writer, organizationID, locationID string) error {
      	ctx := context.Background()
      
      	// Create options for Model Armor client.
      	opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID))
      	// Create the Model Armor client.
      	client, err := modelarmor.NewClient(ctx, opts)
      	if err != nil {
      		return fmt.Errorf("failed to create client: %w", err)
      	}
      	defer client.Close()
      
      	// Prepare organization floor setting path/name
      	floorSettingsName := fmt.Sprintf("organizations/%s/locations/global/floorSetting", organizationID)
      
      	// Update the organization floor setting
      	// For more details on filters, please refer to the following doc:
      	// [https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
      	enableEnforcement := true
      	req := &modelarmorpb.UpdateFloorSettingRequest{
      		FloorSetting: &modelarmorpb.FloorSetting{
      			Name: floorSettingsName,
      			FilterConfig: &modelarmorpb.FilterConfig{
      				RaiSettings: &modelarmorpb.RaiFilterSettings{
      					RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{
      						{
      							FilterType:      modelarmorpb.RaiFilterType_HATE_SPEECH,
      							ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH,
      						},
      					},
      				},
      			},
      			EnableFloorSettingEnforcement: &enableEnforcement,
      		},
      	}
      
      	response, err := client.UpdateFloorSetting(ctx, req)
      	if err != nil {
      		return fmt.Errorf("failed to update floor setting: %w", err)
      	}
      
      	// Print the updated config
      	fmt.Fprintf(w, "Updated org floor setting: %+v\n", response)
      

    Java

    如需运行此代码,请先设置 Java 开发环境安装 Model Armor Java SDK

    Node.js

    如需运行此代码,请先设置 Node.js 开发环境安装 Model Armor Node.js SDK

    • 更新给定项目的 Model Armor 下限设置。

      /**
       * TODO(developer): Uncomment these variables before running the sample.
       */
      // const projectId = 'your-project-id';
      
      const modelarmor = require('@google-cloud/modelarmor');
      const {ModelArmorClient} = modelarmor.v1;
      const {protos} = modelarmor;
      
      // Initiate client
      const client = new ModelArmorClient();
      
      async function updateProjectFloorSettings() {
        const floorSettingsName = `projects/${projectId}/locations/global/floorSetting`;
      
        // Build the floor settings with your preferred filters
        // For more details on filters, please refer to the following doc:
        // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
        const floorSetting = {
          name: floorSettingsName,
          filterConfig: {
            raiSettings: {
              raiFilters: [
                {
                  filterType:
                    protos.google.cloud.modelarmor.v1.RaiFilterType.HARASSMENT,
                  confidenceLevel:
                    protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                      .LOW_AND_ABOVE,
                },
                {
                  filterType:
                    protos.google.cloud.modelarmor.v1.RaiFilterType
                      .SEXUALLY_EXPLICIT,
                  confidenceLevel:
                    protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                      .LOW_AND_ABOVE,
                },
              ],
            },
          },
          enableFloorSettingEnforcement: true,
        };
      
        const request = {
          floorSetting: floorSetting,
        };
      
        const [response] = await client.updateFloorSetting(request);
        return response;
      }
      
      return await updateProjectFloorSettings();
    • 更新给定文件夹的 Model Armor 下限设置。

      /**
       * TODO(developer): Uncomment these variables before running the sample.
       */
      // const folderId = 'your-folder-id';
      
      // Imports the Model Armor library
      const modelarmor = require('@google-cloud/modelarmor');
      const {ModelArmorClient} = modelarmor.v1;
      const {protos} = modelarmor;
      
      // Instantiates a client
      const client = new ModelArmorClient();
      
      async function updateFolderFloorSettings() {
        const floorSettingsName = `folders/${folderId}/locations/global/floorSetting`;
      
        // Build the floor settings with your preferred filters
        // For more details on filters, please refer to the following doc:
        // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
        const floorSetting = {
          name: floorSettingsName,
          filterConfig: {
            raiSettings: {
              raiFilters: [
                {
                  filterType:
                    protos.google.cloud.modelarmor.v1.RaiFilterType.HARASSMENT,
                  confidenceLevel:
                    protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                      .LOW_AND_ABOVE,
                },
                {
                  filterType:
                    protos.google.cloud.modelarmor.v1.RaiFilterType
                      .SEXUALLY_EXPLICIT,
                  confidenceLevel:
                    protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                      .LOW_AND_ABOVE,
                },
              ],
            },
          },
          enableFloorSettingEnforcement: true,
        };
      
        const request = {
          floorSetting: floorSetting,
        };
      
        const [response] = await client.updateFloorSetting(request);
        return response;
      }
      
      return await updateFolderFloorSettings();
    • 更新给定组织的 Model Armor 下限设置。

      /**
       * TODO(developer): Uncomment these variables before running the sample.
       */
      // const organizationId = 'your-organization-id';
      
      const modelarmor = require('@google-cloud/modelarmor');
      const {ModelArmorClient} = modelarmor.v1;
      const {protos} = modelarmor;
      
      const client = new ModelArmorClient();
      
      async function updateOrganizationFloorSettings() {
        const floorSettingsName = `organizations/${organizationId}/locations/global/floorSetting`;
      
        // Build the floor settings with your preferred filters
        // For more details on filters, please refer to the following doc:
        // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
        const floorSetting = {
          name: floorSettingsName,
          filterConfig: {
            raiSettings: {
              raiFilters: [
                {
                  filterType:
                    protos.google.cloud.modelarmor.v1.RaiFilterType.HARASSMENT,
                  confidenceLevel:
                    protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                      .LOW_AND_ABOVE,
                },
                {
                  filterType:
                    protos.google.cloud.modelarmor.v1.RaiFilterType
                      .SEXUALLY_EXPLICIT,
                  confidenceLevel:
                    protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
                      .LOW_AND_ABOVE,
                },
              ],
            },
          },
          enableFloorSettingEnforcement: true,
        };
      
        const request = {
          floorSetting: floorSetting,
        };
      
        const [response] = await client.updateFloorSetting(request);
        return response;
      }
      
      return await updateOrganizationFloorSettings();

    PHP

    如需运行此代码,请先设置 PHP 开发环境安装 Model Armor PHP SDK

    • 更新给定项目的 Model Armor 下限设置。

      use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
      use Google\Cloud\ModelArmor\V1\RaiFilterType;
      use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
      use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest;
      use Google\Cloud\ModelArmor\V1\FilterConfig;
      use Google\Cloud\ModelArmor\V1\FloorSetting;
      use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
      use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
      
      /**
       * Updates the floor settings for a given project.
       *
       * @param string $projectId The project Id for which the floor settings is to be updated.
       *
       */
      function update_project_floor_settings(string $projectId): void
      {
          $client = new ModelArmorClient();
      
          $floorSettingsName = sprintf('projects/%s/locations/global/floorSetting', $projectId);
      
          // Build the floor settings with your preferred filters
          // For more details on filters, please refer to the following doc:
          // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
      
          $raiFilterSetting = (new RaiFilterSettings())
              ->setRaiFilters([
                  (new RaiFilter())
                      ->setFilterType(RaiFilterType::HATE_SPEECH)
                      ->setConfidenceLevel(DetectionConfidenceLevel::HIGH)
              ]);
      
          $filterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
          $floorSetting = (new FloorSetting())
              ->setName($floorSettingsName)
              ->setFilterConfig($filterConfig)
              ->setEnableFloorSettingEnforcement(true);
      
          $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting);
      
          $response = $client->updateFloorSetting($updateRequest);
      
          printf("Floor setting updated: %s\n", $response->getName());
      }
    • 更新给定文件夹的 Model Armor 下限设置。

      use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
      use Google\Cloud\ModelArmor\V1\RaiFilterType;
      use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
      use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest;
      use Google\Cloud\ModelArmor\V1\FilterConfig;
      use Google\Cloud\ModelArmor\V1\FloorSetting;
      use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
      use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
      
      /**
       * Updates the floor settings for a given folder.
       *
       * @param string $folderId The folder Id for which the floor settings is to be updated.
       *
       */
      function update_folder_floor_settings(string $folderId): void
      {
          $client = new ModelArmorClient();
      
          $floorSettingsName = sprintf('folders/%s/locations/global/floorSetting', $folderId);
      
          // Build the floor settings with your preferred filters
          // For more details on filters, please refer to the following doc:
          // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
      
          $raiFilterSetting = (new RaiFilterSettings())
              ->setRaiFilters([
                  (new RaiFilter())
                      ->setFilterType(RaiFilterType::HATE_SPEECH)
                      ->setConfidenceLevel(DetectionConfidenceLevel::HIGH)
              ]);
      
          $filterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
          $floorSetting = (new FloorSetting())
              ->setName($floorSettingsName)
              ->setFilterConfig($filterConfig)
              ->setEnableFloorSettingEnforcement(true);
      
          $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting);
      
          $response = $client->updateFloorSetting($updateRequest);
      
          printf("Floor setting updated: %s\n", $response->getName());
      }
    • 更新给定组织的 Model Armor 下限设置。

      use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
      use Google\Cloud\ModelArmor\V1\RaiFilterType;
      use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
      use Google\Cloud\ModelArmor\V1\UpdateFloorSettingRequest;
      use Google\Cloud\ModelArmor\V1\FilterConfig;
      use Google\Cloud\ModelArmor\V1\FloorSetting;
      use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
      use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
      
      /**
       * Updates the floor settings for a given organization.
       *
       * @param string $organizationId The organization Id for which the floor settings is to be updated.
       *
       */
      function update_organization_floor_settings(string $organizationId)
      {
          $client = new ModelArmorClient();
      
          $floorSettingsName = sprintf('organizations/%s/locations/global/floorSetting', $organizationId);
      
          // Build the floor settings with your preferred filters
          // For more details on filters, please refer to the following doc:
          // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
      
          $raiFilterSetting = (new RaiFilterSettings())
              ->setRaiFilters([
                  (new RaiFilter())
                      ->setFilterType(RaiFilterType::HATE_SPEECH)
                      ->setConfidenceLevel(DetectionConfidenceLevel::HIGH)
              ]);
      
          $filterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);
          $floorSetting = (new FloorSetting())
              ->setName($floorSettingsName)
              ->setFilterConfig($filterConfig)
              ->setEnableFloorSettingEnforcement(true);
      
          $updateRequest = (new UpdateFloorSettingRequest())->setFloorSetting($floorSetting);
      
          $response = $client->updateFloorSetting($updateRequest);
      
          printf("Floor setting updated: %s\n", $response->getName());
      }

    Python

    如需运行此代码,请先设置 Python 开发环境安装 Model Armor Python SDK

    查看有关违反下限设置的发现结果

    每项 Model Armor 发现结果都会识别一次违反下限设置的情况。当 Model Armor 模板未能达到资源层次结构下限设置定义的最低安全标准时,就会发生违规。基准设置用于定义模板的最低要求。违反下限设置可能是由于模板缺少所需的过滤条件,或未达到这些过滤条件所要求的最低置信度级别。检测到违规行为后,系统会在 Security Command Center 中生成高严重性发现结果。该发现结果会指明所违反的下限设置、不合规的模板以及违规详情。

    以下示例展示了发现的 sourceProperties 字段。此违规行为与恶意 URI 过滤条件相关,发生的原因是 maliciousUriFilterSettings 的模板设置是 DISABLED,但下限设置要求它是 ENABLED

    {
      "filterConfig": {
        "raiSettings": {
          "raiFilters": [
            {
              "filterType": "HATE_SPEECH",
              "confidenceLevel": {
                "floorSettings": "LOW_AND_ABOVE",
                "template": "MEDIUM_AND_ABOVE"
              }
            },
            {
              "filterType": "HARASSMENT",
              "confidenceLevel": {
                "floorSettings": "MEDIUM_AND_ABOVE",
                "template": "HIGH"
              }
            }
          ]
        },
        "piAndJailbreakFilterSettings": {
          "confidenceLevel": {
            "floorSettings": "LOW_AND_ABOVE",
            "template": "HIGH"
          }
        },
        "maliciousUriFilterSettings": {
          "floorSettings": "ENABLED",
          "template": "DISABLED"
        }
      }
    }

    后续步骤