创建和管理 Model Armor 模板

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

准备工作

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

获取所需的权限

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

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

启用 API

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

控制台

  1. Enable the Model Armor API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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。

    创建 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. (可选)添加标签。标签采用键值对形式,可用于对相关模板进行分组。

    7. 检测部分,配置检测设置

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

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

    10. 可选:在配置日志记录部分,选择要为其配置日志记录的操作。

    11. 可选:选择启用多语言支持,以使用多语言检测设置

    12. 点击创建

    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=LOW_AND_ABOVE \
         --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:模板的过滤条件配置。
    • PROJECT_ID:模板所属项目的 ID。
    • TEMPLATE_ID:要创建的模板的 ID。
    • LOCATION:模板的位置。

    以下示例展示了一个 Model Armor 模板配置。在此示例中,Responsible AI 过滤条件针对仇恨言论、骚扰、危险内容和露骨色情内容配置了不同的置信度。此外,启用了提示注入和越狱检测过滤条件并将其置信度配置为 LOW_AND_ABOVE,这意味着,任何可能性为“低”“中等”或“高”的内容都将被标记。还启用了恶意 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": "LOW_AND_ABOVE"
      },
      "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_ID/templates?template_id=TEMPLATE_ID"
    

    如需创建启用了多语言检测的 Model Armor 模板,您需要在命令中传递 TEMPLATE_CONFIG 参数。 此参数定义了语言检测设置的配置。

    使用以下命令创建新的 Model Armor 模板,并启用多语言检测。

    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"
    

    以下示例展示了一个启用了多语言检测的 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": "LOW_AND_ABOVE"
      },
      "maliciousUriFilterSettings": {
        "filterEnforcement": "ENABLED"
      }
     },
     "templateMetadata": {
        "multiLanguageDetection": {
          "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_ID/templates?template_id=TEMPLATE_ID"
    

    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 对提示和回答执行的具体检查。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/projectName/locations/locationID/inspectTemplates/templateName

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

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

    设置置信度

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

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

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

    如需针对模板启用全面的日志记录,请参阅 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_ID.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

    替换以下内容:

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

    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 TEMPLATE_ID --project=PROJECT_ID --location=LOCATION

    替换以下内容:

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

    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:要更新的字段,例如 filterConfigfilterConfig.piAndJailbreakFilterSettings。如果将此字段留空,则系统会更新整个过滤条件配置。

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

    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_ID.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/templates/TEMPLATE_ID"

    替换以下内容:

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

    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 模板元数据包括以下字段:

    元数据 类型 说明
    multiLanguageDetection 布尔值 启用多语言检测。
    enforcement_type 枚举

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

    • INSPECT_ONLY:检查违反配置设置的请求,但不阻止这些请求。
    • INSPECT_AND_BLOCK:它会阻止违反配置设置的请求。
    log_template_operations 布尔值 启用模板操作的日志记录。
    log_sanitize_operations 布尔值 启用清理操作的日志记录。

    后续步骤