建立及管理範本

您可以使用 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 管理員 (roles/modelarmor.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

啟用 API

您必須先啟用 Model Armor API,才能使用 Model Armor。

控制台

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

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    啟用 API

  2. 選取要啟用 Model Armor 的專案。

gcloud

開始之前,請按照下列步驟,搭配使用 Google Cloud CLI 和 Model Armor API:

  1. 在 Google Cloud 控制台啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

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

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (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」頁面,點選「建立範本」。「Create Template」(建立範本) 頁面隨即顯示。

  4. 指定範本 ID。範本 ID 可以包含英文字母、數字、底線或連字號。長度不得超過 63 個字元,也不得包含空格或以連字號開頭。

  5. 在「Location type」(位置類型) 部分,選取要執行 Model Armor 作業的區域或多區域。位置一經設定即無法變更。

  6. 選用:在「Data residency compliance」(資料落地法規遵循) 部分,選擇是否啟用資料落地強制執行功能。根據預設,如果 Model Armor 功能並非託管於所選位置,系統會停用該功能,以免資料跨越其他管轄區。本節會列出已停用的功能。

    如要啟用受資料落地強制執行限制的功能,請清除「Enforce data residency」(強制執行資料落地) 選項。如要清除這個選項,請先停用預設組織政策限制。如需操作說明,請參閱「停用資料落地組織政策限制」。這項操作允許跨管轄區轉送資料。

  7. 選用:在「Labels」(標籤) 區段中,新增要用於將相關範本分組的鍵/值組合。

  8. 在「Filter version」(篩選器版本) 專區,選取篩選器版本號碼或篩選器版本別名。

  9. 選取模態,指定要篩選文字、圖片或兩者。

  10. 在「偵測」部分,設定偵測設定。

  11. 選用:如果選取 Sensitive Data Protection 偵測功能,則須調整 Sensitive Data Protection 設定。

  12. 在「Responsible AI」(負責任的 AI) 專區,設定各個內容篩選器的信心水準。

  13. (選用) 展開「Additional configurations (optional)」(其他設定 (選用)) 區段,然後調整下列任一設定:

    • 在「Configure logging」(設定記錄) 部分,選取要設定記錄的作業。
    • 在「Multi-language support」(多語言支援) 專區,選取「Enable Multi-language support」(啟用多語言支援),即可使用多語言偵測功能。
    • 在「Enforcement mode」(強制執行模式) 部分,選取強制執行類型。
  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),您可以在其中定義要偵測的內容。在這個範例中,負責任 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 功能並非託管於範本區域涵蓋的管轄區,就會停用。強制執行資料落地法規遵循,可防止資料離開管轄區。

如果範本優先考量全面的安全性篩選,而非嚴格的資料落地,您可以停用使用中和傳輸中資料的資料落地強制執行功能。在範本中停用資料落地法規遵循功能,即表示允許跨管轄區轉送資料。也就是說,如果範本管轄區不支援特定功能,Model Armor 可能會將要求轉送至其他管轄區。無論這個選項的狀態為何,靜態資料都會遵守資料落地規定。

停用資料落地法規遵循功能後,除了圖像模態仍僅限於 us 和 eu 多區域外,所有 Model Armor 功能都會啟用。

停用資料落地組織政策限制

Model Armor 預設會強制執行要求 Model Armor 範本資料落地法規遵循 (constraints/modelarmor.managed.requireTemplateDataResidencyCompliance) 代管組織政策服務限制。強制執行這項限制時,如果將 data_residency_compliant 設為 false,建立或更新範本就會失敗。現有範本和清理提示與回覆的要求不受影響,除非您在 data_residency_compliant 仍為 false 時更新範本。詳情請參閱「必須遵守範本資料落地規定」。

如要停用範本的資料落地強制執行功能,請完成下列步驟:

  1. 請要求組織政策管理員 (roles/orgpolicy.policyAdmin) 停用專案、資料夾或組織的 constraints/modelarmor.managed.requireTemplateDataResidencyCompliance 限制。如需操作說明,請參閱「在組織政策中使用代管限制」。
  2. 建立或更新範本時,請在 Google Cloud 控制台中清除「Enforce data residency」(強制執行資料落地) 選項,或使用 Model Armor API 將 data_residency_compliant 設為 false。

選取篩選器版本

Model Armor 篩選器版本可兼顧正式版工作負載的穩定性,以及存取更新後的威脅偵測模型。您可以在範本層級設定篩選器版本。篩選器版本適用於該範本中的所有篩選器,但「不使用篩選器版本的篩選器」中列出的篩選器除外。詳情請參閱「設定範本的篩選器版本」。

選取模態

使用模態指定是否要掃描下列項目:

  • 全部:掃描文字和圖片。
  • 特定模態:
    • 文字:掃描支援檔案格式中的文字字串和文字嵌入。
    • 圖片:掃描圖片。

詳情請參閱「圖片篩選」和「清理含有圖片的提示」。

設定偵測

偵測是指 Model Armor 對提示詞和回覆執行的特定檢查。Model Armor 提供彈性的偵測設定系統,可讓您為 AI 應用程式量身打造防護等級。您可以在建立範本時設定偵測功能。Model Armor 會對提示詞和回覆執行下列偵測檢查:

  • 惡意網址偵測:找出用於危害使用者或系統的網址。這些網址可能會通往網路釣魚網站、誘導下載惡意軟體或進行其他網路攻擊。詳情請參閱「惡意網址偵測」。

  • 提示詞注入和越獄偵測:偵測提示詞中的惡意內容和越獄嘗試。建議您將可信度設為「High」(高),盡量減少偽陽性,並確保偵測行為一致。即使將可信度設為「High」(高) 可降低偽陽率,但在極少數情況下,您仍可能看到偽陽性。詳情請參閱「提示詞注入和越獄偵測」。

  • 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 中定義的範本檢查或去識別化機密資料。

如果選取「Advanced」(進階) 模式,請指定下列參數:

  • 檢查範本:用於儲存檢查掃描工作設定資訊的範本,包括要使用的預先定義或自訂 infoType 偵測工具。請按照下列格式輸入範本名稱: projects/PROJECT_ID/locations/LOCATION/inspectTemplates/TEMPLATE_ID

  • 選用:去識別化範本:用於儲存去識別化工作設定資訊的範本,包括 infoType 和結構化資料集轉換。請按照下列格式輸入去識別化範本的 ID:projects/PROJECT_ID/locations/LOCATION/deidentifyTemplates/TEMPLATE_ID

確認 Sensitive Data Protection 中有檢查範本和去識別化範本。如果範本位於其他專案,則必須為 Model Armor 服務代理授予該專案的 DLP 使用者角色 (roles/dlp.user) 和 DLP 讀取者角色 (roles/dlp.reader)。

Model Armor 處理要求的方式,取決於您是否只指定檢查範本,或同時指定檢查和去識別化範本:

  • 僅檢查範本:Model Armor 會在內容中搜尋檢查範本指定的 infoType,並回報結果。

  • 檢查和去識別化範本:Model Armor 會將檢查和去識別化範本中指定的 infoType 去識別化。

Model Armor 只會對您在檢查和去識別化範本中指定的 infoType 進行去識別化。舉例來說,如果您未在檢查和去識別化範本中指定 CREDIT_CARD_NUMBER,Model Armor 就不會標記或去識別化提示和回覆中傳遞的任何信用卡號碼。

設定信賴水準

信心水準代表偵測到的結果符合某個內容篩選器類型的可能性。您可以為每個內容篩選器設定信心水準。可能的值如下:

  • 無:未偵測到任何內容。
  • 低與以上:偵測到信心水準為低、中或高的內容。
  • 中等以上:偵測到內容,且可信度為中等或高。
  • 高:偵測到內容,且可信度高。

如需較嚴格的設定,請將信心水準設為「Low and above」,就能偵測到屬於該篩選器內容類型的多數內容。

如要啟用範本的完整記錄功能,請參閱「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. 在清單中,按一下要更新的範本。系統隨即會顯示「Template details」(範本詳細資料) 頁面。

  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. 在清單中點選要刪除的範本。系統隨即會顯示「Template details」(範本詳細資料) 頁面。

  4. 按一下「Delete」(刪除)。系統隨即會顯示確認對話方塊。

  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 布林值 否 啟用範本作業記錄功能。
log_sanitize_operations 布林值 否 啟用清理作業記錄功能。
multiLanguageDetection 布林值 否 啟用多語言偵測功能。
模態 (預先發布版) 列舉 空白 決定是否要掃描文字、圖片或兩者。如果將這個欄位留空,系統只會掃描文字。

請使用下列其中一個值:

  • TEXT:掃描支援檔案格式中的文字字串和內嵌文字。
  • IMAGE:掃描圖片。
data_residency_compliant 布林值 是

指出範本是否須遵守嚴格的資料落地法規 (在管轄區內處理)。

  • True:停用範本區域管轄範圍內不支援的功能,防止資料離開當地管轄範圍。
  • False:停用資料落地法規遵循檢查,並在管轄區不提供某項功能時,允許跨管轄區轉送資料。

如要進一步瞭解這個欄位,請參閱本文的「設定資料落地法規遵循」一節。

如要進一步瞭解範本的資料落地,請參閱「範本的資料落地強制執行」。

後續步驟