创建和管理模板

您可以使用 Model Armor 模板来配置针对 AI 应用的提示和回答进行筛选的过滤选项。可通过模板为多个安全类别提供自定义的过滤条件及阈值。本文档介绍了如何创建和管理 Model Armor 模板。如需了解详情,请参阅 Model Armor 模板。

使用单区域或多区域端点

使用 Model Armor 模板时,您必须使用与模板位置匹配的区域级或多区域级端点 (modelarmor.LOCATION.rep.googleapis.com)。

全球端点 (modelarmor.googleapis.com) 不支持管理 Model Armor 模板,也不支持清理提示和回答。

何时使用 Model Armor 模板

以下是一些常见使用场景:

  • 在应用之间实现标准化筛查:定义可供多个工作负载引用的集中式过滤配置和阈值级别。
  • 自定义检测阈值和配置:调整过滤器的敏感度(例如设置低、中或高置信度阈值),并针对不同的使用情形或环境调整过滤器配置。
  • 配置多类别防御:将 Sensitive Data Protection、越狱检测、恶意 URI 检查和提示注入过滤条件整合到一项政策中。
  • 隔离开发政策和生产政策:维护单独的模板,以便在预演环境中测试更严格的过滤规则,然后再将其推广到生产服务。

准备工作

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

获取所需的权限

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

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

启用 API

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

控制台

  1. 启用 Model Armor API(如果尚未启用)。

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您是项目创建者,则可能已通过 Owner 角色 (roles/owner) 获得此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获得此权限。了解如何授予角色。

    启用 API

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

gcloud

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

  1. 在 Google Cloud 控制台中,激活 Cloud Shell。

    激活 Cloud Shell

    Cloud Shell 会话随即会在 Google Cloud 控制台的底部启动,并显示命令行提示符。Cloud Shell 是一个已安装 Google Cloud CLI 且已为当前项目设置值的 Shell 环境。该会话可能需要几秒钟时间来完成初始化。

  2. 启用 Model Armor API(如果尚未启用):

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您创建了项目,则可能已经通过 Owner 角色 (roles/owner) 拥有此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获取此权限。了解如何授予角色。

    gcloud services enable modelarmor.googleapis.com

  3. 使用 gcloud CLI 设置 API 端点替换项。

使用 gcloud CLI 设置 API 端点替换项

如果您将 gcloud CLI 与 Model Armor 搭配使用,并且想要使用默认 us 多区域以外的区域或多区域,才需要执行此步骤。您必须手动设置 API 端点替换项,以确保 gcloud CLI 正确地将请求路由到 Model Armor 服务。

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

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

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

创建 Model Armor 模板

Model Armor 模板定义了 Model Armor 用于针对各类安全风险对提示和回答进行筛选的特定过滤条件及阈值。如需创建 Model Armor 模板,请按以下步骤操作:

控制台

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

    前往 Model Armor

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

  3. 在 Model Armor 页面上,点击创建模板。 系统会显示创建模板页面。

  4. 指定模板 ID。模板 ID 可以包含字母、数字、下划线或连字符。不得超过 63 个字符;不能包含空格,也不能以连字符开头。

  5. 在位置类型部分中,选择将运行 Model Armor 操作的区域或多区域。您以后无法更改位置。

  6. 可选:在数据驻留合规性部分中,选择是否启用数据驻留强制执行。默认情况下,任何未在您所选位置本地托管的 Model Armor 功能都会被停用,以防止您的数据跨越到其他司法管辖区。本部分列出了已停用的功能。

    您可以停用强制执行数据驻留选项,从而启用受数据驻留强制执行限制的功能。此操作允许跨司法管辖区路由您的数据。

  7. 可选:在标签部分中,添加您要用于对相关模板进行分组的任何键值对。

  8. 在过滤条件版本部分中,选择过滤条件版本号或过滤条件版本别名。

  9. 选择模态,以指定您要筛查的是屏幕文字、图片还是两者兼而有之。

  10. 在检测部分,配置检测设置。

  11. 可选:如果您选择 Sensitive Data Protection 检测,则需要配置 Sensitive Data Protection 设置。

  12. 在 Responsible AI 部分,为每个内容过滤条件设置置信度。

  13. 可选:展开其他配置(可选)部分,然后配置以下任意设置:

  14. 点击创建。

gcloud

运行以下命令:

 gcloud model-armor templates create TEMPLATE_ID --project=PROJECT_ID --location=LOCATION \
     --rai-settings-filters='[{ "filterType": "HATE_SPEECH", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "HARASSMENT", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "SEXUALLY_EXPLICIT", "confidenceLevel": "MEDIUM_AND_ABOVE" }]' \
     --basic-config-filter-enforcement=enabled  \
     --pi-and-jailbreak-filter-settings-enforcement=enabled \
     --pi-and-jailbreak-filter-settings-confidence-level=HIGH \
     --malicious-uri-filter-settings-enforcement=enabled \
     --template-metadata-custom-llm-response-safety-error-code=798 \
     --template-metadata-custom-llm-response-safety-error-message="test template llm response evaluation failed" \
     --template-metadata-custom-prompt-safety-error-code=799 \
     --template-metadata-custom-prompt-safety-error-message="test template prompt evaluation failed" \
     --template-metadata-ignore-partial-invocation-failures \
     --template-metadata-log-operations \
     --template-metadata-log-sanitize-operations

替换以下内容:

  • LOCATION:模板所在的位置。
  • TEMPLATE_ID:模板的 ID。
  • PROJECT_ID:模板所属项目的 ID。

REST

使用以下命令创建新的 Model Armor 模板。

  curl -X POST \
    -d "FILTER_CONFIG" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

替换以下内容:

  • FILTER_CONFIG:模板的过滤条件配置(采用 JSON 格式)。
  • PROJECT_ID:模板所属项目的 ID。
  • TEMPLATE_ID:要创建的模板的 ID。
  • LOCATION:模板所在的位置。

以下示例展示了 Model Armor 过滤条件配置 (FilterConfig),您可以在其中定义要检测的内容。在此示例中,Responsible AI 过滤条件针对仇恨言论、骚扰、危险内容和露骨色情内容配置了不同的置信度。此外,启用了提示注入和越狱检测过滤条件并将其置信度配置为 HIGH,这意味着,只有可能性为“高”的内容才会被标记。还启用了恶意 URI 过滤条件。

  export FILTER_CONFIG='{
   "filterConfig": {
    "raiSettings": {
     "raiFilters": [{
       "filterType": "HATE_SPEECH",
       "confidenceLevel": "MEDIUM_AND_ABOVE"
      }, {
      "filterType": "HARASSMENT",
      "confidenceLevel": "HIGH"
    }, {
      "filterType": "DANGEROUS",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    },{
      "filterType": "SEXUALLY_EXPLICIT",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    }]
  },

  "piAndJailbreakFilterSettings": {
    "filterEnforcement": "ENABLED",
    "confidenceLevel": "HIGH"
  },
  "maliciousUriFilterSettings": {
    "filterEnforcement": "ENABLED"
  }
 }
}'

curl -X POST \
 -d "$FILTER_CONFIG" \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

如需定义 Model Armor 处理操作、错误和日志的方式,请在命令中设置模板元数据 (TemplateMetadata)。模板元数据包括语言检测、模态和数据驻留合规性设置。

以下示例创建了一个 Model Armor 模板配置,该配置启用了多语言检测和模态(图片和文本)。

  export TEMPLATE_CONFIG='{
   "filterConfig": {
    "raiSettings": {
     "raiFilters": [{
       "filterType": "HATE_SPEECH",
       "confidenceLevel": "MEDIUM_AND_ABOVE"
      }, {
      "filterType": "HARASSMENT",
      "confidenceLevel": "HIGH"
    }, {
      "filterType": "DANGEROUS",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    },{
      "filterType": "SEXUALLY_EXPLICIT",
      "confidenceLevel": "MEDIUM_AND_ABOVE"
    }]
  },

  "piAndJailbreakFilterSettings": {
    "filterEnforcement": "ENABLED",
    "confidenceLevel": "HIGH"
  },
  "maliciousUriFilterSettings": {
    "filterEnforcement": "ENABLED"
  }
 },
 "templateMetadata": {
    "multiLanguageDetection": {
      "enableMultiLanguageDetection": true
    },
    "modalities": ["MODALITY_IMAGE", "MODALITY_TEXT"]
  }
}'

curl -X POST \
 -d "$TEMPLATE_CONFIG"  \
 -H "Content-Type: application/json" \
 -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

C#

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

using Google.Api.Gax.ResourceNames;
using Google.Cloud.ModelArmor.V1;
using System.Collections.Generic;

public class CreateTemplateSample
{
    public Template CreateTemplate(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        // Build the Model Armor template 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

        // Configure Responsible AI filter with multiple categories and their confidence
        // levels.
        RaiFilterSettings raiFilterSettings = new RaiFilterSettings();
        List<RaiFilterSettings.Types.RaiFilter> filters =
            new List<RaiFilterSettings.Types.RaiFilter>
            {
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.Dangerous,
                    ConfidenceLevel = DetectionConfidenceLevel.High,
                },
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.HateSpeech,
                    ConfidenceLevel = DetectionConfidenceLevel.High,
                },
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.SexuallyExplicit,
                    ConfidenceLevel = DetectionConfidenceLevel.LowAndAbove,
                },
                new RaiFilterSettings.Types.RaiFilter
                {
                    FilterType = RaiFilterType.Harassment,
                    ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                },
            };

        raiFilterSettings.RaiFilters.Add(filters);

        Template template = new Template
        {
            FilterConfig = new FilterConfig { RaiSettings = raiFilterSettings },
        };

        CreateTemplateRequest request = new CreateTemplateRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation(projectId, locationId),
            TemplateId = templateId,
            Template = template,
        };

        Template createdTemplate = client.CreateTemplate(request);
        System.Console.WriteLine($"Created template: {createdTemplate.Name}");

        return createdTemplate;
    }
}

Go

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


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// createModelArmorTemplate method creates a new
// Model Armor template with the provided settings.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the Google Cloud project.
// locationID string: The ID of the Google Cloud location.
// templateID string: The ID of the template to create.
func createModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create the call options
	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 for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Build the Model Armor template 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
	template := &modelarmorpb.Template{
		FilterConfig: &modelarmorpb.FilterConfig{
			PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
				FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
				ConfidenceLevel:   modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE,
			},
			MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
				FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
			},
		},
	}
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Prepare the request for creating the template.
	req := &modelarmorpb.CreateTemplateRequest{
		Parent:     parent,
		TemplateId: templateID,
		Template:   template,
	}

	// Create the template.
	response, err := client.CreateTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create template: %v", err)
	}

	// Print the new template name using fmt.Fprintf with the io.Writer.
	fmt.Fprintf(w, "Created template: %s\n", response.Name)

	return err
}

Java

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


import com.google.cloud.modelarmor.v1.CreateTemplateRequest;
import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
import com.google.cloud.modelarmor.v1.FilterConfig;
import com.google.cloud.modelarmor.v1.LocationName;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
import com.google.cloud.modelarmor.v1.RaiFilterType;
import com.google.cloud.modelarmor.v1.Template;
import java.io.IOException;
import java.util.List;

public class CreateTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1. 
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";

    createTemplate(projectId, locationId, templateId);
  }

  public static Template createTemplate(String projectId, String locationId, String templateId)
      throws IOException {
    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the 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(modelArmorSettings)) {
      String parent = LocationName.of(projectId, locationId).toString();

      // Build the Model Armor template 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

      // Configure Responsible AI filter with multiple categories and their confidence
      // levels.
      RaiFilterSettings raiFilterSettings = RaiFilterSettings.newBuilder()
          .addAllRaiFilters(
              List.of(
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.DANGEROUS)
                      .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                      .build(),
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.HATE_SPEECH)
                      .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                      .build(),
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
                      .setConfidenceLevel(DetectionConfidenceLevel.LOW_AND_ABOVE)
                      .build(),
                  RaiFilter.newBuilder()
                      .setFilterType(RaiFilterType.HARASSMENT)
                      .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                      .build()))
          .build();

      FilterConfig modelArmorFilter = FilterConfig.newBuilder()
          .setRaiSettings(raiFilterSettings)
          .build();

      Template template = Template.newBuilder()
          .setFilterConfig(modelArmorFilter)
          .build();

      CreateTemplateRequest request = CreateTemplateRequest.newBuilder()
          .setParent(parent)
          .setTemplateId(templateId)
          .setTemplate(template)
          .build();

      Template createdTemplate = client.createTemplate(request);
      System.out.println("Created template: " + createdTemplate.getName());

      return createdTemplate;
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'your-project-id';
// const locationId = 'us-central1';
// const templateId = 'your-template-id';

const parent = `projects/${projectId}/locations/${locationId}`;

// 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({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

/**  Build the Model Armor template 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 templateConfig = {
  filterConfig: {
    raiSettings: {
      raiFilters: [
        {
          filterType:
            protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH,
          confidenceLevel:
            protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH,
        },
        {
          filterType:
            protos.google.cloud.modelarmor.v1.RaiFilterType.SEXUALLY_EXPLICIT,
          confidenceLevel:
            protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel
              .MEDIUM_AND_ABOVE,
        },
      ],
    },
  },
};

// Construct request
const request = {
  parent,
  templateId,
  template: templateConfig,
};

// Create the template
const [response] = await client.createTemplate(request);
return response;

PHP

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

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\Template;
use Google\Cloud\ModelArmor\V1\CreateTemplateRequest;
use Google\Cloud\ModelArmor\V1\FilterConfig;
use Google\Cloud\ModelArmor\V1\RaiFilterType;
use Google\Cloud\ModelArmor\V1\RaiFilterSettings;
use Google\Cloud\ModelArmor\V1\RaiFilterSettings\RaiFilter;
use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;

/**
 * Create a Model Armor template.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function create_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $parent = $client->locationName($projectId, $locationId);

    /**
     * Build the Model Armor template with preferred filters.
     * For more details on filters, refer to:
     * https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters
     */

    $raiFilters = [
        (new RaiFilter())
            ->setFilterType(RaiFilterType::DANGEROUS)
            ->setConfidenceLevel(DetectionConfidenceLevel::HIGH),
        (new RaiFilter())
            ->setFilterType(RaiFilterType::HATE_SPEECH)
            ->setConfidenceLevel(DetectionConfidenceLevel::HIGH),
        (new RaiFilter())
            ->setFilterType(RaiFilterType::SEXUALLY_EXPLICIT)
            ->setConfidenceLevel(DetectionConfidenceLevel::LOW_AND_ABOVE),
        (new RaiFilter())
            ->setFilterType(RaiFilterType::HARASSMENT)
            ->setConfidenceLevel(DetectionConfidenceLevel::MEDIUM_AND_ABOVE),
    ];

    $raiFilterSetting = (new RaiFilterSettings())->setRaiFilters($raiFilters);

    $templateFilterConfig = (new FilterConfig())->setRaiSettings($raiFilterSetting);

    $template = (new Template())->setFilterConfig($templateFilterConfig);

    $request = (new CreateTemplateRequest)
        ->setParent($parent)
        ->setTemplateId($templateId)
        ->setTemplate($template);

    $response = $client->createTemplate($request);

    printf('Template created: %s' . PHP_EOL, $response->getName());
}

Python

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


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "your-google-cloud-project-id"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Build the Model Armor template 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
template = modelarmor_v1.Template(
    filter_config=modelarmor_v1.FilterConfig(
        pi_and_jailbreak_filter_settings=modelarmor_v1.PiAndJailbreakFilterSettings(
            filter_enforcement=modelarmor_v1.PiAndJailbreakFilterSettings.PiAndJailbreakFilterEnforcement.ENABLED,
            confidence_level=modelarmor_v1.DetectionConfidenceLevel.MEDIUM_AND_ABOVE,
        ),
        malicious_uri_filter_settings=modelarmor_v1.MaliciousUriFilterSettings(
            filter_enforcement=modelarmor_v1.MaliciousUriFilterSettings.MaliciousUriFilterEnforcement.ENABLED,
        ),
    ),
)

# Prepare the request for creating the template.
request = modelarmor_v1.CreateTemplateRequest(
    parent=f"projects/{project_id}/locations/{location_id}",
    template_id=template_id,
    template=template,
)

# Create the template.
response = client.create_template(request=request)

# Print the new template name.
print(f"Created template: {response.name}")

设置数据驻留合规性

默认情况下,您创建的任何模板都会严格执行数据留存合规性要求。也就是说,任何并非托管在涵盖模板所在区域的管辖范围内的 Model Armor 功能都会被停用。数据驻留合规性强制执行可防止您的数据离开其管辖范围。

对于优先考虑全面安全过滤而非严格数据驻留的模板,您可以针对使用中和传输中的数据停用数据驻留强制执行功能。为此,您可以通过Google Cloud 控制台停用强制执行数据驻留选项,也可以通过 Model Armor API 将 data_residency_compliant 设置为 false。无论此选项处于何种状态,您的静态数据都将始终符合数据驻留要求。

在模板中停用数据驻留合规性后,您便允许跨管辖区路由数据。也就是说,当模板所在管辖区内没有特定功能时,Model Armor 可能会将请求路由到其他管辖区。

停用数据驻留合规性后,除了图片模态以外的所有 Model Armor 功能都将启用,图片模态仍仅限于 us 和 eu 多区域。

选择过滤条件版本

Model Armor 过滤条件版本可在生产工作负载的稳定性和对更新后的威胁检测模型的访问权限之间实现平衡。您可以在模板级层配置过滤条件版本。过滤条件版本适用于相应模板中的所有过滤条件,但不使用过滤条件版本的过滤条件中列出的过滤条件除外。 如需了解详情,请参阅为模板设置过滤条件版本。

选择模态

使用模态来指定您是否要扫描以下内容:

  • 全部:扫描文字和图片。
  • 特定模态:
    • 文本:扫描文本字符串和嵌入在支持的文件格式中的文本。
    • 图片:扫描图片。

如需了解详情,请参阅图片筛查和清理包含图片的提示。

配置检测

检测是指 Model Armor 对提示和回答执行的具体检查。Model Armor 提供了一个灵活的检测配置系统,可让您根据需要调整针对 AI 应用设置的保护级别。您可以在创建模板时配置检测。Model Armor 会对提示和回答执行以下检测检查:

  • 恶意网址检测:识别旨在危害用户或系统的网址 (URL)。这些网址可能会导致您访问钓鱼式攻击网站、下载恶意软件或遭受其他网络攻击。如需了解详情,请参阅恶意网址检测。

  • 提示注入和越狱检测:检测提示中的恶意内容和越狱尝试。我们建议您将置信度设置为高,以最大限度地减少假正例,并确保检测行为的一致性。 即使将置信度设置为高,假正例率也会降低,但您可能仍会在极少数情况下看到假正例。如需了解详情,请参阅提示注入和越狱检测。

  • Sensitive Data Protection:检测敏感数据,并帮助防止其因提示注入等攻击而意外泄露。如需了解详情,请参阅 Sensitive Data Protection。

配置 Sensitive Data Protection 设置

Model Armor 利用 Sensitive Data Protection 来识别和防止 LLM 互动中敏感信息的泄露。如需了解详情,请参阅 Sensitive Data Protection。

Model Armor 提供了两种模式来配置 Sensitive Data Protection:

  • 基本:该方法更为简单,使用预定义的 infoType 来检测敏感数据。如需详细了解预定义的 infoType,请参阅 Sensitive Data Protection 基本配置。

  • 高级:该方法可提供更灵活的配置,使用 Sensitive Data Protection 服务中定义的检查模板作为敏感数据 infoType 的单一来源。

如果您选择高级模式,则需要指定以下参数:

  • 检查模板:用于保存检查扫描作业配置信息的模板,包括要使用的预定义或自定义检测器。 请按以下格式输入模板名称: projects/projectId/locations/locationId/inspectTemplates/templateName

  • 可选:去标识化模板:此类模板用于保存去标识化作业的配置信息,包括 infoType 和结构化数据集转换。按以下格式输入去标识化模板的标识符: projects/projectId/locations/locationId/deidentifyTemplates/templateName

验证 Sensitive Data Protection 中是否存在检查模板和去标识化模板。如果模板位于其他项目中,则必须向 Model Armor 服务代理授予该项目的 DLP User 角色 (roles/dlp.user) 和 DLP Reader 角色 (roles/dlp.reader)。

设置置信度

置信度表示发现结果与内容过滤条件类型匹配的可能性。您可以为每个内容过滤条件设置置信度。可能的值如下:

  • 无:不检测任何内容。
  • “低”及以上:检测置信度为“低”“中等”或“高”的内容。
  • “中等”及以上:检测置信度为“中等”或“高”的内容。
  • “高”:检测置信度为“高”的内容。

若要更严格地执行,请将置信度设置为“低”及以上,以检测大部分属于某种内容过滤器类型的内容。

如需针对模板启用全面的日志记录,请参阅 Model Armor 审核和平台日志记录。

定义模板的强制执行类型

如需配置 Model Armor 处理检测结果的方式,请设置强制执行类型。

在模板配置的 template_metadata 字段中,将 enforcement_type 设置为 INSPECT_ONLY 或 INSPECT_AND_BLOCK。

export TEMPLATE_CONFIG='{
   "filter_config": {
    "rai_settings": {
     "rai_filters": [{
       "filter_type": "HATE_SPEECH",
       "confidence_level": "MEDIUM_AND_ABOVE"
      }, {
      "filter_type": "HARASSMENT",
      "confidence_level": "MEDIUM_AND_ABOVE"
    }, {
      "filter_type": "DANGEROUS",
      "confidence_level": "MEDIUM_AND_ABOVE"
    },{
      "filter_type": "SEXUALLY_EXPLICIT",
      "confidence_level": "MEDIUM_AND_ABOVE"
    }]
  },
  "pi_and_jailbreak_filter_settings": {
    "filter_enforcement": "ENABLED",
    "confidence_level": "HIGH"
  },
  "malicious_uri_filter_settings": {
    "filter_enforcement": "ENABLED"
  }
 },
 "template_metadata": {
    "enforcement_type": "INSPECT_ONLY",
    "multi_language_detection": {
      "enableMultiLanguageDetection": true
    }
  }
}'

curl -X POST \
    -d "$TEMPLATE_CONFIG"  \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates?template_id=TEMPLATE_ID"

替换以下内容:

  • PROJECT_ID:模板所属项目的 ID。
  • TEMPLATE_ID:要创建的模板的 ID。
  • LOCATION:模板所在的位置。

配置特定于模板的排除规则

Model Armor 排除规则有助于针对已获批准的特定领域术语、独特的业务背景或临时性运营变通方案来缓解误报检测问题。您可以在模板级配置这些规则,以便支持的过滤条件排除良性内容,防止触发检测。如需了解详情,请参阅配置特定于模板的排除规则。

查看 Model Armor 模板

查看现有模板,了解可用的配置,以及排查和解决针对提示和回答进行筛选时出现的问题。

控制台

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

    前往 Model Armor

  2. 确认您正在查看的是已启用 Model Armor 的项目。系统会显示 Model Armor 页面,其中列出了为您的项目创建的模板。

  3. 点击列表中的任意模板即可查看其详细信息。

gcloud

运行以下命令:

gcloud model-armor templates describe TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

替换以下内容:

  • LOCATION:模板所在的位置。
  • TEMPLATE_ID:模板的 ID。
  • PROJECT_ID:模板所属项目的 ID。

REST

运行以下命令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

替换以下内容:

  • PROJECT_ID:模板所属项目的 ID。
  • TEMPLATE_ID:要查看的模板的 ID。
  • LOCATION:模板所在的位置。

C#

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

using Google.Cloud.ModelArmor.V1;
using System;

public class GetTemplateSample
{
    public Template GetTemplate(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        GetTemplateRequest request = new GetTemplateRequest
        {
            TemplateName = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId),
        };

        Template template = client.GetTemplate(request);
        Console.WriteLine($"Retrieved template: {template.Name}");

        return template;
    }
}

Go

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


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// getModelArmorTemplate method retrieves a Model Armor template.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The location of the template.
// templateID string: The ID of the template.
func getModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create options for the 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 for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Initialize request arguments.
	req := &modelarmorpb.GetTemplateRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
	}

	// Get the template.
	response, err := client.GetTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get template: %w", err)
	}

	// Print the template name using fmt.Fprintf with the io.Writer.
	fmt.Fprintf(w, "Retrieved template: %s\n", response.Name)

	return nil
}

Java

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


import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.Template;
import com.google.cloud.modelarmor.v1.TemplateName;
import java.io.IOException;

public class GetTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "your-location-id";
    String templateId = "your-template-id";

    getTemplate(projectId, locationId, templateId);
  }

  public static Template getTemplate(String projectId, String locationId, String templateId)
      throws IOException {
    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);

    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the 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(modelArmorSettings)) {
      // Build the template name.
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Get the template.
      Template template = client.getTemplate(name);

      // Find more details about Template object here:
      // https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#Template
      System.out.printf("Retrieved template: %s\n", template.getName());

      return template;
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const templateId = 'my-template';

const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`;

// Imports the Model Armor library
const {ModelArmorClient} = require('@google-cloud/modelarmor').v1;

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

const request = {
  name: name,
};

// Run request
const [response] = await client.getTemplate(request);
return response;

PHP

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

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\GetTemplateRequest;

/**
 * Gets a Model Armor template.
 *
 * @param string $projectId The ID of your Google Cloud Platform project (e.g. 'my-project').
 * @param string $locationId The ID of the location where the template is stored (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function get_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $name = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $locationId, $templateId);

    $getTemplateRequest = (new GetTemplateRequest())->setName($name);

    $response = $client->getTemplate($getTemplateRequest);

    printf('Template retrieved: %s' . PHP_EOL, $response->getName());
}

Python

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


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Initialize request arguments.
request = modelarmor_v1.GetTemplateRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
)

# Get the template.
response = client.get_template(request=request)
print(response.name)

更新 Model Armor 模板

定期更新模板,以确保 AI 应用的安全状况始终可靠、有效。

控制台

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

    前往 Model Armor

  2. 确认您正在查看的是已启用 Model Armor 的项目。系统会显示 Model Armor 页面,其中列出了为您的组织创建的模板。

  3. 点击要从列表中更新的模板。系统会显示模板详细信息页面。

  4. 点击修改。

  5. 更新必需参数,然后点击保存。

gcloud

如需更新模板,请运行 gcloud model-armor templates update 命令,并添加要修改的设置的标志。

例如,以下命令会更新模板的过滤条件设置和元数据:

gcloud model-armor templates update TEMPLATE_ID \
    --project=PROJECT_ID \
    --location=LOCATION \
    --rai-settings-filters='[{ "filterType": "HATE_SPEECH", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "HARASSMENT", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "DANGEROUS", "confidenceLevel": "MEDIUM_AND_ABOVE" },{ "filterType": "SEXUALLY_EXPLICIT", "confidenceLevel": "MEDIUM_AND_ABOVE" }]' \
    --basic-config-filter-enforcement=enabled \
    --pi-and-jailbreak-filter-settings-enforcement=enabled \
    --pi-and-jailbreak-filter-settings-confidence-level=HIGH \
    --malicious-uri-filter-settings-enforcement=enabled \
    --template-metadata-custom-llm-response-safety-error-code=798 \
    --template-metadata-custom-llm-response-safety-error-message="test template llm response evaluation failed" \
    --template-metadata-custom-prompt-safety-error-code=799 \
    --template-metadata-custom-prompt-safety-error-message="test template prompt evaluation failed" \
    --template-metadata-ignore-partial-invocation-failures \
    --template-metadata-log-operations \
    --template-metadata-log-sanitize-operations

替换以下内容:

  • TEMPLATE_ID:模板的 ID。
  • PROJECT_ID:模板所属项目的 ID。
  • LOCATION:模板所在的位置。

REST

运行以下命令:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d "$FILTER_CONFIG" \
  "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID?updateMask=UPDATE_MASK"

替换以下内容:

  • PROJECT_ID:模板所属项目的 ID。
  • LOCATION:模板所在的位置。
  • TEMPLATE_ID:模板的 ID。
  • UPDATE_MASK:您要更新的字段,例如 filterConfig、filterConfig.piAndJailbreakFilterSettings 或 filterConfig.filterRuleSettings。如需了解详情,请参阅更新模板中的排除规则。 如果将此字段留空,则系统会更新整个过滤条件配置。

所有其他字段都是不可变的。尝试更新其他字段(例如,尝试更新模板名称)会导致错误。

C#

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

using Google.Cloud.ModelArmor.V1;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;

namespace ModelArmor.Samples
{
    public class UpdateTemplateSample
    {
        public Template UpdateTemplate(
            string projectId = "my-project",
            string locationId = "us-central1",
            string templateId = "my-template"
        )
        {
            // Construct the API endpoint URL.
            ModelArmorClientBuilder clientBuilder = new ModelArmorClientBuilder
            {
                Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
            };

            // Create the client.
            ModelArmorClient client = clientBuilder.Build();

            // Get the template name.
            TemplateName name = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId);

            // Build the updated Model Armor template with modified 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
            RaiFilterSettings raiFilterSettings = new RaiFilterSettings();
            List<RaiFilterSettings.Types.RaiFilter> filters =
                new List<RaiFilterSettings.Types.RaiFilter>
                {
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.Dangerous,
                        ConfidenceLevel = DetectionConfidenceLevel.High,
                    },
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.HateSpeech,
                        ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                    },
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.SexuallyExplicit,
                        ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                    },
                    new RaiFilterSettings.Types.RaiFilter
                    {
                        FilterType = RaiFilterType.Harassment,
                        ConfidenceLevel = DetectionConfidenceLevel.MediumAndAbove,
                    },
                };

            raiFilterSettings.RaiFilters.Add(filters);

            Template template = new Template
            {
                TemplateName = name,
                FilterConfig = new FilterConfig { RaiSettings = raiFilterSettings },
            };

            // Create a field mask to specify which fields to update.
            // Ref: https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
            FieldMask updateMask = new FieldMask { Paths = { "filter_config.rai_settings" } };

            // Prepare the request.
            UpdateTemplateRequest request = new UpdateTemplateRequest
            {
                Template = template,
                UpdateMask = updateMask,
            };

            // Send the request.
            Template updatedTemplate = client.UpdateTemplate(request);
            Console.WriteLine($"Updated template: {updatedTemplate.Name}");

            return updatedTemplate;
        }
    }
}

Go

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


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// updateModelArmorTemplate updates a Model Armor template.
//
// updateModelArmorTemplate method updates a Model Armor template.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the project.
// locationID string: The ID of the location.
// templateID string: The ID of the template.
func updateModelArmorTemplate(w io.Writer, projectID, locationID, templateID 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 for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Build the Model Armor template 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters)
	updatedTemplate := &modelarmorpb.Template{
		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
		FilterConfig: &modelarmorpb.FilterConfig{
			PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{
				FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED,
				ConfidenceLevel:   modelarmorpb.DetectionConfidenceLevel_LOW_AND_ABOVE,
			},
			MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{
				FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED,
			},
		},
	}

	// Initialize request argument(s).
	req := &modelarmorpb.UpdateTemplateRequest{
		Template: updatedTemplate,
	}

	// Update the template.
	response, err := client.UpdateTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update template: %w", err)
	}

	// Print the updated filters in the template.
	fmt.Fprintf(w, "Updated Filter Config: %+v\n", response.FilterConfig)

	return nil
}

Java

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


import com.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
import com.google.cloud.modelarmor.v1.FilterConfig;
import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings;
import com.google.cloud.modelarmor.v1.RaiFilterSettings.RaiFilter;
import com.google.cloud.modelarmor.v1.RaiFilterType;
import com.google.cloud.modelarmor.v1.Template;
import com.google.cloud.modelarmor.v1.TemplateName;
import com.google.cloud.modelarmor.v1.UpdateTemplateRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.List;

public class UpdateTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1. 
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";

    updateTemplate(projectId, locationId, templateId);
  }

  public static Template updateTemplate(String projectId, String locationId, String templateId)
      throws IOException {
    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the 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(modelArmorSettings)) {
      // Get the template name.
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Build the updated Model Armor template with modified 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
      RaiFilterSettings raiFilterSettings =
          RaiFilterSettings.newBuilder()
              .addAllRaiFilters(
                  List.of(
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.DANGEROUS)
                          .setConfidenceLevel(DetectionConfidenceLevel.HIGH)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.HATE_SPEECH)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.HARASSMENT)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build(),
                      RaiFilter.newBuilder()
                          .setFilterType(RaiFilterType.SEXUALLY_EXPLICIT)
                          .setConfidenceLevel(DetectionConfidenceLevel.MEDIUM_AND_ABOVE)
                          .build()))
              .build();

      FilterConfig modelArmorFilter = FilterConfig.newBuilder()
          .setRaiSettings(raiFilterSettings)
          .build();

      Template template = Template.newBuilder()
          .setName(name)
          .setFilterConfig(modelArmorFilter)
          .build();

      // Create a field mask to specify which fields to update.
      // Ref: https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
      FieldMask updateMask = FieldMask.newBuilder()
          .addPaths("filter_config.rai_settings")
          .build();

      UpdateTemplateRequest request = UpdateTemplateRequest.newBuilder()
          .setTemplate(template)
          .setUpdateMask(updateMask)
          .build();

      Template updatedTemplate = client.updateTemplate(request);
      System.out.println("Updated template: " + updatedTemplate.getName());

      return updatedTemplate;
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'your-project-id';
// const locationId = 'us-central1';
// const templateId = 'template-id';

const modelarmor = require('@google-cloud/modelarmor');
const {ModelArmorClient} = modelarmor.v1;
const {protos} = modelarmor;

const DetectionConfidenceLevel =
  protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel;
const PiAndJailbreakFilterEnforcement =
  protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings
    .PiAndJailbreakFilterEnforcement;
const MaliciousUriFilterEnforcement =
  protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings
    .MaliciousUriFilterEnforcement;

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

// Build the updated template configuration
const updatedTemplate = {
  name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`,
  filterConfig: {
    piAndJailbreakFilterSettings: {
      filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED,
      confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE,
    },
    maliciousUriFilterSettings: {
      filterEnforcement: MaliciousUriFilterEnforcement.ENABLED,
    },
  },
};

const request = {
  template: updatedTemplate,
};

const [response] = await client.updateTemplate(request);
return response;

PHP

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

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\DetectionConfidenceLevel;
use Google\Cloud\ModelArmor\V1\PiAndJailbreakFilterSettings\PiAndJailbreakFilterEnforcement;
use Google\Cloud\ModelArmor\V1\PiAndJailbreakFilterSettings;
use Google\Cloud\ModelArmor\V1\MaliciousUriFilterSettings;
use Google\Cloud\ModelArmor\V1\UpdateTemplateRequest;
use Google\Cloud\ModelArmor\V1\FilterConfig;
use Google\Cloud\ModelArmor\V1\Template;

/**
 * Updates a Model Armor template with the specified configuration.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function update_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);

    $templateFilterConfig = (new FilterConfig())
        ->setPiAndJailbreakFilterSettings(
            (new PiAndJailbreakFilterSettings())
                ->setFilterEnforcement(PiAndJailbreakFilterEnforcement::ENABLED)
                ->setConfidenceLevel(DetectionConfidenceLevel::LOW_AND_ABOVE)
        )
        ->setMaliciousUriFilterSettings(
            (new MaliciousUriFilterSettings())
                ->setFilterEnforcement(PiAndJailbreakFilterEnforcement::ENABLED)
        );

    $template = (new Template())
        ->setFilterConfig($templateFilterConfig)
        ->setName("projects/$projectId/locations/$locationId/templates/$templateId");

    $updateTemplateRequest = (new UpdateTemplateRequest())->setTemplate($template);

    $response = $client->updateTemplate($updateTemplateRequest);

    printf('Template updated: %s' . PHP_EOL, $response->getName());
}

Python

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


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Build the Model Armor template 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
updated_template = modelarmor_v1.Template(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
    filter_config=modelarmor_v1.FilterConfig(
        pi_and_jailbreak_filter_settings=modelarmor_v1.PiAndJailbreakFilterSettings(
            filter_enforcement=modelarmor_v1.PiAndJailbreakFilterSettings.PiAndJailbreakFilterEnforcement.ENABLED,
            confidence_level=modelarmor_v1.DetectionConfidenceLevel.LOW_AND_ABOVE,
        ),
        malicious_uri_filter_settings=modelarmor_v1.MaliciousUriFilterSettings(
            filter_enforcement=modelarmor_v1.MaliciousUriFilterSettings.MaliciousUriFilterEnforcement.ENABLED,
        ),
    ),
)

# Initialize request argument(s).
request = modelarmor_v1.UpdateTemplateRequest(template=updated_template)

# Update the template.
response = client.update_template(request=request)

# Print the updated filters in the template.
print(response.filter_config)

删除 Model Armor 模板

如果模板不再使用、被新模板取代或安全政策发生变化,请删除该模板。

控制台

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

    前往 Model Armor

  2. 确认您正在查看的是已启用 Model Armor 的项目。系统会显示 Model Armor 页面,其中列出了为您的组织创建的模板。

  3. 点击要从列表中删除的模板。系统会显示模板详细信息页面。

  4. 点击删除。此时会显示一个确认对话框。

  5. 输入模板名称以确认删除,然后点击删除。

gcloud

运行以下命令:

gcloud model-armor templates delete TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

替换以下内容:

  • LOCATION:模板所在的位置。
  • TEMPLATE_ID:模板的 ID。
  • PROJECT_ID:模板所属项目的 ID。

REST

运行以下命令:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)"  \
  "https://modelarmor.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

替换以下内容:

  • PROJECT_ID:模板所属项目的 ID。
  • LOCATION:模板所在的位置。
  • TEMPLATE_ID:模板的 ID。

C#

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

using Google.Cloud.ModelArmor.V1;
using System;

public class DeleteTemplateSample
{
    public void DeleteTemplate(
        string projectId = "my-project",
        string locationId = "us-central1",
        string templateId = "my-template"
    )
    {
        ModelArmorClient client = new ModelArmorClientBuilder
        {
            Endpoint = $"modelarmor.{locationId}.rep.googleapis.com",
        }.Build();

        DeleteTemplateRequest request = new DeleteTemplateRequest
        {
            TemplateName = TemplateName.FromProjectLocationTemplate(projectId, locationId, templateId),
        };

        client.DeleteTemplate(request);
        Console.WriteLine($"Deleted template: {templateId}");
    }
}

Go

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


import (
	"context"
	"fmt"
	"io"

	modelarmor "cloud.google.com/go/modelarmor/apiv1"
	modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb"
	"google.golang.org/api/option"
)

// deleteModelArmorTemplate method deletes a Model Armor template with the provided ID.
//
// w io.Writer: The writer to use for logging.
// projectID string: The ID of the Google Cloud project.
// locationID string: The ID of the Google Cloud location.
// templateID string: The ID of the template to delete.
func deleteModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error {
	ctx := context.Background()

	// Create option 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 for project %s, location %s: %w", projectID, locationID, err)
	}
	defer client.Close()

	// Build the request for deleting the template.
	req := &modelarmorpb.DeleteTemplateRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID),
	}

	// Delete the template.
	if err := client.DeleteTemplate(ctx, req); err != nil {
		return fmt.Errorf("failed to delete template: %w", err)
	}

	// Print the success message using fmt.Fprintf with the io.Writer.
	fmt.Fprintf(w, "Successfully deleted Model Armor template: %s\n", req.Name)

	return err
}

Java

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


import com.google.cloud.modelarmor.v1.ModelArmorClient;
import com.google.cloud.modelarmor.v1.ModelArmorSettings;
import com.google.cloud.modelarmor.v1.TemplateName;
import java.io.IOException;

public class DeleteTemplate {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Specify the Google Project ID.
    String projectId = "your-project-id";
    // Specify the location ID. For example, us-central1.
    String locationId = "your-location-id";
    // Specify the template ID.
    String templateId = "your-template-id";

    deleteTemplate(projectId, locationId, templateId);
  }

  public static void deleteTemplate(String projectId, String locationId, String templateId)
      throws IOException {

    // Construct the API endpoint URL.
    String apiEndpoint = String.format("modelarmor.%s.rep.googleapis.com:443", locationId);
    ModelArmorSettings modelArmorSettings = ModelArmorSettings.newBuilder().setEndpoint(apiEndpoint)
        .build();

    // Initialize the 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(modelArmorSettings)) {
      String name = TemplateName.of(projectId, locationId, templateId).toString();

      // Note: Ensure that the template you are deleting isn't used by any models.
      client.deleteTemplate(name);
      System.out.println("Deleted template: " + name);
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'us-central1';
// const templateId = 'my-template';

const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`;

// Imports the Model Armor library
const {ModelArmorClient} = require('@google-cloud/modelarmor');

// Instantiates a client
const client = new ModelArmorClient({
  apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`,
});

const response = await client.deleteTemplate({
  name: name,
});
return response;

PHP

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

use Google\Cloud\ModelArmor\V1\Client\ModelArmorClient;
use Google\Cloud\ModelArmor\V1\DeleteTemplateRequest;

/**
 * Deletes a Model Armor template.
 *
 * @param string $projectId The ID of the project (e.g. 'my-project').
 * @param string $locationId The ID of the location (e.g. 'us-central1').
 * @param string $templateId The ID of the template (e.g. 'my-template').
 */
function delete_template(string $projectId, string $locationId, string $templateId): void
{
    $options = ['apiEndpoint' => "modelarmor.$locationId.rep.googleapis.com"];
    $client = new ModelArmorClient($options);
    $templateName = sprintf('projects/%s/locations/%s/templates/%s', $projectId, $locationId, $templateId);

    $dltTemplateRequest = (new DeleteTemplateRequest())->setName($templateName);

    $client->deleteTemplate($dltTemplateRequest);

    printf('Deleted template: %s' . PHP_EOL, $templateName);
}

Python

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


from google.api_core.client_options import ClientOptions
from google.cloud import modelarmor_v1

# TODO(Developer): Uncomment these variables.
# project_id = "YOUR_PROJECT_ID"
# location_id = "us-central1"
# template_id = "template_id"

# Create the Model Armor client.
client = modelarmor_v1.ModelArmorClient(
    transport="rest",
    client_options=ClientOptions(
        api_endpoint=f"modelarmor.{location_id}.rep.googleapis.com"
    ),
)

# Build the request for deleting the template.
request = modelarmor_v1.DeleteTemplateRequest(
    name=f"projects/{project_id}/locations/{location_id}/templates/{template_id}",
)

# Delete the template.
client.delete_template(request=request)

模板元数据

Model Armor 模板元数据有助于您配置 Model Armor 的行为,包括安全检查处理、错误处理以及日志记录行为。

Model Armor 模板元数据包括以下字段:

元数据 类型 默认值 说明
enforcement_type 枚举 INSPECT_AND_BLOCK

定义强制执行类型。请使用以下某个值:

  • INSPECT_ONLY:Model Armor 会检查违反配置设置的请求,但不会屏蔽这些请求。
  • INSPECT_AND_BLOCK:Model Armor 会屏蔽违反配置设置的请求。
log_template_operations 布尔值 False 启用模板操作的日志记录。
log_sanitize_operations 布尔值 False 启用清理操作的日志记录。
multiLanguageDetection 布尔值 False 启用多语言检测。
模态(预览版) 枚举 空 确定是扫描文字、图片还是两者都扫描。如果将此字段留空,则仅扫描文本。

请使用以下某个值:

data_residency_compliant 布尔值 True

指示模板是否受严格的数据驻留合规性(管辖区内处理)约束。

  • True:停用模板所在区域管辖范围内不支持的本地功能,以防止数据离开本地管辖范围。
  • False:停用数据驻留合规性检查,并允许在管辖区内本地没有相应功能时,跨管辖区路由数据。

如需详细了解此字段,请参阅本文档中的设置数据驻留合规性。

如需详细了解模板的数据驻留,请参阅针对模板强制执行数据驻留。

后续步骤